Adding a mouse listener to a rectangle in java

Sam picture Sam · Sep 4, 2011 · Viewed 10.9k times · Source

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

Answer

Perception picture Perception · Sep 4, 2011

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.