8

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.

trashgod
  • 203,806
  • 29
  • 246
  • 1,045
Raed Shahid
  • 241
  • 5
  • 7
  • 12
  • 2
    Please have a look at this answer of mine, for How to [add images to your resource folder](http://stackoverflow.com/a/9866659/1057230), that might will be of some help on the topic :-) The very last link will guide you surely, if you doing everything manually without using any IDE. If anything is still unclear, please do ask :-) – nIcE cOw Mar 03 '13 at 07:19
  • 1
    Why doing something so complicated when just `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). – Guillaume Polet Mar 03 '13 at 13:13
  • @GagandeepBali I am doing it from NetBeans so I checked the NetBeans link. The thing is, I am also adding pictures to the images folder during the runtime of the .jar file. And I cannot add images to the package in the .jar file while running the .jar file cant I? So is there a way I can read the images from a folder where the .jar file is run from? – Raed Shahid Mar 03 '13 at 13:42
  • @GuillaumePolet Thank you that did work for me. But is there a way where I can read the images from a folder where the .jar file is run from? – Raed Shahid Mar 03 '13 at 13:45
  • @RaedShahid Yes, if that folder is on the classpath, or is child-folder of a folder on the classpath. Assuming you have a folder `root` containing a jar `foo.jar` and an image `bar.png`, if you run your program with `java -cp .;foo.jar` (Windows)/`java -cp .:foo.jar` (Unix/Linux/MacOS), you can access the file with `getResource("/bar.png");`. You can also embedded directly the file in the jar – Guillaume Polet Mar 03 '13 at 14:25
  • @RaedShahid : Then you simply can add this line to your `manifest` file, `Class-Path: .` , this will allow the contents of the current directory to be on the `CLASSPATH`, for the .jar file to access. – nIcE cOw Mar 03 '13 at 14:49
  • @RaedShahid : I had managed to provide one example code, for you to have a look at. Please do let me know if this is not what you intend to mean. – nIcE cOw Mar 03 '13 at 15:25

5 Answers5

13

This is my directory structure :

                                packageexample
                                      |
                   -------------------------------------------
                   |                  |                      |
                build(folder)     src(folder)           manifest.txt
                   |                  |
             swing(package)       ComboExample.java
                   |
            imagetest(subpackage)
                   |
     ComboExample.class + related .class files

This is the content of the ComboExample.java file :

package swing.imagetest;    

import java.awt.*;
import java.awt.event.*;
import java.net.*;
import javax.swing.*;
    
public class ComboExample {

    private String[] data = new String[]{
                                            "geek0",
                                            "geek1",
                                            "geek2",
                                            "geek3",
                                            "geek4"
                                        };
    private String MESSAGE = "No Image to display yet...";
    private JLabel imageLabel;
    private JComboBox cBox;
    private ActionListener comboActions = 
                            new ActionListener() {
        @Override
        public void actionPerformed(ActionEvent ae) {
            JComboBox combo = (JComboBox) ae.getSource();
            ImageIcon image = new ImageIcon(
                        getClass().getResource(
                            "/" + combo.getSelectedItem() + ".gif"));
            if (image != null) {
                imageLabel.setIcon(image);
                imageLabel.setText("");
            } else {
                imageLabel.setText(MESSAGE);
            }
        }    
    };

    private void displayGUI() {
        JFrame frame = new JFrame("Combo Example");
        frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);

        JPanel contentPane = new JPanel();
        imageLabel = new JLabel(MESSAGE, JLabel.CENTER);
        cBox = new JComboBox(data);
        cBox.addActionListener(comboActions);

        contentPane.add(imageLabel);
        contentPane.add(cBox);

        frame.setContentPane(contentPane);
        frame.pack();
        frame.setLocationByPlatform(true);
        frame.setVisible(true);
    }

    public static void main(String... args) {
        EventQueue.invokeLater(new Runnable() {
            @Override
            public void run() {
                new ComboExample().displayGUI();
            }
        });
    }
}

NOW THE COMPILATION :

To compile I did this :

Gagandeep Bali@LAPTOP ~/c/Mine/JAVA/J2SE/src/packageexample
$ javac -d build src/*.java

Contents of Manifest File :

enter image description here

JAR File creation :

Gagandeep Bali@LAPTOP ~/c/Mine/JAVA/J2SE/src/packageexample
$ cd build

Gagandeep Bali@LAPTOP ~/c/Mine/JAVA/J2SE/src/packageexample/build
$ jar -cfm imagecombo.jar ../manifest.txt *

Now take this JAR File to any location having these images (geek0.gif, geek1.gif, geek2.gif, geek3.gif and geek4.gif), and run the JAR File, and see the results :-)

nIcE cOw
  • 24,468
  • 7
  • 50
  • 143
3

As discussed in How to Use Icons, the getResource() method expects to find the image in your program's JAR file. You'll need to move the image into your project. IconDemo is a complete example.

trashgod
  • 203,806
  • 29
  • 246
  • 1,045
  • that was the way i was doing before and it was working. but then i am not able to add new images to be read. how can i make it read from a specific folder outside the jar so i can add new images to be read from that folder. – Raed Shahid Mar 03 '13 at 12:30
  • You could try a [_file URI_](http://en.wikipedia.org/wiki/File_URI_scheme#Windows) or `new ImageIcon(path)`. – trashgod Mar 03 '13 at 19:41
0

Since you use jLabel, you can simple use HTML tags, just begin the label text with < html > and use HTML tags in the label as u want, in tour case : < img src=filepth\imagefile.jpg > U can use this to replace : ). With smile icon.

EsmaeelQash
  • 488
  • 2
  • 6
  • 20
0
      /*

Create an Image File whose size is 700 x 472 (pixels) in any image editor. 
Here Image was created using MS - Paint.

Make sure that the Image File and the main file are in the same folder.

The size of the JFrame should be set to 700 x 472 (pixels) in the program. 


Set the JLabel's IconImage.

Add the JLabel to the JFrame.

Set JFrame properties.

Display JFrame.

------------------------------------------------------------------------------

label.setIcon(getClass().getResources(String name));

label.setIcon(new ImageIcon(String file));


These 2 methods, don't always work with us. 


So, we create a method "getImageIcon(File f)" that returns a new ImageIcon Object,
everytime a new File Object is passed to it. 


*/




import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JButton;


import java.awt.Image;
import javax.imageio.ImageIO;
import java.io.File;
import java.io.IOException;


import javax.swing.ImageIcon;

import static javax.swing.WindowConstants.*;






public class ImageDemo
{

    JFrame frame = new JFrame();      //initialized


    JLabel label = new JLabel();      //initialized


    JButton button = new JButton();   //initialized


    ImageIcon ii;                //not initialized  





    public void displayImage()
    {

        //Layout Type: Null Layout.

        label.setIcon(getImageIcon(new File("print.png")));


        button.setBounds(150,150,358,66);
        //Note that sizes of the Image and Button are same.
        button.setIcon(getImageIcon(new File("Button.png")));



        label.add(button);
        //add the button to the label


        frame.add(label);
        frame.setBounds(300, 50, 700, 472);
        //(300 x 50 = HorizontalAlignment x VerticalAlignment)
        //(700 x 472 = Width x Height)      

        frame.setTitle("Image Demo");
        frame.setDefaultCloseOperation(EXIT_ON_CLOSE); //WindowConstants.EXIT_ON_CLOSE
        frame.setVisible(true);


    }





    public ImageIcon getImageIcon(File f)
    {


        try
        {
            Image im = ImageIO.read(f);


            ii = new ImageIcon(im);


        }
        catch(IOException i)
        {

            i.printStackTrace();


        }



        finally
        {

            return ii;

        }


    }



    public static void main(String[] args)
    {

        ImageDemo id = new ImageDemo();

        id.displayImage();


    }





}
Guest
  • 1
0

This is an old question but I am recording the answer that worked for me in case it helps someone else who is in a hurry and unfamiliar with java file structures.

Check what the expression System.getProperty("user.dir") returns, either by printing it or with your debugger, in my case it was: /home/Admin/NetBeansProjects/MyProject
if you make a folder with your image in that location such that your folders look like this:

NetBeansProjects
  └MyProject
    ├src
    │ └main
    │   └java
    │     └mypackage
    │       └MyClass
    │         └myJavaFile.java
    └img
      └myImage.jpg

Then you should be able just do this:
myLabel.setIcon(new ImageIcon("img/myImage.jpg"));

This solution works but be aware that it is probably not ideal in every case since every high scoring answer talks about a "resource folder".

lupinx2
  • 83
  • 1
  • 7