I am trying to set an icon to a JLabel from a folder of images whenever an item is selected from a JComboBox. The name of items in the JComboBox and name of the images in the folder are same. So whenever an item is selected from the JComboBox, the corresponding image with the same name should be set as an icon to the JLabel. I am trying to do something like this.
private void cmb_movieselectPopupMenuWillBecomeInvisible(javax.swing.event.PopupMenuEvent evt){
updateLabel(cmb_moviename.getSelectedItem().toString());
}
protected void updateLabel(String name) {
ImageIcon icon = createImageIcon("C:\\Users\\xerof_000\\Pictures\\tmspictures\\" + name + ".jpg");
if(icon != null){
Image img = icon.getImage();
Image newimg = img.getScaledInstance(lbl_pic.getWidth(), lbl_pic.getHeight(), java.awt.Image.SCALE_SMOOTH);
icon = new ImageIcon(newimg);
lbl_pic.setIcon(icon);
lbl_pic.setText(null);
}
else{
lbl_pic.setText("Image not found");
lbl_pic.setIcon(null);
}
}
protected static ImageIcon createImageIcon(String path) {
URL imgURL;
imgURL = NowShowing.class.getResource(path);
if (imgURL != null) {
return new ImageIcon(imgURL);
} else {
return null;
}
}
I thought the problem is in "C:\Users\xerof_000\Pictures\tmspictures\" I tried using "C:/Users/xerof_000/Pictures/tmspictures/" but even that did not work. And whatever I do it only shows "Image not found" on the JLabel.
new ImageIcon("C:\\Users\\xerof_000\\Pictures\\tmspictures\\" + name + ".jpg");
will work immediately? (although this is not much maintainable as it will only work on your computer, I agree). – Subadarroot
containing a jarfoo.jar
and an imagebar.png
, if you run your program withjava -cp .;foo.jar
(Windows)/java -cp .:foo.jar
(Unix/Linux/MacOS), you can access the file withgetResource("/bar.png");
. You can also embedded directly the file in the jar – Subadarmanifest
file,Class-Path: .
, this will allow the contents of the current directory to be on theCLASSPATH
, for the .jar file to access. – Bahamas