This morning I was testing my out my program and just running it through and it was working well. After an hour my images just stopped appearing on my buttons I'm not sure why.
JButton chuck = new JButton(new ImageIcon("chucknorris.jpg"));//this part of program runs this if user picks lizard
chuck.setSize(210,175); //sets size of button
chuck.setLocation(25,75); //sets location of button
chuck.addActionListener(new ActionListener() {
public void actionPerformed (ActionEvent e) {
int answer = JOptionPane.showConfirmDialog(null, "\t\t STATS\nAttack: 10\nDefence: 15\nspecial: bomb");
if (answer == JOptionPane.NO_OPTION) {
System.out.println("No button clicked");
} else if (answer == JOptionPane.YES_OPTION) {
x = 1;
b = 0;
} else if (answer == JOptionPane.CLOSED_OPTION) {
System.out.println("JOptionPane closed");
}
}
});
my images are stored in a folder with my java file
This suggests that the images are, in fact, embedded resources and can't be referenced like normal files on the file system.
ImageIcon(String)
assumes that the String
reference is referring to a file on the file system. Once built, this will no longer be true
, instead, you need to use Class#getResource
or Class#getResourcesAsStream
depending on your needs, for example...
JButton chuck = new JButton(new ImageIcon(getClass().getResource("chucknorris.jpg")));
A better solution would be to use ImageIO.read
as this will actually throw an IOException
if the image can't be loaded for some reason, rather than failing silently
try {
BufferedImage img = ImageIO.read(getClass().getResource("chucknorris.jpg"));
JButton chuck = new JButton(new ImageIcon(img));
} catch (IOException exp) {
JOptionPane.showMessageDialog(null, "Check has left the building");
exp.printStackTrace();
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.