对于为什么我的程序无法正常工作,我有点困惑。我正在尝试在单击按钮时将图像添加到框架中。我在java中验证过该文件存在,它可以找到照片。我也证实了这个按钮的作用。但是,当我编译并单击按钮时,它什么也不做......如果有人能指引我在正确的方向,那将是非常感谢。将ImageIcon添加到按钮单击中已经显示的GUI上
package gamePractice;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.SwingConstants;
public class window {
public static void main(String[] args){
JFrame frame = new JFrame("ex");
JPanel panel = new JPanel();
JButton button = new JButton();
button.setText("Press Me");
panel.add(button);
frame.add(panel);
frame.setSize(300, 300);
frame.setLocationRelativeTo(null);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
button.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
if(e.getSource() == button) {
ImageIcon img = new ImageIcon(getClass().getResource("t.jpg"));
JLabel stickLabel = new JLabel("yes", img, SwingConstants.CENTER);
JPanel panel2 = new JPanel();
panel2.add(stickLabel);
frame.add(panel2);
}
}
});
}
}
非常感谢您!完美工作 –
但JPanel面板=新JPanel();用JButton按钮= new JButton();可以永远消失,因为JFrame使用BorderLayout – mKorbel
由于没有图像图标或文本且不可见的'JLabel'实际上是不可见的,因此将标签声明为类属性并在帧初始化期间添加它会更好。然后在'actionPerformed(..)'方法中设置图标。虽然在运行时添加组件是可能的,但它不是最理想的方式(尤其是在这种情况下)。 –