graphics - simply print a component in java with a diagonal line -
i'm beginner trying print basic window line 0,0,500,500. i've tried validate, dolayout, printall. unsure g in printall. can't find anywhere says is. ??
package helloprogram; import java.awt.graphics.*; /** * * @author jglvn */ class component{ void setsize(int width, int height){ } void setbounds(int x, int y){ } void drawline(int x1, int y1, int x2, int y2){ } void setbackground(int r, int g, int b){ } void validate(){ } void dolayout(){ } void printall(graphics g){ } } public class helloprogram { public static void main(string[] args) { component canvas = new component(); canvas.setsize(500, 500); canvas.setbounds(300, 300); canvas.setbackground(153,153,153); canvas.drawline(0, 0, 500, 500); canvas.dolayout(); canvas.validate(); canvas.printall(g); } }
it seams want draw line in frame. if case, should go container jpanel
. want paint
on panel, should override paint
method:
here sample code:
import java.awt.graphics; import java.awt.graphics2d; import java.awt.point; import javax.swing.jframe; import javax.swing.jpanel; public class drawlinepanel extends jpanel{ private static final int frame_height = 600; private static final int frame_width = 600; public static void main(string[] args) { jframe f = new jframe(); f.setdefaultcloseoperation(jframe.exit_on_close); f.setsize(frame_width, frame_height); f.add(new drawlinepanel(new point(100, 100), new point(500, 500))); f.setvisible(true); } private point pointa; private point pointb; public drawlinepanel(point pointa, point pointb) { this.pointa = pointa; this.pointb = pointb; } @override public void paint(graphics g) { super.paintcomponents(g); // graphics2d g2 = (graphics2d) g; g2.drawline(pointa.x, pointa.y, pointb.x, pointb.y); } }
some advice:
don't make frame visible before graphics.
don't mix
component
sub classesframe
orpanel
jcomponent
sub classesjframe
orjpanel
.
hope helpful.
Comments
Post a Comment