How to set Icon to a JLabel from an image from a folder?
Asked Answered
D

5

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.

Discussant answered 3/3, 2013 at 4:1 Comment(7)
Please have a look at this answer of mine, for How to add images to your resource folder, 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 :-)Bahamas
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).Subadar
@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?Discussant
@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?Discussant
@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 jarSubadar
@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.Bahamas
@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.Bahamas
B
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 :-)

Bahamas answered 3/3, 2013 at 15:23 Comment(2)
+1 The tutorial should cite this answer!Gers
Thankyou both of you and KEEP SMILING :-)Bahamas
G
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.

Gers answered 3/3, 2013 at 7:23 Comment(2)
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.Discussant
You could try a file URI or new ImageIcon(path).Gers
A
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.

Alithia answered 10/10, 2013 at 20:2 Comment(0)
B
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();


    }





}
Blepharitis answered 14/8, 2015 at 0:2 Comment(0)
A
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".

Anciently answered 22/8, 2022 at 5:18 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.