所以我是Java新手,从YouTube上的视频中学习一些基础知识,我正在学习制作GUI /窗口,目前我正在努力让iamges显示但是我不确定是否代码错误/旧或图像不在正确的位置/位置。这是我到目前为止所写的内容。非常感谢帮助。拜托,谢谢。
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();
}
}
我在错误中得到的是:
线程“main”中的异常java.lang.NullPointerException
at javax.swing.ImageIcon。(Unknown Source)
在FirstGUI。(FirstGUI.java:39)
在FirstGUI.main(FirstGUI.java:50)
答案 0 :(得分:0)
首先您没有将标签添加到框架中,因此即使执行该标签也不会显示图像图标。所以不要忘记将标签添加到框架中:
add(label1);
add(label2);
第二次我尝试了你的代码,它对我来说运行正常,它只打印了我提到的错误,当我没有将图像图标导入到我工作的包中时。 为此你需要这样做:
右键点击你的src包 - >导入 - >一般 - >单击文件系统,然后单击next
并选择包含图像的目录,单击确定,然后添加您在代码中指定的图像。