user3185161
user3185161

Reputation: 53

Java MouseListener on graphics elements

g.drawString("String",50,50);

I would like to add MouseListener to this graphic element.

public void mouseEntered(MouseEvent e) {
   saySomething("Mouse entered", e);
}

public void mouseExited(MouseEvent e) {
   saySomething("Mouse exited", e);
}

is there any straightforward way to do it, or I have manually find element position?

thanks

Upvotes: 1

Views: 97

Answers (1)

Hovercraft Full Of Eels
Hovercraft Full Of Eels

Reputation: 285460

Suggestions:

  • To move a String around, you could put it into a JLabel and then move the JLabel via a MouseListener.
  • Alternatively, you could simply move the drawn String, one drawn in a paintComponent method, using a MouseListener/MouseMotionListener, but then you still will need to recognize when the String has been clicked on, something that is far easier to do with a JLabel.
  • To move a graphic, if it's an image, you could create an ImageIcon with it, put it into an JLabel and do the same as with the String/JLabel above.
  • or you could draw it as a BufferedImage sprite in your paintComponent method, and move it's drawn location in the paintComponent method via your MouseAdapter, but again, the difficult part will be recognizing when the mouse has clicked on it. Since you know its dimensions and location, this shouldn't be hard to do.
  • or if it's a Graphics2D drawing, you could create a Shape-implementing object, and move the Shape.

For example please look at my previous answers with sample code in the links below:

Upvotes: 3

Related Questions