我有以下问题:
listView.getSelectionModel().selectedItemProperty().addListener((obs, oldV, newV) -> {
if (!selectionChanged(newV)) {
lististView.getSelectionModel().select(oldV);
}
});
selectionChanged(newV) 只需弹出一个消息框,其中显示“您想选择新值?”并将结果作为 boolean 值返回。当我点击取消时,它返回 false,因此条件为 true。但因为 .select(oldV);这会导致循环。如何取消或回滚 javafx listview 中的选择?
最佳答案
创建一个 boolean 标志,如果未设置,则不询问用户。您需要在 Platform.runLater(...)
中将更改包装回原始值(如果用户否决更改),以避免选择模型的 selectedItems< 中出现冲突问题
list(基本上,在处理另一个列表更改时您无法更改列表)。
private boolean checkSelectionChange = true ;
// ...
listView.getSelectionModel().selectedItemProperty().addListener((obs, oldV, newV) -> {
if (checkSelectionChange) {
checkSelectionChange = false ;
Platform.runLater(() -> {
if (!selectionChanged(newV)) {
lististView.getSelectionModel().select(oldV);
}
checkSelectionChange = true ;
});
}
});
SSCCE:
import javafx.application.Application;
import javafx.application.Platform;
import javafx.scene.Scene;
import javafx.scene.control.Alert;
import javafx.scene.control.Alert.AlertType;
import javafx.scene.control.ButtonType;
import javafx.scene.control.ListView;
import javafx.stage.Stage;
public class ListViewSelectionUserVeto extends Application {
private boolean checkSelectionChange = true ;
@Override
public void start(Stage primaryStage) {
ListView<String> listView = new ListView<>();
listView.getItems().addAll("One", "Two", "Three", "Four");
listView.getSelectionModel().selectedItemProperty().addListener((obs, oldValue, newValue) -> {
if (checkSelectionChange) {
checkSelectionChange = false ;
Platform.runLater(() -> {
if (! verifySelectionChange(newValue)) {
listView.getSelectionModel().select(oldValue);
}
checkSelectionChange = true ;
});
}
});
Scene scene = new Scene(listView);
primaryStage.setScene(scene);
primaryStage.show();
}
private boolean verifySelectionChange(String newValue) {
Alert alert = new Alert(AlertType.CONFIRMATION);
alert.setContentText("Change selection to "+newValue);
return alert.showAndWait().filter(ButtonType.OK::equals).isPresent();
}
public static void main(String[] args) {
launch(args);
}
}
关于java - selectedItem PropertyChanged 取消事件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44659471/