如果我创建一个继承自JComponent的新类( paintComponent(Graphics )方法),通过使用g绘制一个圆圈,我应该修改什么才能使MouseListener只在组件的边界内单击时触发?
因为我在组件的构造函数中添加了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);
}
}发布于 2014-12-05 21:47:03
您的鼠标监听器工作正常,因为它只在JComponent的范围内工作。要向自己证明这一点,请在组件周围设置一个边框,以查看其实际涵盖的内容:
public Node(int xx, int yy, int r) {
//. ....
setBorder(BorderFactory.createTitledBorder("Node"));
}要知道,您的组件正被添加到BorderLayout-使用默认(BorderLayout.CENTER)位置的容器中,因此它将填充容器。设置组件的界限(不应该做的事情)或设置组件的首选大小(也是通常应该避免的事情)并不重要。
为了节省我的钱,我会让我的节点成为一个逻辑类,一个实现形状接口的类,而不是一个扩展JComponent的类,然后每当我需要知道我的节点是否被点击时,我就可以使用该形状的contains(Point p)方法。
https://stackoverflow.com/questions/27323709
复制相似问题