开发者

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;
    g开发者_JAVA技巧1.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.

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

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜