2014-12-05 132 views
0

如果我创建一个继承自JComponent的新类,该JComponent的paintComponent(Graphics g)方法通过使用g绘制圆来覆盖,我应该修改哪些内容才能使MouseListener仅触发当我点击组件的边界时?Java:将MouseListener添加到自定义JComponent

因为在我的组件的构造函数中,我添加了setBounds(...),然后添加了一个MouseListener,但每次单击我的自定义组件的容器内的任何位置时它都会触发,而不仅仅是当我单击它时。

我不想在mouseClicked()方法中检查事件是否发生在我的组件内部,我只希望它在内部点击时被调用。

这里是我的代码:

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); 
    } 
} 
+0

请输入密码?我希望你的意思是你重载'paintComponent(Graphics g)',因为没有'paintMethod(Graphics g)'。 – 2014-12-05 20:03:48

+0

我对我的错误表示歉意,我已更正并添加了代码。 – user 2014-12-05 20:12:45

回答

1

你的鼠标侦听器工作正常,因为它只是你的JComponent的范围内发挥作用。要证明给自己,把边框您的组件,看看它实际上涵盖:

public Node(int xx, int yy, int r) { 
    //. .... 
    setBorder(BorderFactory.createTitledBorder("Node")); 
} 

据了解,您组件将被添加到一个BorderLayout的,使用容器默认(BorderLayout.CENTER)位置,并因此填充容器。不要紧,你设置组件的边界(你不应该这样做)或者设置它的首选大小(也是通常应该避免的)。我想让我的Node成为一个逻辑类,一个实现Shape接口,不是扩展JComponent的类,然后我可以使用Shape的contains(Point p)方法,只要我需要知道Node已被点击。

+0

我看到了问题。如果我重写getPreferredSize()方法,并使用FlowLayout一切正常。如果我想动态修改组件的大小,将使用什么样的正确布局?谢谢。 – user 2014-12-05 21:51:50