在JFrame中显示图像

在JFrame中显示图像

问题描述:

我目前正在学习Java,目前我遇到了一些问题。

I am currently learning Java, and I am stuck with something at the moment.

我一直在寻找一种方法来将图像添加到我的JFrame中。
我在互联网上找到了这个:

I was looking for a way to add an image to my JFrame. I found this on the internet:

ImageIcon image = new ImageIcon("path & name & extension");
JLabel imageLabel = new JLabel(image); 

在将它实现到我自己的代码之后,它看起来像这样(这只是相关部分) :

And after implementing it to my own code, it looks like this (this is only the relevant part):

class Game1 extends JFrame
{
    public static Display f = new Display();
    public Game1()
    {
        Game1.f.setSize(1000, 750);
        Game1.f.setResizable(false);
        Game1.f.setVisible(true);
        Game1.f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        Game1.f.setTitle("Online First Person Shooter");

        ImageIcon image = new ImageIcon("C:\\Users\\Meneer\\Pictures\\image.png");
        JLabel imageLabel = new JLabel(image); 
        add(imageLabel);
        }
}

class Display extends JFrame
{
}

运行此代码时,它不会给我任何错误,但它也不显示图片。我看到一些问题和人有同样的问题,但他们的代码与我的完全不同,他们用其他方式来显示图像。

When running this code, it doesn't give me any errors, but it also doesn't show the picture. I saw some questions and people having the same problem, but their code was completely different from mine, they used other ways to display the image.

创建 Jlabel后执行此操作

imageLabel.setBounds(10, 10, 400, 400);
imageLabel.setVisible(true);

还将布局设置为JFrame

also set the layout to JFrame

Game.f.setLayout(new FlowLayout);