问题
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