0

I am trying to add tool tip to every image I draw on the JPanel. But each time a new Image is added, the tool tip text gets over written because I am using this.setToolTipText(text); for every image.

As seen in the image, the second traffic light image shows tool tip that reads traffic light 3 because that was the last image added.

Can someone please tell me another way to add unique tool tips? I searched for possible solutions but could not find any.

enter image description here

//Drawing the blockage on the road
g.drawImage(blockageImage, bestMatchRUnit.getX(), bestMatchRUnit.getY(), 5, 5, this); 
this.setToolTipText("Blockage: " + blockageIndex); //setting the tooltip
blockageIndex++;
Andrew Thompson
  • 168,117
  • 40
  • 217
  • 433
  • Be sure to review the preview of the message before posting it. In this case, the image disappeared when the embedded marker for it was formatted as code. – Andrew Thompson Mar 01 '15 at 00:58
  • 1) For better help sooner, post an [MCVE](http://stackoverflow.com/help/mcve) (Minimal Complete Verifiable Example) or [SSCCE](http://www.sscce.org/) (Short, Self Contained, Correct Example). 2) One way to get image(s) for an example is to hot link to images seen in [this Q&A](http://stackoverflow.com/q/19209650/418556). 3) Why not display the image(s) in a `JLabel`(s) and add the tool tip to the label? – Andrew Thompson Mar 01 '15 at 00:59
  • Don't change the state of any component from within any paint method – MadProgrammer Mar 01 '15 at 02:11

1 Answers1

0

The easiest way is to display a JLabel with an ImageIcon on your panel. Then you can add individual tool tip messages to each JLabel.

Or, the other approach is to override the getToolTipText(...) method of your JPanel. Then you will need to keep an ArrayList of a custom Object that contains two pieces of data:

  1. the Rectangle to represent the size/location of each image
  2. the tool tip for the image

Then in the getToolTipText(...) method you need to iterate through the ArrayList to find the image that contains the mouse point and the you need to return the tool tip message.

camickr
  • 321,443
  • 19
  • 166
  • 288