我试图在java中构建一个基本程序,它创建一个带有JPanel的窗口,当用户单击JPanel时会显示一个图像,但是当运行应用程序并单击JPanel时没有任何显示...
这里是代码...
//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);
}
}
//更新了 Gui.java
import javax.swing.*;
import java.awt.*;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
公共类 Gui 扩展 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);
}
}
注意:这是我的项目的 组织方式