JavaFX Wombo组合显示文本,具体取决于下拉列表中的选择

时间:2019-06-17 19:50:27

标签: java javafx

如何在窗口中以例如以下形式显示文本:

目的地伦敦,高级折扣

我不太了解JavaFx,所以我尝试做类似的事情

package sample;

public class Main extends Application {


Stage window;
Scene scene;
Button button;
ComboBox<String> destinationBox, discountBox;


@Override
public void start(Stage primaryStage) throws Exception {

    window = primaryStage;
    window.setTitle("Tickets");


    destinationBox = new ComboBox<>();
    destinationBox.getItems().addAll(
            "Berlin", "London", "Madrid", "Moscow", "Paris", "Prague", "Rome"
    );

    discountBox = new ComboBox<>();
    discountBox.getItems().addAll(
            "Full price", "Senior", "Student"
    );
    discountBox.setValue("Full price");
    destinationBox.setValue("Berlin");
    Label label = new Label("Destination " + destinationBox.getValue() + " " + "discount " + discountBox.getValue());


    VBox layout = new VBox(10);
    layout.setPadding(new Insets(20, 20, 20, 20));
    layout.getChildren().addAll(label, discountBox, destinationBox);

    scene = new Scene(layout, 300, 250);
    window.setScene(scene);
    window.show();


}


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

1 个答案:

答案 0 :(得分:2)

唯一缺少的是对这两个组合框的value属性进行“反应”的代码段。尝试添加:

StringBinding binding = Bindings.createStringBinding(() -> "Destination " + destinationBox.getValue() + " " + "discount " + discountBox.getValue(), destinationBox.valueProperty(), discountBox.valueProperty());
Label label = new Label();
label.textProperty().bind(binding);