swing - Java: Add MouseListener to custom JComponent -


if create new class inherits jcomponent, paintcomponent(graphics g) method override, painting circle using g, should modify in order mouselistener trigger when click inside bounds of component?

because in constructor of component added setbounds(...) , added mouselistener, fires every time click anywhere inside container in custom component , not when click inside it.

i not want check in mouseclicked() method whether event happened inside component or not, want called when click inside.

here's code:

public class node extends jcomponent {     private int x, y, radius;      public node(int xx, int yy, int r) {         x = xx;         y = yy;         radius = r;         this.setbounds(new rectangle(x - r, y - r, 2 * r, 2 * r));         setpreferredsize(new dimension(2 * r, 2 * r));     }      public void paintcomponent(graphics g) {         super.paintcomponent(g);         graphics2d gr = (graphics2d) g;         gr.setcolor(color.black);         gr.drawoval(x - radius, y - radius, 2 * radius, 2 * radius);     }      public static void main(string[] args) {         final jframe f = new jframe();         f.setsize(new dimension(500, 500));         f.setdefaultcloseoperation(jframe.exit_on_close);         final jpanel p = new jpanel();         p.setlayout(new borderlayout());         node n = new node(100, 100, 25);         n.addmouselistener(new mouseadapter() {             @override             public void mouseclicked(mouseevent e) {                 super.mouseclicked(e);                 system.out.println("clicked");             }         });         p.add(n);         f.add(p);         f.setvisible(true);     } } 

your mouse listener working correctly functioning within bounds of jcomponent. prove yourself, put border around component see covers:

public node(int xx, int yy, int r) {    //. ....    setborder(borderfactory.createtitledborder("node")); } 

understand you're component being added borderlayout-using container in default (borderlayout.center) position, , fills container. not matter set bounds of component (something should not doing) or set preferred size (also should avoided).

for money, i'd make node logical class, 1 implements shape interface, not class extends jcomponent, , use shape's contains(point p) method whenever need know if node has been clicked.


Comments

Popular posts from this blog

python - mat is not a numerical tuple : openCV error -

c# - MSAA finds controls UI Automation doesn't -

wordpress - .htaccess: RewriteRule: bad flag delimiters -