如何从 lambda 表达式中获取 return 值? (JavaFx- ChoiceBox addListener)

How to return value from lambda expression? (JavaFx- ChoiceBox addListener)

choiceBox.getSelectionModel().selectedItemProperty().addListener( (v, oldValue, newValue) -> {selectedColor = newValue.toString();});

System.out.println(selectedColor);

我想将 newValue 传递给 selectedColor 但在 lambda 之外它没有打印任何东西。

除非你提供更多关于你想要完成的事情的细节,否则我只能猜测什么对你有帮助。但是以下代码将使您的示例按照您描述的方式工作:

choiceBox.getSelectionModel().selectedItemProperty().addListener((v,oldValue,newValue) -> {
printSelection(newValue.toString());
});


private void printSelection(String selection){
    System.out.println(selection);
    //Here you can do what ever you need to do with the given value of 'selection'
}

为了获得更好的解决方案,您需要提供更多详细信息,说明您的目标是什么,您希望将 newValue 用于