I was trying to build a basic program in java which creates a window with a JPanel,and when user clicks on the JPanel an image is displayed but when run the app and click on the JPanel nothing shows up...
Here goes the code...
//driver.java
import javax.swing.JFrame;
public class driver {
public static void main(String[] args) {
Gui obj = new Gui();
obj.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
obj.setSize(400, 400);
obj.setVisible(true);
}
}
//GUI.java
import javax.swing.*;
import java.awt.Color;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
public class Gui extends JFrame{
public JPanel panel;
public ImageIcon img;
public Gui(){
panel = new JPanel();
panel.setBackground(Color.DARK_GRAY);
img = new ImageIcon("cross.png");
panel.addMouseListener(new MouseAdapter(){
public void mouseReleased(MouseEvent e){
panel.add(new JLabel(img));
System.out.println("Mouse Click detected");
}}
);
add(panel);
}
}
//Updated Gui.java
import javax.swing.*;
import java.awt.*;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
public class Gui extends JFrame{
public JPanel panel;
public ImageIcon img;
public final JLabel label;
public Gui(){
panel = new JPanel();
label = new JLabel();
panel.add(label);
img = new ImageIcon(getClass().getResource("res/cross.png"));
panel.addMouseListener(new MouseAdapter(){
public void mouseReleased(MouseEvent e){
label.setIcon(img);
System.out.println("Mouse Click detected");
}}
);
add(panel);
}
}
Note: here is how my project is organised