Pergunta

i am getting Exception in thread "AWT-EventQueue-0" java.lang.NullPointerException at this.commaPos = Name.indexOf(" "); line of my project. The concept is that i have 5 JButtons of ships, and when you click, you place the ship on a Board for a battleship game. Lot of time now i am stuck at this. Any ideas ? Thank you. !

EDIT: I changed the name of String name to String nname. Now i get the same error at the next line. 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();
  }

Here i use the change listener:

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

        }
    }
}
Foi útil?

Solução

Name (bad name for a variable since all variable names should begin with a lower case letter) is null and likely it's because you've never set it. Why worry about a JButton's name anyway? Why not check the actionCommand instead?

It seems a bit unusual that you're JButton is triggering a ChangeListener and not an ActionListener. Can you give us more information about what this bit of code is supposed to be doing?

Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top