Adding a mouse listener to a rectangle in java

java, listener, mouselistener, swing

Solution

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.

Problem

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

Original source