我试图用java构建一个基本程序,它创建一个带有JPanel的窗口,当用户单击JPanel时,会显示图像,但是当运行应用程序并单击JPanel时,什么也不会显示......
这是代码...
//驱动程序.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;
公共(public)类 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);
}
}
注意:这是我的项目的情况 organised
最佳答案
改变..
// ..
panel.addMouseListener(new MouseAdapter(){
public void mouseReleased(MouseEvent e){
panel.add(new JLabel(img));
System.out.println("Mouse Click detected");
}}
);
至(类似 - 未经测试):
// ..
final JLabel label = new JLabel();
panel.add(label);
panel.addMouseListener(new MouseAdapter(){
public void mouseReleased(MouseEvent e){
label.setIcon(img);
System.out.println("Mouse Click detected");
}}
);
这是 ImageViewer
中使用的基本技术,尽管它会更改 Swing Timer
上的图像,而不是单击鼠标。
当然,使用 JButton
图标比使用 JLabel
/MouseListener
更容易。 JButton
不需要任何监听器来更改图标,并且适用于鼠标和键盘 Activity 。例如。如this answer中所示.
img = new ImageIcon("cross.png");
到部署时,这些资源可能会变成 embedded-resource 。
既然如此,资源必须通过URL
而不是File
来访问。请参阅info page对于标签,对于形成 URL
的方法。
关于java - 如何在发生 mouseReleased 事件时将图像添加到 JPanel,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19075584/