java - mousePressed method won't respond -
i'm trying basic: write program draw line on frame between 2 points: point mouse pressed on , point mouse released on.
i have these classes:
import java.awt.graphics; public class line implements drawable{ private int x1,x2,y1,y2; public line( int x1,int x2,int y1,int y2){ this.x1=x1; this.x2=x2; this.y1=y1; this.y2=y2; } public void draw(graphics g){ g.drawline(x1, y1, x2, y2); } }
import java.awt.graphics; public interface drawable { public void draw(graphics g); }
import java.awt.graphics; import java.awt.point; import java.awt.event.mouseadapter; import java.awt.event.mouseevent; import java.util.arraylist; import javax.swing.jpanel; @suppresswarnings("serial") public class linepanel extends jpanel { arraylist<line> lines = new arraylist<line>(); public linepanel() { addmouselistener(new mouseadapter() { point p1, p2; @override public void mousepressed(mouseevent e) { p1 = e.getpoint(); system.out.println("pressed"); } @override public void mouseclicked(mouseevent e) { // todo auto-generated method stub system.out.println("clicked"); } @override public void mousereleased(mouseevent e) { p2 = e.getpoint(); lines.add(new line(p1.x, p1.y, p2.x, p2.y)); } }); system.out.println("after add mouselistener"); } public void paintcomponent(graphics g) { super.paintcomponent(g); (line l : lines) { l.draw(g); } } }
import javax.swing.jframe; public class launchlinesgui { public static void main(string[] args) { // todo auto-generated method stub jframe frame=new jframe(); frame.setsize(500, 500); frame.setvisible(true); linepanel panel=new linepanel(); frame.add(panel); } }
the problem when press themouse on place on frame no response , system.out.println
's of mousepressed
methods not printed on console. doing wrong?
it job of layout manager determine size/location of components added frame.
the reason panel has size of (0, 0) because add panel frame after make frame visible layout manager never invoked.
also, should not set size of frame should let layout manager job invoking pack() method on frame.
the proper order of code should be:
linepanel panel=new linepanel(); jframe frame=new jframe(); frame.add(panel); //frame.setsize(500, 500); frame.pack(); frame.setvisible(true);
also when custom painting panel responsible determining own size, need override getpreferredsize()
method of panel:
@override public dimension getpreferredsize() { return new dimension(500, 500); }
now layout manager can job properly.
Comments
Post a Comment