带JButton数组的空指针

时间:2014-04-09 03:49:02

标签: java arrays swing nullpointerexception jbutton

到目前为止,我已经在添加我的ControlPanel类时创建了一个框架,该类采用了一个int,并且该int用于使用添加到Panel并显示的JButton对象填充数组。

但是当我尝试将JButtons添加到数组时,我收到Null指针错误。我不确定为什么(因为我认为空指针来自于你尝试引用不在数组中的位置的东西?)

对此的任何帮助都将非常感激。

错误讯息:

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.

            }
        }
    }

}

3 个答案:

答案 0 :(得分:3)

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))); 

初始化数组以反映您的需求,同时,不要使用floorButton[i].add,您不想添加按钮(当前是null元素)按钮,您想将其分配给数组的位置......

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做同样的事情......

答案 1 :(得分:2)

您必须初始化floorButton

    floorButton = new JButton [yourCount];

答案 2 :(得分:1)

您创建了JButton数组,但未创建数组中的每个元素。要做到这一点:

替换它:

 floorButton[i].add(new JButton("F" + Integer.toString(i)));

由此:

 floorButton[i] = new JButton("F" + Integer.toString(i));