1

我在 this.commaPos = Name.indexOf(" ");的线程“AWT-EventQueue-0”java.lang.NullPointerException中遇到异常 我的项目线。这个概念是我有 5 个 JButton 的船,当你点击时,你把船放在一个战舰游戏的板上。现在很多时间我都被困在这上面。有任何想法吗 ?谢谢你。!

编辑:我将字符串名称的名称更改为字符串 nname。现在我在下一行得到同样的错误。this.commaPos = nname.indexOf(",");

 public void stateChanged(ChangeEvent event)
  {

    JButton currentButton = (JButton)event.getSource();
      System.out.println("STATE CHANGED");
    String nname = currentButton.getName();
    this.commaPos = nname.indexOf(",");
    int x = Integer.parseInt(nname.substring(0, commaPos));
    int y = Integer.parseInt(nname.substring(commaPos + 1));

    checkDeletable(x, y);

    if (currentButton.getName().equals(""))
      return;
    if (this.shipSelected == null) {
      return;
    }
    this.shipSelected.setPos(x, y);

    clearOldCoords();
    boolean valid = getShipCoords();
    paintShip(valid);

    if ((currentButton.isFocusOwner()) && (valid))
      placeShip();
  }

在这里,我使用更改侦听器:

{
 for (int y = 0; y < 10; y++) {
        for (int x = 0; x < 10; x ++) {
            this.myBoard[x][y] = new JButton();
            this.myBoard[x][y].setMargin(margins); 
            this.myBoard[x][y].setToolTipText(x + "," + y);
            this.myBoard[x][y].setName(null);
            this.myBoard[x][y].setIcon(this.sea);
            this.myBoard[x][y].addChangeListener(this);
            this.myBoard[x][y].addMouseListener(this);

            myBoard.add(this.myBoard[x][y]);

        }
    }
}
4

1 回答 1

4

名称(变量的错误名称,因为所有变量名称都应以小写字母开头)为空,可能是因为您从未设置过它。为什么还要担心 JButton 的名字呢?为什么不检查 actionCommand 呢?

您是 JButton 正在触发 ChangeListener 而不是 ActionListener,这似乎有点不寻常。你能给我们更多关于这段代码应该做什么的信息吗?

于 2013-04-14T23:29:55.747 回答