简体   繁体   English

将鼠标侦听器添加到java中的矩形

[英]Adding a mouse listener to a rectangle in java

As the title suggests, I am attempting to add an action listener to a basic shape on a window. 正如标题所示,我试图在窗口上添加一个基本形状的动作监听器。 I'm wondering if this is even possible? 我想知道这是否可能? I'm getting errors when I attempt to add the listener. 我尝试添加监听器时遇到错误。

public static void main(String args[]) {
    JFrame frame = new Main();
    frame.setSize(300, 200);
    frame.setVisible(true);
    frame.setBackground(Color.BLUE);
}

Rectangle2D rect = new Rectangle2D.Double(60, 70, 120, 80);

public void paint(Graphics g) {
    Graphics2D g1 = (Graphics2D)g;
    g1.draw(rect);
    g1.setPaint(Color.yellow);
    g1.fill(rect);
}

Handlerclass handle = new Handlerclass();
rect.addMouseListener(handle);

public class Handlerclass implements MouseListener{
    public void mouseClicked (MouseEvent e){
    }
}

You can't add a mouse listener to that object. 您无法向该对象添加鼠标侦听器。 If you are trying to detect mouse clicks within it then you want to add a mouse listener to whatever Swing container you are drawing the shape in, then use one of the contains... or intersects... methods. 如果您正在尝试检测其中的鼠标单击,那么您希望将鼠标侦听器添加到正在绘制形状的任何Swing容器中,然后使用contains...intersects...方法之一。

Check out the documentation for Rectangle2D when you get a chance. 如果有机会,请查看Rectangle2D的文档。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM