我无法在GUI上实现图片。

3
我正在使用eclipse,我想在标签或GUI的徽标上添加一张图片。
我希望它看起来像这样!
我将其上传到网络上,因为我没有10个声望值。
(“Names cool program”)是该图片。
 import java.awt.*;
    import javax.swing.*;
    import javax.swing.JFrame;

    public class MainClass extends JFrame{ // super class JFrame

        // Kind of a tutorial for creating GUI's in java
        private JLabel label;
        private JLabel label1;
        private JButton button;
        private JTextField textfeild;
        private ImageIcon image1; // image for my logo

        public MainClass () {
            setLayout (new FlowLayout());

            image1 = new ImageIcon (getClass ().getResource ("logo.gif")); // declares image

            label = new JLabel ("This is the label");
            add (label);

            label1 = new JLabel (image1); // adds image
            add (label1);

            textfeild = new JTextField (15);
            add (textfeild);

            button = new JButton ("Click");
            add (button);

        }

        public static void main(String[] args) {        

            MainClass gui = new MainClass ();


            gui.setDefaultCloseOperation (JFrame.EXIT_ON_CLOSE); // creates window
            gui.setSize (300,300);
            gui.setVisible (true);
            gui.pack ();
            gui.setTitle ("Title");

        }

    }

程序可以编译,但无法运行。会提示错误信息。
Exception in thread "main" java.lang.NullPointerException
    at javax.swing.ImageIcon.<init>(Unknown Source)
    at JonsCalc.<init>(JonsCalc.java:18)
    at JonsCalc.main(JonsCalc.java:38)

1
我正在使用Eclipse,想要在我的GUI中的标签或徽标上添加一张图片。我希望它看起来像这样!好的,那么你具体的问题是什么?当你尝试时会发生什么?有异常吗?它无法编译?你的电脑会爆炸成1000个碎片吗? - Hovercraft Full Of Eels
那么这是您想要放入程序中的图像,还是“NAMES COOL PROGRAM”代表您想要添加的图像? - Nick ODell
2
我猜测你的问题(我们本不应该这样做!)可能是因为你当前的GUI布局不是你想要的方式。如果是这样,那么你需要参考[布局管理器教程](http://docs.oracle.com/javase/tutorial/uiswing/layout/index.html),学习如何使用Swing GUI可以使用的各种布局。完成后,考虑下载MigLayout。 - Hovercraft Full Of Eels
如果问题是图像未显示,请检查您是否将“logo.gif”与“MainClass”放在同一位置。 - Adrian Ber
1
ImageIcon 的问题在于它无法以任何有意义的方式报告当它不能加载图像时的情况。尝试使用 getClass().getResource("/logo.gif"),并使用 ImageIO API,因为它至少会抛出一个 Exception 如果不能加载图像。 - MadProgrammer
@FryonAlexandra:请看一下这个答案,可能对你有些帮助 :-) - nIcE cOw
4个回答

1
我建议您为图像/图标创建一个专门的包,然后在其中创建一个名为“ImageLoader”的单个加载器类或其他任何您想要的名称。然后,您可以使用以下代码...
new ImageLoader().getClass().getResource("NAME_OF_IMAGE"));

1
这段代码 getClass().getResource("logo.gif") 的意思是从与你的类 MainClass 相同的位置加载图像。请检查您的图像是否与 MainClass 在同一个包中。如果您使用 Eclipse,则将图像文件放在 src 文件夹中的包中,它将自动复制到 bin 中。

0

在你的类上右键,然后选择新建。点击新建源文件夹。最后将你的图片移动到该文件夹中。现在你可以使用那段代码了。


0
如果您正在使用Eclipse,请将图像复制到您的和项目的bin文件夹中。然后只需键入 image1 = new ImageIcon(this.getClass().getResource("filename.filetype"));

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接