因此,我刚接触Java,可以从YouTube上的视频中学习一些基础知识,正在学习制作GUI /窗口,目前正试图显示图像,但不确定代码是否错误/图像过旧或图像位置不正确。到目前为止,这是我写的内容。帮助将不胜感激。谢谢,麻烦您了。
import java.awt.*;
import javax.swing.*;
public class FirstGUI extends JFrame {
private static Object out;
private JLabel label;
private JButton button;
private JTextField textfield;
private ImageIcon image1;
private JLabel label1;
private ImageIcon image2;
private JLabel label2;
public FirstGUI() {
setLayout (new FlowLayout());
label = new JLabel("Hi, I'm a label!");
add(label);
textfield = new JTextField(15);
add(textfield);
button = new JButton("Click me!");
add(button);
button = new JButton("No, CLICK ME!!");
add(button);
label = new JLabel("This is the end of the program?");
add(label);
image1 = new ImageIcon(getClass().getResource("Apiary.png"));
label1 = new JLabel(image1);
image2 = new ImageIcon(getClass().getResource("bee.png"));
label2 = new JLabel(image2);
}
public static void main(String[] args) {
FirstGUI gui = new FirstGUI();
gui.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
//* gui.setSize(400, 400);
gui.setVisible(true);
gui.setTitle("Hello World");
gui.pack();
}
}
我得到的错误是:
线程“主”中的异常java.lang.NullPointerException
在javax.swing.ImageIcon处。(未知源)
在FirstGUI。(FirstGUI.java:39)
在FirstGUI.main(FirstGUI.java:50)
首先,您没有在框架上添加标签,因此即使执行标签也不会显示图像图标。因此,请不要忘记将标签添加到框架中:
add(label1);
add(label2);
其次,我尝试了您的代码,它对我来说很好用,它只打印了我没有将图像图标导入到我正在使用的程序包中时提到的错误。为此,您需要执行以下操作:
右键单击src包-> import-> General-> File System,然后单击next
并选择包含图像的目录,单击Ok,然后添加您在代码中指定的图像。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句