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

时间:2016-04-17 16:32:55

标签: java swing jlabel

我想将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();

    }
}

enter image description here

2 个答案:

答案 0 :(得分:0)

您必须向JLabel提供Icon实现(即ImageIcon)。您可以通过setIcon方法(如您的问题)或通过JLabel构造函数执行此操作:尝试此操作

tryImage.setIcon(new ImageIcon(path));

答案 1 :(得分:-2)

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

如果图像位于项目类路径中,请尝试以下操作:

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