gpt4 book ai didi

java - GUI构建错误

转载 作者:行者123 更新时间:2023-12-01 13:50:00 24 4
gpt4 key购买 nike

我对 Java 还很陌生,并且不确定为什么在编译时会出现错误(在此之前没有显示错误)。错误是:

Exception in thread "main" java.lang.NullPointerException
at Lab10.<init>(Lab10.java:21)
at Lab10.main(Lab10.java:55)

我假设这表明数组为空?我尝试将它移到构造函数之前,但无论我做什么,它都会出现错误。在我实际使用用户输入作为数组之前,仅用一个空格对其进行初始化之前,存在数百个错误。我想做的只是一个简单的 GUI,如果您单击“添加类(class)”按钮,它会提示您输入类(class),并将其添加到 JList 中。我将不胜感激任何意见!谢谢!

import javax.swing.*;
import java.awt.*;
import java.util.Scanner;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

public class Lab10 extends JFrame implements ActionListener {

private static final long serialVersionUID = 1L;
int count = 0;
String subject;
private JList list;
private JButton button;
private JButton button2;
Scanner input = new Scanner(System.in);
String [] Courses;

@SuppressWarnings("unchecked")
public Lab10() {
JPanel p1 = new JPanel();
for (int j = 0 ; j < 100 ; j++) {
Courses[j] = " ";
}
p1.setLayout(new FlowLayout(FlowLayout.LEFT, 10, 10));
button = new JButton("Add Course");
button2 = new JButton("Close");
button.addActionListener(this);
button2.addActionListener(this);
add(button);
add(button2);

setLayout(new BorderLayout(10, 10));
list = new JList(Courses);
add(list, BorderLayout.CENTER);
add(p1, BorderLayout.SOUTH);
}

@Override
public void actionPerformed(ActionEvent e) {
if (e.getActionCommand().equals("Add Course")) {
System.out.println("Enter your new subject: ");
subject = input.next();
count++;
for (int i = 0 ; i <= count ; i++) {
if (Courses[i].equals(" ")) {
Courses[i] = subject;
}
}
}
else if (e.getActionCommand().equals("Close")) {
System.exit(0);
}
}

public static void main(String [] args) {
Lab10 frame = new Lab10();
frame.setTitle("Java");
frame.setSize(500, 600);
frame.setLocationRelativeTo(null);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
}

}

最佳答案

将其添加到构造函数的顶部:

this.Courses = new String[100];

更好的是,您实际上应该将 100 以及 for 循环条件中的 100 移至以下位置:

private static final int ARRAY_SIZE = 100;

然后将 100 的其他实例更改为 ARRAY_SIZE

另外,请注意,编译时不会发生NullPointerException;当您运行程序时就会发生这种情况。

关于java - GUI构建错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20038307/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com