如何从图标从文件夹中的图像设置为一个JLabel?(How to set Icon to a JLa

2019-07-20 21:19发布

我试图从每当项目从一个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:\用户\ xerof_000 \图片\ tmspictures \”我尝试使用“C:/用户/ xerof_000 /图片/ tmspictures /”但即使没有工作。 而且不管我做什么,只显示“未找到图像”上的JLabel。

Answer 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 ,并查看结果:-)



Answer 2:

正如在讨论如何使用图标时, getResource()方法,希望能够找到在你的程序的JAR文件中的图像。 你需要将图像移动到您的项目。 IconDemo是一个完整的例子。



Answer 3:

由于您使用的JLabel,你可以简单的使用HTML标签,就开始与标签文本<html>和使用HTML标签在标签为u想,在旅游的情况:<IMG SRC = filepth \ imagefile.jpg> U可以使用此取代 : )。 随着微笑图标。



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


    }





}


文章来源: How to set Icon to a JLabel from an image from a folder?