Search code examples
javaimageswingbuttonclickable

Java Swing : best way to set background image clickable


I try to find the best way to make an image clickable with different action depending on the area you click. For now, my window display an EFTPOS (image found on google image) using :

 getContentPane().add(new JPanelBackground("./img/background.png", "./img/eftposAboveBackground.png", this.getWidth(), this.getHeight()));

Now, I would like to click on every EFTPOS's buttons. I was thinking of create some transparent buttons at the buttons's positions but :

  • First, I don't want to use an absolute layer
  • Second, the Swing GUI design editor (Netbeans) doesn't display my background image since I used the code above.

I'm pretty sure there is another way than setting my eftpos on the background, maybe using the ImageIcon class..

Any help would be greatly appreciated!


Solution

    1. You can to create an ArrayList of Rectangles (or Shapes) to represent the area of each button on the image.
    2. You need to add a MouseListener to the image.
    3. In the mousePressed() event you need to iterate through all the Rectangle in the ArrayList using the Rectangle.contains(mouse point) method to see if the user clicked in a Rectangle.
    4. When you find the Rectangle that was clicked you execute your custom code.