简体   繁体   English

图像不会显示在JLabel中

[英]Image won't display in JLabel

I've gone through every post I could find on this site and the Java tutorials and I still can't figure out why my code isn't working. 我已经浏览了我在本网站和Java教程中找到的每一篇文章,但我仍然无法弄清楚为什么我的代码无效。 Even when I copy/paste other peoples' code, it still doesn't work. 即使我复制/粘贴其他人的代码,它仍然无效。

I've made a dummy program just to test this out and the code looks like so: 我做了一个虚拟程序只是为了测试它,代码看起来像这样:

import java.awt.EventQueue;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.border.EmptyBorder;
import javax.swing.JLabel;
import javax.swing.ImageIcon;

public class gui extends JFrame {

    private JPanel contentPane;

    /**
     * Launch the application.
     */
    public static void main(String[] args) {
        EventQueue.invokeLater(new Runnable() {
            public void run() {
                try {
                    gui frame = new gui();
                    frame.setVisible(true);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        });
    }

    /**
     * Create the frame.
     */
    public gui() {
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        setBounds(100, 100, 900, 700);
        contentPane = new JPanel();
        contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
        setContentPane(contentPane);
        contentPane.setLayout(null);

        JLabel lblNewLabel = new JLabel(new ImageIcon("bg.png"));
        contentPane.add(lblNewLabel);
    }
}

The background image I'm trying to display, bg.png, is located in the project's root folder. 我正在尝试显示的背景图片bg.png位于项目的根文件夹中。 I tried multiple formats for the path string with no success. 我为路径字符串尝试了多种格式但没有成功。 What am I doing wrong? 我究竟做错了什么?

What you're doing wrong is that when you call new ImageIcon("bg.png") , you try loading the bg.png file from the current directory. 你做错了是当你调用new ImageIcon("bg.png") ,你尝试从当前目录加载bg.png文件。 The current directory is the directory from which java is executed. 当前目录是执行java的目录。 And the current directory is probably not the directory you believe when you execute java from your IDE. 当前目录可能不是您从IDE执行java时所信任的目录。

Use the following code to display the current directory: 使用以下代码显示当前目录:

File dir1 = new File (".");
System.out.println("current directory: " + dir1.getAbsolutePath());

You should probably load the png file from the classpath, using Class.getResource("/images/bg.png") . 您应该使用Class.getResource("/images/bg.png")从类路径加载png文件。 Create an images folder in your source directory, and put the file in this directory. 在源目录中创建一个images文件夹,并将该文件放在该目录中。 Your IDE will copy it to the target folder, along with the .class files. 您的IDE会将其与.class文件一起复制到目标文件夹。 If you're not using an IDE, then you'll have to copy it yourself. 如果您没有使用IDE,那么您必须自己复制它。

EDIT: 编辑:

After more investigations, it appeared that the root cause of the problem was the use of the null layout. 经过更多的调查,似乎问题的根本原因是使用了null布局。 The above still stands, though, because loading a file from the current directory is not a good idea. 但是,上面仍然有效,因为从当前目录加载文件不是一个好主意。

You're looking for the image as a file. 您正在寻找图像作为文件。 When you do that the searches are all done in a path relative to the user directory which you can get via 当您这样做时,搜索都是在相对于您可以通过的用户目录的路径中完成的

// code not tested
System.out.println(System.getProperty("user.dir"));

So you will likely have to adjust your image's path to get it as a file. 因此,您可能需要调整图像的路径才能将其作为文件。 The other option is to get it as a resource as noted by Siva Charan in which case the path is relative to the location of your class files. 另一个选择是将其作为Siva Charan所指出的资源,在这种情况下,路径是相对于类文件的位置。

Oh and once you study and use the layout managers, they become intuitive, and creating and especially maintaing your GUI's become much easier. 哦,一旦你学习和使用布局管理器,它们就变得直观了,创建和维护你的GUI变得更加容易。

Try this way:- 试试这种方式: -

ImageIcon icon = createImageIcon("bg.png", "image description");

protected ImageIcon createImageIcon(String path, String description) {
    java.net.URL imgURL = getClass().getResource(path);

    if (imgURL != null) {
        return new ImageIcon(imgURL, description);
    } else {
        System.err.println("Couldn't find file:" +path);
        return null;
    }
}

Just simply put your bg.png, alongside your gui.class file. 只需将您的bg.png与您的gui.class文件放在一起即可。 That will do, if you write this code 如果你编写这段代码,那就行了

private ImageIcon getImage(String path)
{
    URL url = getClass().getResource(path);
    System.out.println(url);
    if (url != null)
        return (new ImageIcon(url));
    return null;
}

More information can be found on Access to Resources 可以在Access to Resources上找到更多信息

Here path = "bg.png"; 这里path =“bg.png”; or if it's inside some folder than path = "someFolder/bg.png"; 或者如果它在某个文件夹中而不是path =“someFolder / bg.png”; So you be writing something like this : 所以你写这样的东西:

JLabel lblNewLabel = new JLabel(getImage("bg.png"));
lblNewLabel.setBounds(30, 30, 100, 100);

Hope that might help. 希望可能有所帮助。

Regards 问候

You might need to debug it and check if the image file is loaded correctly. 您可能需要调试它并检查图像文件是否正确加载。 And then you need to check if the JLabel Component gets its size because adding the image to the JLabel wouldn't expand the JLabel. 然后,您需要检查JLabel组件是否获得其大小,因为将图像添加到JLabel不会扩展JLabel。

First you should try to see the image handler has its width and height. 首先,您应该尝试查看图像处理程序的宽度和高度。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM