0

オブジェクトの配列を作成しようとすると、Java プログラムで問題が発生します。スレッド「メイン」の例外 java.lang.NullPointerException エラーは、私が得るエラーです。この場所で何時間も立ち往生しているので、本当に助けが必要です...

ご協力いただきありがとうございます !

public class Placement extends JFrame  {
    private JPanel placementPanel;

    private JFrame gameEngineFrame;




    private Ship[] boardShips; //Array of ships objects to save ships
    private JButton[] shipButton; //Array of buttons for the ships
    private JLabel selectShipLabel;
    private Ship shipSelected;
    private Ship highlightedShip;





        JPanel shipSelect = new JPanel();
        shipSelect.setLayout(new GridLayout(14, 1));
        shipSelect.setBackground(Color.getHSBColor(0.0F, 0.0F, 0.75F)); //Setting background color. Hue, saturation, brightness format. (HSB)
        shipSelect.setBounds(320, 20, 200, 300); //Setting postiion of the panel inside the JPanel and setting width & height
        this.placementPanel.add(shipSelect);     



     makeShips(shipSelect);

  private void makeShips(JPanel inPanel)
  {
      System.out.println("make ships testing");
    this.shipButton[0] = new JButton("Aircraft Carrier");
    boardShips[0] = new Ship(5, "Aircraft Carrier", 0);

    this.shipButton[1] = new JButton("Battleship");
    boardShips[1] = new Ship(4, "Battleship", 1);

    this.shipButton[2] = new JButton("Cruiser");
  boardShips[2] = new Ship(3, "Cruiser", 2);

    this.shipButton[3] = new JButton("Destroyer 1");
    boardShips[3] = new Ship(2, "Destroyer", 3);


    this.shipButton[4] = new JButton("Submarine 1");
    boardShips[4] = new Ship(1, "Submarine", 4);

  System.out.println("make ships testing22");

    for (int i = 0; i < 5; i++)
    {
      this.shipButton[i].setName("" + i);
     this.shipButton[i].addActionListener((ActionListener) this);
      inPanel.add(this.shipButton[i]);
      this.boardShips[i].makeIcons();
    }

  }

船舶クラス:

  public Ship(int tempSize, String tempName, int tempButton)
  {
    this();
    this.size = tempSize;
    this.name = tempName;
    this.button = tempButton;
   // this.shipCoords = new int[this.size][2];
    //this.shipIcons = new ImageIcon[2][this.size];
    //this.shipSunkIcons = new ImageIcon[2][this.size];
  }
4

1 に答える 1

2

これprivate JButton[] shipButton;はどこにも初期化されていない Jbutton の配列であり、this.shipButton[0] = new JButton("Aircraft Carrier");causin NPE を実行しようとしています。

5つのshipButton配列があることがわかりました

  JButton[] shipButton=new JButton[5];

編集

クラス本体からメソッドを呼び出すことはできません。そこでしかメソッドを定義できません。メソッドを呼び出すには、コンストラクターを使用するか、他のメソッドを使用する必要があります。

于 2013-04-12T18:25:41.883 に答える