icon in JButton is not shown at the running of the program, what could be?

隐身守侯 提交于 2019-12-25 15:28:22

问题


I'm training with Java, especially with GUI (Swing & AWT), but I'm having a problem with icon in JButton. The image isn't shown, to make that visible I must resize the window, how could I do?

Here is the code:

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);
    }
}

回答1:


You need to call the revalidate() method on your JFrame after adding the JButton.

When you change the attribute of a component that would affect its appearance, you should call this method.

Difference between validate(), revalidate() and invalidate() in Swing GUI



来源:https://stackoverflow.com/questions/21709997/icon-in-jbutton-is-not-shown-at-the-running-of-the-program-what-could-be

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!