1

How can I to add mouse listener to image or imageIcon in Java?

Here is my code. I want to do anything with imageIcon after mouse click on it.

public class Bubbles extends JPanel {
    
    public static final int LINE_OUT = 440;
    int x = 20;
    int y = 50;
    int v = 4;
    
    Image img = new ImageIcon("res/lop.png").getImage();
    BackSide back;
    

    public Bubbles(int x, int y, int v, BackSide back) {
        this.x = x;
        this.y = y;
        this.v = v;
        this.back = back;
        setFocusable(true);
        
    }
    
 
    public void move() {
        if (y >= 440) {
            y = 0;
        } else {
            y += v;
        }
    }

}
Bashir
  • 2,057
  • 5
  • 19
  • 44
Ashot
  • 1,229
  • 1
  • 12
  • 13
  • You can't, but you can add it to a JLabel or to the container that the image is painted to, but you will need to check if the mouse was actioned within the bounds of the image based on where it is within the container. Take a look at [How to use MouseListeners](http://docs.oracle.com/javase/tutorial/uiswing/events/mouselistener.html) – MadProgrammer Feb 18 '14 at 20:19
  • give me advice please is there any other ways to paint an image and relize onclick on it ? without using JLable or any checkings? – Ashot Feb 18 '14 at 20:28

3 Answers3

2

What you can do is that you can use a JLabel and set the ImageIcon to it. make the JLabel transparent by using setOpaque(false). Then, add listener to it and do whatever you want to do :)

An SO User
  • 24,612
  • 35
  • 133
  • 221
  • JLabel is transparent by default – MadProgrammer Feb 18 '14 at 20:49
  • JLabel lable = new JLabel(); lable.add(new Bubbles(10, 10, 10, null)); lable.setOpaque(false); lable.addMouseListener(new MouseAdapter() { public void mouseClicked(MouseEvent e ){ System.out.println("mouseClicked"); } }); – Ashot Feb 18 '14 at 20:52
  • @Ashot Don't add the "Bubbles" to the label, set the labels icon property to whatever image you want to use. – MadProgrammer Feb 18 '14 at 21:00
1

If you dont want to use JLabel you can paint the image onto panel by overriding paintComponent method.Then you can add listener to your JPanel.I woud strongly recomend you to use JLabel but if you still preffer the other way,here you can see some example how to do it. How to set background image in Java?.

Icon icon = new ImageIcon("give path of the image");
JLabel lb = new JLabel(icon);
//now set listener for label.
lb.addMouseListener(new MouseAdapter() 
{
    @Override
    public void mouseClicked(MouseEvent e) 
    {
        //statement             
    }
});
Community
  • 1
  • 1
Tomas Bisciak
  • 2,801
  • 5
  • 33
  • 57
  • 1
    " without using JLable or any checkings?". I do not see how that can be done. In my case the OP will have to deal with `JLabel` and in your case with checking the bounds – An SO User Feb 18 '14 at 20:36
  • I think label is way to go. – Tomas Bisciak Feb 18 '14 at 20:39
  • JLabel lable = new JLabel(); lable.add(new Bubbles(10, 10, 10, null)); lable.setOpaque(false); lable.addMouseListener(new MouseAdapter() { public void mouseClicked(MouseEvent e ){ System.out.println("mouseClicked"); } }); – Ashot Feb 18 '14 at 20:42
1

The simplest solution would be to use a JLabel and set it's icon property. See How to use labels for more details.

If you must paint the image yourself (ie, you want to apply effects or perform animation across a container), then you need to add the MouseListener to the container which is rendering the image and test to see if the mouse event occurred within the context of the image based on it's location and size.

import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.EventQueue;
import java.awt.Graphics;
import java.awt.Point;
import java.awt.Rectangle;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.imageio.ImageIO;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;

public class ImageMouseListener {

    public static void main(String[] args) {
        new ImageMouseListener();
    }

    public ImageMouseListener() {
        EventQueue.invokeLater(new Runnable() {
            @Override
            public void run() {
                try {
                    UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
                } catch (ClassNotFoundException ex) {
                } catch (InstantiationException ex) {
                } catch (IllegalAccessException ex) {
                } catch (UnsupportedLookAndFeelException ex) {
                }

                JFrame frame = new JFrame("Test");
                frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
                frame.setLayout(new BorderLayout());
                frame.add(new ImagePane());
                frame.pack();
                frame.setLocationRelativeTo(null);
                frame.setVisible(true);
            }
        });
    }

    public class ImagePane extends JPanel {

        private BufferedImage img;
        private Point imgPoint;

        public ImagePane() {
            try {
                img = ImageIO.read(...);
                imgPoint = new Point(100, 100);
            } catch (IOException ex) {
                ex.printStackTrace();
            }

            addMouseListener(new MouseAdapter() {

                @Override
                public void mouseClicked(MouseEvent e) {
                    if (img != null && imgPoint != null) {
                        Point me = e.getPoint();
                        Rectangle bounds = new Rectangle(imgPoint, new Dimension(img.getWidth(), img.getHeight()));
                        if (bounds.contains(me)) {
                            System.out.println("I was clicked!");
                        }
                    }
                }

            });
        }

        @Override
        public Dimension getPreferredSize() {
            return new Dimension(400, 400);
        }

        @Override
        protected void paintComponent(Graphics g) {
            super.paintComponent(g);
            if (img != null && imgPoint != null) {
                g.drawImage(img, imgPoint.x, imgPoint.y, this);
            }
        }

    }

}

Take a look at Performing Custom Painting and How to use Mouse Listeners for more details

MadProgrammer
  • 343,457
  • 22
  • 230
  • 366