【问题标题】:How to set Icon to a JLabel from an image from a folder?如何从文件夹中的图像将图标设置为 JLabel?
【发布时间】:2013-02-17 09:44:46
【问题描述】:

每当从 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 上显示“找不到图像”。

【问题讨论】:

  • 请看看我的这个答案,对于如何add images to your resource folder,这可能会对这个主题有所帮助:-) 最后一个链接肯定会指导你,如果你这样做一切手动操作,无需使用任何 IDE。如果还有什么不清楚的,请询问:-)
  • new ImageIcon("C:\\Users\\xerof_000\\Pictures\\tmspictures\\" + name + ".jpg"); 可以立即工作时,为什么要做这么复杂的事情? (虽然这不太容易维护,因为它只能在您的计算机上运行,​​我同意)。
  • @GagandeepBali 我是从 NetBeans 做的,所以我检查了 NetBeans 链接。问题是,我还在 .jar 文件运行时将图片添加到图像文件夹中。我不能在运行 .jar 文件时将图像添加到 .jar 文件中的包中吗?那么有没有办法从运行 .jar 文件的文件夹中读取图像?
  • @GuillaumePolet 谢谢你为我工作。但是有没有办法可以从运行 .jar 文件的文件夹中读取图像?
  • @RaedShahid 是的,如果该文件夹在类路径上,或者是类路径上文件夹的子文件夹。假设您有一个文件夹 root 包含一个 jar foo.jar 和一个图像 bar.png,如果您使用 java -cp .;foo.jar (Windows)/java -cp .:foo.jar (Unix/Linux/MacOS) 运行程序,您可以访问该文件与getResource("/bar.png");。也可以直接将文件嵌入jar中

标签: java swing jlabel jcombobox imageicon


【解决方案1】:

这是我的目录结构:

                                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

清单文件的内容:

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 带到任何具有这些图像(、、、 和)的位置,然后运行JAR File,然后查看结果:- )

【讨论】:

  • +1 tutorial 应该引用这个答案!
  • 非常感谢 :) 帮助了我很多。
  • 谢谢你们,保持微笑:-)
【解决方案2】:

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

【讨论】:

  • 那是我以前做的方式,它正在工作。但后来我无法添加要阅读的新图像。我怎样才能让它从 jar 外部的特定文件夹中读取,以便我可以添加要从该文件夹中读取的新图像。
  • 你可以试试file URInew ImageIcon(path)
【解决方案3】:

由于您使用 jLabel,您可以简单地使用 HTML 标签,只需以 开头标签文本,并根据需要在标签中使用 HTML 标签,在旅游案例中: 你可以用它来代替:)。带有微笑图标。

【讨论】:

    【解决方案4】:
          /*
    
    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();
    
    
        }
    
    
    
    
    
    }
    

    【讨论】:

      猜你喜欢
      • 2011-06-08
      • 2014-05-20
      • 1970-01-01
      • 2016-01-21
      • 2013-02-02
      • 1970-01-01
      • 2019-03-30
      • 2018-05-27
      • 2015-05-23
      相关资源
      最近更新 更多