为什么这个 GUI 应用程序不显示图像?

Why this GUI app does not show me the image?

我正在尝试编写一个带有 JFrame 对象的 java 应用程序,该对象必须显示三个带有文本和图像的标签对象,我的文本 "North" 和 "South" 显示在执行,但我的图像没有,即使我将图像文件放入src文件夹。

package deitel9;

import java.awt.BorderLayout;

import javax.swing.ImageIcon;

import javax.swing.JLabel;

import javax.swing.JFrame;


public class LabelDemo {

    public static void main(String[] args)
    {
         //crate a label with a plain text
        JLabel northLabel = new JLabel("North");

        //crate an icon from an image so we can put it on a JLabel
        ImageIcon labelIcon = new ImageIcon("maldive.jpg");

        //crate a label with an Icon instead of text
        JLabel centerLabel = new JLabel(labelIcon);

        //create another label with an Icon
        JLabel southLabel = new JLabel(labelIcon);

        //set the label to display text (as well as an icon)
        southLabel.setText("South");

        //create a frame to hold the labels
        JFrame application = new JFrame();

        application.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

        //add the labels to the frame; the second argument specifies
        //where on the frame to add the label

        application.add(northLabel,BorderLayout.NORTH);
        application.add(centerLabel,BorderLayout.CENTER);
        application.add(southLabel,BorderLayout.SOUTH);

        application.setSize(300,300);
        application.setVisible(true);
    }//end main


}//end class LabelDemo

由于您的图像存储在存储 LabelDemo 的同一个包中,请试试这个,

ImageIcon labelIcon = new ImageIcon(LabelDemo.class.getResource("/deitel9/maldive.jpg").getFile());

private String getImage() {
    return getClass().getResource("/deitel9/maldive.jpg").getFile();
}

ImageIcon labelIcon = new ImageIcon(new LabelDemo().getImage());

根据 documentation,您选择的 ImageIcon 构造函数需要一个文件名或文件路径,因此图像需要在文件系统上而不是在 class 路径上.

Creates an ImageIcon from the specified file. [...] The specified String can be a file name or a file path.

根据您的描述,当您的项目布局如下所示时

\---src
    \---deitel9
        LabelDemo.java
        maldive.jpg

那么您应该能够检索图像作为位于 class 路径上的资源,如下所示:

ImageIcon labelIcon = new ImageIcon(LabelDemo.class.getResource("maldive.jpg"));

要弄清楚在这种情况下你做错了什么,你可以简单地调用

File file = new File ("maldive.jpg");
System.out.println(file.getAbsolutePath());

这将打印出它为您的文件查找的绝对路径,这可能会提示您做错了什么。

当然,如果您知道如何使用调试器,则不需要第二行(技术上什至不需要第一行,但这有点棘手;))