如果我创建一个继承自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);
}
}
请输入密码?我希望你的意思是你重载'paintComponent(Graphics g)',因为没有'paintMethod(Graphics g)'。 – 2014-12-05 20:03:48
我对我的错误表示歉意,我已更正并添加了代码。 – user 2014-12-05 20:12:45