0

I am looking for a way to make a button change from saying "Player 1 End Turn" to "Player 2 End Turn" when pressed. The following is what I have:

private int pTurn = 1;
        Button turn = new Button();
            turn.setText("Player " + pTurn + " End Turn");
            turn.setOnAction(new turnButton());

//There is code between these two blocks, but it isn't important for
//this question I don't think

        class turnButton implements EventHandler<ActionEvent> {
        @Override
        public void handle(ActionEvent event) {
            pTurn++;
            if (pTurn == 3) {
                pTurn = 1;
            }
            turn.setText("Player " + pTurn + " End Turn");
        }

    }

When I run this and press the button I get the following error:

Executing /Users/bronsonlane/NetBeansProjects/FinalProject/dist/run1715909217/FinalProject.jar using platform /Library/Java/JavaVirtualMachines/jdk1.8.0_111.jdk/Contents/Home/jre/bin/java
Exception in thread "JavaFX Application Thread" java.lang.NullPointerException
at halma.Halma$turnButton.handle(Halma.java:234)
at halma.Halma$turnButton.handle(Halma.java:227)
at com.sun.javafx.event.CompositeEventHandler.dispatchBubblingEvent(CompositeEventHandler.java:86)
at com.sun.javafx.event.EventHandlerManager.dispatchBubblingEvent(EventHandlerManager.java:238)
Bronson Lane
  • 45
  • 12

1 Answers1

-1

You need to declare the pTurn variable before Button turn. pTurn is not set and is returning null.

        int pTurn = 1;

        Button turn = new Button();
            turn.setText("Player " + pTurn + " End Turn");
            turn.setOnAction(new turnButton());

        class turnButton implements EventHandler<ActionEvent> {
        @Override
        public void handle(ActionEvent event) {
            pTurn++;
            if (pTurn == 3) {
                pTurn = 1;
            }
            turn.setText("Player " + pTurn + " End Turn");
        }

    }
  • Ah whoops. I have that implemented already but forgot to say so. – Bronson Lane Nov 28 '16 at 21:33
  • 1
    an `int` cannot be null. More over - a variable not being declared would never result in a `NullPointerException`, the code would simply not compile. – Itai Nov 28 '16 at 21:39