我现在正在学习Java 3周,我想知道如何通过使用Listener来获得没有lambdas的ChoiceBox所选项目(只是字符串)的值。我不使用lambdas因为我想了解它背后的内容。我得到了以下代码:
public class Main extends Application {
public static void main(String[] args) {
launch(args);
}
@Override
public void start(Stage stage) throws Exception {
//BAUSTEINE:
ChoiceBox<String> choiceBox = new ChoiceBox<String>();
choiceBox.getItems().addAll("item1", "item2", "item3");
choiceBox.setValue("item1");
choiceBox.getSelectionModel().selectedItemProperty().addListener()
//THIS IS THE PLACE FOR THE LISTENER CODE WHICH I NEED ;)
//LAYOUT:
VBox vBox = new VBox();
vBox.setPadding(new Insets(20,20,20,20));
vBox.setSpacing(10);
vBox.getChildren().addAll(choiceBox);
//EIGENSCHAFTEN DER SCENE:
Scene scene = new Scene(vBox, 300, 250);
//EIGENSCHAFTEN DER STAGE:
stage.setScene(scene);
//PROGRAMMSTART:
stage.show();
}
}
答案 0 :(得分:1)
这三者完全相同:
choiceBox.getSelectionModel().selectedItemProperty().addListener(new ChangeListener<String>()
{
@Override
public void changed(ObservableValue<? extends String> observable, String oldValue, String newValue)
{
System.out.println(observable + oldValue + newValue);
}
});
choiceBox.getSelectionModel().selectedItemProperty().addListener((observable, oldValue, newValue) -> {
System.out.println(observable + oldValue + newValue);
});
choiceBox.getSelectionModel().selectedItemProperty().addListener((observable, oldValue, newValue) -> System.out.println(observable + oldValue + newValue));