selectedItemPropertyChanged取消事件

时间:2017-06-20 17:25:45

标签: java javafx

我有以下问题:

listView.getSelectionModel().selectedItemProperty().addListener((obs, oldV, newV) -> {
            if (!selectionChanged(newV)) {
                lististView.getSelectionModel().select(oldV);
            }

    });

selectionChanged(newV)只弹出一个消息框,其中包含“你想选择新值吗?”并将结果作为布尔值返回。当我点击取消它返回false,这样条件为真。但是因为.select(oldV);它会导致循环。如何在javafx listview中取消或回滚选择?

1 个答案:

答案 0 :(得分:2)

创建一个布尔标志,不要询问用户是否设置了它。您需要在Platform.runLater(...)中将更改包装回原始值(如果用户否决更改),以避免选择模型selectedItems列表中的冲突问题(基本上您无法更改)正在处理另一个列表更改时的列表。)

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);
    }
}