Is there a way to add a mouse listener to an image for example when the image is clicked change the text of a label... :?:

Any help would be greatly appreciated
Thanks’ :)

How do you plan to display that image. If you are thinking of using the constructor of the JLabel:

ImageIcon img = new ImageIcon("filename");
JLabel label = new JLabel(img);

Then the JLabel class has an addMouseListener method:

ImageIcon img = new ImageIcon("filename");
JLabel label = new JLabel(img);



You can put the code that changes the text inside the method mouseClicked of the MouseListener that you implemented, for example.

How would i go around doing it with the code i got so far

import javax.swing.*;
import java.awt.*;
import javax.imageio.ImageIO;
public class ImagePanel extends JPanel
	private JLabel label = new JLabel();
	private String path;
	private Image img , img2 , img3;

	public ImagePanel(String path, String Path2 , String Path3)	 throws IOException
		img = File(path));
		img2 = File(Path2));
		img3 = File(Path3));
	//override paint method of panel
	public void paint(Graphics g)
		//draw the image
		if( img != null)
			g.drawImage(img,0,0, this);
			g.drawImage(img2,100,100, this);
			g.drawImage(img3,200,200, this);
class ImageFrame extends JFrame
	public JPanel ButtonPanel = new JPanel();
	public JPanel NorthPanel = new JPanel();
	public JFrame f = new JFrame();
	public JFrame f2 = new JFrame(); 

	public static void main(String[] args) throws IOException
			JFrame f = new JFrame();
			ImagePanel panel = new ImagePanel("C:\\...\\....png","C:\\...\\....png","C:\\...\\....png");
			f.getContentPane().add(panel , BorderLayout.CENTER);
		catch(Exception e)
			System.out.println ( "Please verify that you selected a valid image file");	

Given that code the only thing I can think of is when you click the mouse, to get the coordinates of the mouse cursor and to see if those coordinates are inside in any of those images.

Also after seeing your code, and I am not saying that it is wrong, but you'd better try to read some decent tutorials on how to create GUI using the javax.swing.
Try the sun tutorials, or search the net

This article has been dead for over six months. Start a new discussion instead.