如何让我的事件更改我的变量x?

时间:2017-02-15 02:06:00

标签: java javafx-8

package RockPaperScissors;

import javafx.application.Application;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.control.Label;
import javafx.scene.layout.*;
import javafx.stage.Stage;

public class Main extends Application{

    String x; 

    public static void main(String[] args){
        launch(args);
    }

    public void start(Stage primarystage) throws Exception{

        Stage window;
        window = primarystage;
        window.setTitle("Rock, Paper, Scissor");

        Button rockButton = new Button("Rock");
        rockButton.setLayoutX(50);
        rockButton.setLayoutY(50);
        rockButton.setPrefSize(50,20);
        rockButton.setOnAction(e -> System.out.println("Rock"));

        Button paperButton = new Button("Paper");
        paperButton.setLayoutX(120);
        paperButton.setLayoutY(50);
        paperButton.setPrefSize(50,20);
        paperButton.setOnAction(e -> System.out.println("Paper"));

        Button scissorButton = new Button("Scissor");
        scissorButton.setLayoutX(190);
        scissorButton.setLayoutY(50);
        scissorButton.setPrefSize(60, 20);
        scissorButton.setOnAction(e -> System.out.println("Scissor"));

        Label direction = new Label("Pick Rock, Paper, or Scissor:");
        direction.setLayoutX(50);
        direction.setLayoutY(30);

        Pane pane = new Pane();
        pane.getChildren().addAll(rockButton, paperButton, scissorButton, direction);

        Scene scene = new Scene(pane, 500, 400);

        window.setScene(scene);
        window.isFullScreen();
        window.show();
    }
}

我想更改变量,以便我可以与计算机生成的int进行比较。我也想知道如何更新标签的更新,以便用户可以看到结果。现在我只是在控制台中打印出用户选择的事件。我只是把它当作占位符。提前致谢。

1 个答案:

答案 0 :(得分:0)

例如,您可以将用户输入的变量转换为属性:

StringProperty x = new SimpleStringProperty();

属性所包含的字符串可以在按钮事件上更新,如下所示:

rockButton.setOnAction(e -> x.set("Rock"));
paperButton.setOnAction(e -> x.set("Paper"));
scissorButton.setOnAction(e -> x.set("Scissor"));

然后您可以像这样收听对该属性所做的更改:

x.addListener(new ChangeListener<String>(){

        @Override
        public void changed(ObservableValue<? extends String> observable, String oldValue, String newValue) {
            String outcome = "";
            //determine outcome depending on newValue.intern();
            outcomeLabel.setText(outcome);
        }           

}); 

语句newValue.intern();将为您提供更新后的字符串。您可以使用setText()方法更新要显示结果的标签。