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

8

当我从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上都只显示"图片未找到"。


2
请看一下我的这个答案,关于如何将图片添加到资源文件夹,这可能会对这个主题有所帮助 :-) 如果你手动操作而没有使用任何IDE,最后一个链接肯定会指导你。如果还有什么不清楚的地方,请随时提问 :-) - nIcE cOw
1
为什么要做一些如此复杂的事情,当只需使用new ImageIcon("C:\\Users\\xerof_000\\Pictures\\tmspictures\\" + name + ".jpg");即可立即工作呢?(尽管这不太可维护,因为它只能在您的计算机上运行,我同意)。 - Guillaume Polet
@GagandeepBali 我正在使用NetBeans进行操作,因此我查看了NetBeans链接。问题在于,我还要在.jar文件的运行时将图片添加到图像文件夹中。而且我不能在运行.jar文件时将图像添加到包中,对吧?所以,有没有办法从.jar文件运行的文件夹中读取图像? - Raed Shahid
@GuillaumePolet 谢谢,这对我有用。但是有没有一种方法可以从一个文件夹中读取图像,而该文件夹是从 .jar 文件运行的呢? - Raed Shahid
@RaedShahid 是的,如果该文件夹在类路径上或是类路径上某个文件夹的子文件夹,则可以。假设您有一个名为“root”的文件夹,其中包含一个名为“foo.jar”的jar文件和一个名为“bar.png”的图像文件,如果您使用java -cp .;foo.jar(Windows)/ java -cp .:foo.jar(Unix / Linux / MacOS)运行程序,则可以使用getResource("/bar.png")访问该文件。您还可以直接将文件嵌入到jar中。 - Guillaume Polet
显示剩余2条评论
5个回答

13

这是我的目录结构:

                                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 文件 带到任何具有以下图片的位置 (geek0.gif, geek1.gif, geek2.gif, geek3.gifgeek4.gif),然后运行 JAR 文件,并查看结果 :-)

2
+1 这个教程应该引用这个答案! - trashgod
谢谢你们两个,保持微笑 :-) - nIcE cOw

3

如在使用图标中所讨论的,getResource()方法期望在你程序的JAR文件中找到图像。你需要将图像移动到你的项目中。IconDemo是一个完整的示例。


那是我之前的做法,而且它一直都有效。但现在我无法添加要读取的新图像。我该如何让它从一个特定的文件夹外部读取,以便我可以添加要从该文件夹读取的新图像。 - Raed Shahid
你可以尝试使用file URI或者new ImageIcon(path) - trashgod

0

这是一个老问题,但我记录下了对我有用的答案,以防帮助那些匆忙且不熟悉Java文件结构的人。

检查表达式System.getProperty("user.dir")返回什么,可以通过打印或使用调试器来实现,在我的情况下是:/home/Admin/NetBeansProjects/MyProject
如果您在该位置创建一个包含图像的文件夹,使您的文件夹看起来像这样:

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

那么你应该能够这样做:
myLabel.setIcon(new ImageIcon("img/myImage.jpg"));

这个解决方案是可行的,但要注意并不是每种情况都理想,因为每个高分答案都提到了“资源文件夹”。


0

由于您使用了jLabel,因此可以简单地使用HTML标记,只需以<html>开始标签文本,并在标签中按照您的意愿使用HTML标记,在您的情况下: <img src=filepth\imagefile.jpg> 您可以使用此方法替换:)。带笑脸图标。


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


    }





}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接