J.Olufsen
J.Olufsen

Reputation: 13915

How to create java swing Graphic object which will response to mouse clicks?

I need to draw graphic element (square) dynamically in different positions of Canvas and I need to listen to mouse clicks in order to change place of my square. How to add mouse listener to Graphics object? Do I have to use another approach?

int x = 0;
int y = 0;
 Graphics g = getGraphics(); // get Graphics context
                  g.setColor(Color.red);
          g.fillRect( x - 25, y - 15, 60, 30 );
          g.setColor(Color.black);
          g.drawRect( x - 25, y - 15, 60, 30 );
                  g.dispose();

Upvotes: 0

Views: 754

Answers (1)

Jason S
Jason S

Reputation: 189626

I'd probably use a JPanel as a child element of your larger component that forms the canvas. A JPanel, since it is a subclass of JComponent, allows you both to add a mouse listener via addMouseListener(), and to override its paintComponent() method.

If you want to move the square, just reposition the JPanel.

(for that matter, if it's a square or rectangle, you don't even need to override paintComponent, you could just accomplish this with appropriate calls to setBorder and setBackground.)


Another approach would be to use a JPanel as the entire canvas, override the paintComponent to draw whatever you like, addMouseListener on the JPanel, and then manually determine whether the mouse listener events occur within the geometry of your graphic element.

Upvotes: 1

Related Questions