Reputation: 47
im having trouble in adding an image after a button is clicked, ive only added the code with the jlabel/imageicon
JLabel picture;
public Check() {
picture = new JLabel(createImageIcon("images\\exit.png"));
add(picture, BorderLayout.WEST);
}
public void actionPerformed(ActionEvent e) {
picture.setIcon(createImageIcon("images\\update.png"));
}
protected static ImageIcon createImageIcon(String path) {
java.net.URL imgURL = Check.class.getResource(path);
System.err.println(imgURL);
if (imgURL != null) {
return new ImageIcon(imgURL);
} else {
System.err.println("Couldn't find file: " + path);
return null;
}
}
i always get null for the path, what could be the problem
the image path is correct as when i tested another way,
public Check() {
String imgStr = "images\\exit.png";
ImageIcon image = new ImageIcon(imgStr);
JLabel label1 = new JLabel(image, JLabel.CENTER);
JPanel South = new JPanel();
South.add(label1);
add("South", South);
}
the image appears, but this is done when i run it, the image is there already and not when i click a button.
thanks
Upvotes: 0
Views: 660
Reputation: 75
or you can simply add this line in the action performed method.
picture = new JLabel(new ImageIcon("/images/update.png"));
Upvotes: 0
Reputation: 25380
Please try picture.setIcon(createImageIcon("/images/update.png"));
since it looks like that you image is loaded from classpath.
See here:
Finds a resource with a given name. This method returns null if no resource with this name is found. The rules for searching resources associated with a given class are implemented by the * defining class loader of the class.
This method delegates the call to its class loader, after making these changes to the resource name: if the resource name starts with "/", it is unchanged; otherwise, the package name is prepended to the resource name after converting "." to "/". If this object was loaded by the bootstrap loader, the call is delegated to ClassLoader.getSystemResource.
http://docs.oracle.com/javase/1.4.2/docs/api/java/lang/Class.html#getResource%28java.lang.String%29
Upvotes: 0