到目前为止,我已经在添加我的 ControlPanel 类时创建了一个框架,该类采用一个 int,并且该 int 用于用 JButton 对象填充数组,这些对象被添加到 Panel 并显示。
但是,当我尝试将 JButtons 添加到数组时,出现空指针错误。我不确定为什么(因为我认为空指针是在您尝试引用数组中不存在的内容时产生的?)
如有任何帮助,我们将不胜感激。
错误信息:
Exception in thread "main" java.lang.NullPointerException
at elevator.ControlPanel.<init>(ControlPanel.java:22)
at elevator.Elevator_Simulator.main(Elevator_Simulator.java:27)
主类
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import javax.swing.event.*;
public class Elevator_Simulator extends JFrame {
public static void main(String[] args) {
JFrame frame = new JFrame ("Elevator Simulation");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().add(new ControlPanel(8));
frame.pack();
frame.setVisible(true);
}
}
控制面板类:
import java.awt.Color;
import java.awt.event.*;
import javax.swing.*;
public class ControlPanel extends JPanel implements ActionListener {
public JButton[] floorButton; // an array of floor buttons.
public int[] floorIn; // state of button. 0 == not click >= 1 means clicked (how many times).
public ControlPanel(int x) {
JPanel floors = new JPanel();
for (int i = 0; i < x; i++) { // interates through user input and creates that many JButtons.
floorButton[i].add(new JButton("F" + Integer.toString(i))); // adds a button to button array. Sets text to F(floorNo).
floors.add(floorButton[i]); // adds buttons to the floor panel.
floorButton[i].addActionListener(this); // adds action listener to the buttons.
}
}
public void actionPerformed(ActionEvent e) {
for (int i = 0; i < floorButton.length; i++) {
if (e.getSource() == floorButton[i]) { // checks which button the event occured on.
floorButton[i].setBackground(Color.red); // sets button background to red.
floorButton[i].setText(floorButton[i].getText() + "(1)"); // marks button as clicked.
}
}
}
}
最佳答案
floorButton
没有初始化为任何东西...
public JButton[] floorButton; // I'm null
public ControlPanel(int x) {
//...
for (int i = 0; i < x; i++) { // in
// Still null
floorButton[i].add(new JButton("F" + Integer.toString(i)));
初始化数组以反射(reflect)您的需要,另外,不要使用 floorButton[i].add
,您不想将按钮添加到(当前是 null
element) 按钮,你想把它赋值到数组的位置...
public ControlPanel(int x) {
//...
floorButton = new JButton[x];
for (int i = 0; i < x; i++) { // in
floorButton[i] = new JButton("F" + Integer.toString(i));
我猜你会想对 floorIn
做同样的事情......
关于java - JButton 数组的空指针,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22952405/