如何从文件夹中的图像将图标设置为JLabel?

时间:2013-03-03 04:01:25

标签: java swing jlabel jcombobox imageicon

每当从JComboBox中选择一个项目时,我都会尝试从图像文件夹中为JLabel设置一个图标。 JComboBox中的项目名称和文件夹中图像的名称相同。因此,无论何时从JComboBox中选择一个项目,都应将具有相同名称的相应图像设置为JLabel的图标。我正在尝试这样做。

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;
        }
    }

我认为问题出现在“C:\ Users \ xerof_000 \ Pictures \ tmspictures \”中我尝试使用“C:/ Users / xerof_000 / Pictures / tmspictures /”,但即使这样也行不通。无论我做什么,它只在JLabel上显示“Image not found”。

4 个答案:

答案 0 :(得分:12)

这是我的目录结构:

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

这是 ComboExample.java 文件的内容:

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();
            }
        });
    }
}

现在编制:

编译我做了这个:

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

清单文件的内容:

enter image description here

JAR文件创建:

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 *

现在将此JAR File带到包含这些图片的任何位置(geek0.gifgeek1.gifgeek2.gifgeek3.gifgeek4.gif),以及运行JAR File,并查看结果: - )

答案 1 :(得分:3)

正如How to Use Icons中所讨论的,getResource()方法希望在程序的JAR文件中找到图像。您需要将图像移动到项目中。 IconDemo是一个完整的例子。

答案 2 :(得分:0)

由于你使用jLabel,你可以简单地使用HTML标签,只需用<标签文本开始。 html>在旅游案例中,根据需要在标签中使用HTML标签: < img src = filepth \ imagefile.jpg> 你可以用它来取代:)。带着微笑图标。

答案 3 :(得分: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();


    }





}