Amorites
Amorites

Reputation: 65

How to set and get a private variable in javaFX?

I'm using the radioButton in javaFX to set a parameter.

public class SelectCOM extends Application {
private int comNum ;

public int getComNum() {
    return comNum;
}

public void setComNum() {
    launch();
}
    @Override
public void start(Stage primaryStage) {

    //......

    //OK BUTTON
     btn.setOnAction(new EventHandler<ActionEvent>() {
        @Override
        public void handle(ActionEvent event) {
            String str = tg.getSelectedToggle().toString();
            int begin = str.indexOf("COM");
            str = str.substring(begin+3, str.length()-1);
            comNum = Integer.parseInt(str);
            System.out.println(comNum);
            primaryStage.close();
        }
    });
}

When I call setComNum, the variable comNum is changed to the number I want. But getComNum just return 0.
Here is my calling method:

    SelectCOM selectCOM = new SelectCOM();
    selectCOM.setComNum();//After clicking the OK BUTTON about 3s, a 0 printed.
    int com = selectCOM.getComNum();
    System.out.println(com);

Upvotes: 1

Views: 558

Answers (1)

James_D
James_D

Reputation: 209714

The static launch() method in Application creates a new instance of your Application subclass, starts the JavaFX toolkit, and invokes start() on the instance it created. (The call to start() is made on the FX Application Thread.)

So you are setting the comNum value on the field in the instance created by the call to launch(), but you are calling getComNum() on the instance you created yourself (i.e. on a different object); hence you don't get the correct value.

Note also the launch() method, and consequently your setComNum() method, will not complete until the JavaFX Platform exits (by default this is when the user closes the last window).

Upvotes: 1

Related Questions