-1

I want to add multiples images in a JFrame and make each of them clickable. As listeners cannot be implemented directly on image in Swing, I would have to make those many JComponent objects and implement listeners on these components.

Is this understanding correct or is there a better approach?

Andrew Thompson
  • 168,117
  • 40
  • 217
  • 433
Raj Trivedi
  • 557
  • 7
  • 18
  • *"there is better approach?"* One `ActionListener` attached to many buttons that uses `Event.getSource()` to find out which button (and therefore which image) was clicked, or a `JList` to render all the images. Here is [an example of showing images in a list](http://stackoverflow.com/a/9544652/418556).. – Andrew Thompson Sep 09 '15 at 13:37
  • You may also want to look at JButton.setIcon(new ImageIcon(...))... – ControlAltDel Sep 09 '15 at 14:21
  • I also want to make the image stretchable.Can I implement mouselistener on buttons and change the button width on mouse events? – Raj Trivedi Sep 10 '15 at 05:07

1 Answers1

0

There are a few ways you can handle this:

  1. Create a class of your own and extends it to JComponent

    class ClickableImage extends JComponent implements MouseListener
    {
        private BufferedImage img;
    
        //Include all the overridden methods for MouseListener
        @Override public void mouseClicked(MouseEvent e){
            //To do upon clicking on image;
        }
    }
    
  2. You can set the image on a JButton. Add an ActionListener for those JButton(s).

  3. Use a BufferedImage for your image, detect clicking on that image by mouse cursor position.

    class ClikableImage extends Rectangle{
        private BufferedImage img;
        //You can include any other class members you need.
    
        public MyClickableImage(int x, int y, int width, int height){
            setBounds(x, y, width, height);
        } 
    }
    

To detect click on particular image, iterate through the list of ClickableImage and check whether that ClickableImage contains the mouse cursor coordinates.

//Within a MouseListener
for(ClickableImage ci : list)
    if(ci.contains(e.getX(), e.getY()))
        clickedImage = ci;
user3437460
  • 17,253
  • 15
  • 58
  • 106
  • I also want to make the image stretchable.Can I implement mouselistener on buttons and change the button width on mouse events?Which approach will be better to handle this? – Raj Trivedi Sep 10 '15 at 05:08
  • @RajTrivedi Both approach is equally fine for stretchable image. You will need to repaint the JPanel/JComponent holding the JButton in both cases. The approach of using JButton is easier because you can make use of the available listerners such as ActionListener to detect for clicks instead of manually iterating through a list of objects. – user3437460 Sep 10 '15 at 08:14