如何在 Java 中将图像分配给 JLabel?

How do I assign an image to JLabel in Java?

我想将 png 图像分配给 JLabel

我试过这个代码但是没有图像出现[更新]:

class firstPokemonChoose extends JFrame{
    private static final int WIDTH = 800; //ukuran panjang window
    private static final int HEIGHT = 800; //ukuran lebar window
    JLabel intro, tryImage;

    public firstPokemonChoose(){
        setTitle("Choose Your Pokemon"); //set judul window
        setSize(WIDTH, HEIGHT); //set ukuran

        intro = new JLabel("Please choose your first Pokemon", SwingConstants.LEFT);

        java.net.URL url = getClass().getResource("torchic.png");
        ImageIcon img = new ImageIcon(url);
        tryImage.setIcon(img);

        Container pane = getContentPane();
        pane.setLayout(new GridLayout(3, 3));
        pane.add(intro);
        pane.add(tryImage);

        setVisible(true); //set windows visible
        setDefaultCloseOperation(EXIT_ON_CLOSE);
        validate();

    }
}

您必须向 JLabel 提供一个图标实现(即 ImageIcon)。您可以通过 setIcon 方法(如您的问题)或通过 JLabel 构造函数来完成:试试这个

tryImage.setIcon(new ImageIcon(path));

我建议将您的图像放在您的项目中,因为这样,您的图像将与项目一起移植,并且不应在代码中修改任何路径。

如果图像在您的项目类路径中,试试这个:

java.net.URL url = getClass().getResource("/Resources/torchic.png");
ImageIcon image = new ImageIcon(url);
tryImage .setIcon(image);

如果不是,你必须定义图片的绝对路径如下:

tryImage.setIcon(new ImageIcon("path\torchic.png"));

更新:

您的代码中有 2 个错误:

  • 首先要给出图片的完整路径"/Resources/torchic.png"而不仅仅是torchic.png

  • 第二个是你试图将图标设置为未初始化的 tryImage JLabel

    按如下方式编辑您的代码:

    class firstPokemonChoose extends JFrame{
        private static final int WIDTH = 800; //ukuran panjang window
        private static final int HEIGHT = 800; //ukuran lebar window
        JLabel intro, tryImage;
    
        public firstPokemonChoose(){
            setTitle("Choose Your Pokemon"); //set judul window
            setSize(WIDTH, HEIGHT); //set ukuran
            intro = new JLabel("Please choose your first Pokemon", SwingConstants.LEFT);
            tryImage = new JLabel(); // initialize the tryImage label
            java.net.URL url = getClass().getResource("/Resources/torchic.png");
            ImageIcon img = new ImageIcon(url);
            tryImage.setIcon(img);
    
            Container pane = getContentPane();
            pane.setLayout(new GridLayout(3, 3));
            pane.add(intro);
            pane.add(tryImage);
    
            setVisible(true); //set windows visible
            setDefaultCloseOperation(EXIT_ON_CLOSE);
            validate();
        }
    
        public static void main(String [] args){
            firstPokemonChoose firstPokemonChooseInstance = new firstPokemonChoose();
        }
    }