JButton 中的图标在程序运行时未显示,可能是什么



我正在用Java训练,特别是GUI(Swing和AWT),但是我在JButton中遇到了icon的问题。图像没有显示,要使其可见,我必须调整窗口大小,我该怎么办?

这是代码:

public class MainWindow extends JFrame implements WindowListener, KeyListener, ActionListener, FocusListener, MouseListener{
private final String APPLICATION_NAME = "GUI";
private final String APPLICATION_VERSION = "0.0.1";
private final JButton btnCiao;
JPanel panel = new JPanel();
JPanel panel2 = new JPanel();
public MainWindow(){
        super();
        this.setTitle(APPLICATION_NAME + " " + APPLICATION_VERSION);
        this.setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE);
        this.addWindowListener(this); 
        Dimension dimension = Toolkit.getDefaultToolkit().getScreenSize();
        setLocation((int)(dimension.getWidth()/2-getWidth()/2), (int)(dimension.getHeight()/2-getHeight()/2));
        this.setVisible(true);
        setMinimumSize(new Dimension(600,600));
        add(panel);
        btnCiao = new JButton("WAU");
        panel.add(btnCiao);
        JButton imageButton = new JButton();
        try{
            Image img = ImageIO.read(getClass().getResource("Nike.jpg"));
            Image img2 = ImageIO.read(getClass().getResource("Adidas.jpg"));
            imageButton.setIcon(new ImageIcon(img));
            imageButton.setPressedIcon(new ImageIcon(img2));
        } catch(IOException ex){}
        // to remove the border
        imageButton.setBorder(null);
        panel.add(imageButton);
    }
}
添加

JButton后,您需要在JFrame上调用revalidate()方法。

更改会影响其外观的组件的属性时,应调用此方法。

Swing GUI 中 validate()、revalidate() 和 invalidate() 之间的区别

最新更新