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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/7296438/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-30 19:26:44  来源:igfitidea点击:

Adding a mouse listener to a rectangle in java

javaswinglistenermouselistener

提问by Sam

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){
    }
}

回答by Perception

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 Rectangle2Dwhen you get a chance.

有机会时查看Rectangle2D的文档。