對於爲什麼我的程序無法正常工作,我有點困惑。我正在嘗試在單擊按鈕時將圖像添加到框架中。我在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(..)'方法中設置圖標。雖然在運行時添加組件是可能的,但它不是最理想的方式(尤其是在這種情況下)。 –