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

标签 java swing embedded-resource

我正在尝试编写一个带有 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());

关于java - 为什么这个 GUI 应用程序不向我显示图像?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52160543/

相关文章:

java - Spring Security antMatcher 与 HttpMethod.POST 不起作用

java - 基于 REST token 的身份验证不起作用

java - 如何在现有 JTable 的顶部添加一个表,其中一行由 JComboboxes 组成

java - 按金额删除购物车中的产品

读取输入文件时出现 javax.imageio.IIOException

Java返回对象/修改对象(编码指南)

java - 无间隙连接 Mp3 文件

java - 如何使用 JPanel 将一系列线函数合并为一个 drawPolygon 函数?

css - svg 中的响应图像

java - 如何将属性文件添加到 Java 项目中?