为什么此GUI应用程序不显示图像? [英] Why this GUI app does not show me the image?

查看:140
本文介绍了为什么此GUI应用程序不显示图像?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试用JFrame对象编写一个Java应用程序,该对象必须显示三个带有文本和图像的标签对象,我的文本 North和 South在执行时显示,但是我的图像却没有,即使我

I'm trying yo write a java app with a JFrame object that must show three label objects, with text and image, my text "North" and "South" shows up on execution, but my image does not, even I put the image file into src folder.

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 的同一程序包中,请尝试执行此操作,

Since your image stored in same package where LabelDemo is stored, try this,

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

这篇关于为什么此GUI应用程序不显示图像?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆