在Java中将鼠标侦听器添加到矩形 [英] Adding a mouse listener to a rectangle in java

查看:77
本文介绍了在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){
    }
}

推荐答案

您不能向该对象添加鼠标侦听器.如果要尝试检测其中的鼠标单击,则要将鼠标侦听器添加到要在其中绘制形状的任何Swing容器中,然后使用contains...intersects...方法之一.

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.

查看有关 Rectangle2D的文档有机会的时候.

Check out the documentation for Rectangle2D when you get a chance.

这篇关于在Java中将鼠标侦听器添加到矩形的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆