JavaFX - CheckListView 的 SelectionModel

问题描述
我有一个包含多个项目(复选框)的 CheckListView。我更改了选择模式(下面的代码)以允许多项选择。但是,当我选择多行(如下图所示)并按空格键时,只有“当前选定行”会更改状态。

我想要/需要:当我按空格时,切换所有选定的行状态。

我尝试调查处理程序,但我对要更改的内容感到困惑。

任何帮助是极大的赞赏。

https://img.mukewang.com/64ccda250001879602460212.jpg

        @FXML

        private CheckListView<String> checkListPermissoes;



        @Override

        public void initialize(URL url, ResourceBundle rb) {

            ...  checkListPermissoes.getSelectionModel().setSelectionMode(SelectionMode.MULTIPLE);


喵喵时光机
浏览 123回答 1
1回答

RISEBY

这是一个简单的解决方法,只需将 keyListener 注册到列表中,然后当您按 Space 时处理 JavaFx 未处理的项目:代码:public class Controller implements Initializable {&nbsp; &nbsp; @FXML private CheckListView<String> list;&nbsp; &nbsp; @Override&nbsp; &nbsp; public void initialize(URL location, ResourceBundle resources) {&nbsp; &nbsp; &nbsp; &nbsp; list.getSelectionModel().setSelectionMode(SelectionMode.MULTIPLE);&nbsp; &nbsp; &nbsp; &nbsp; list.getItems().addAll("Apple", "Lemon", "Orange", "Banana");&nbsp; &nbsp; &nbsp; &nbsp; list.setOnKeyPressed(event -> {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; if (event.getCode().equals(KeyCode.SPACE)) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; revertCheck(list.getSelectionModel().getSelectedIndices());&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; });&nbsp; &nbsp; }&nbsp; &nbsp; private void revertCheck(ObservableList<Integer> selectedIndices) {&nbsp; &nbsp; &nbsp; &nbsp; selectedIndices.forEach(index -> {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; // If needed to skip the selected index which is handled by JavaFx&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; if (!index.equals(list.getSelectionModel().getSelectedIndex())) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; if (list.getCheckModel().isChecked(index)) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; list.getCheckModel().clearCheck(index);&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; } else {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; list.getCheckModel().check(index);&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; });&nbsp; &nbsp; }}.fxml :<?xml version="1.0" encoding="UTF-8"?><?import javafx.scene.layout.AnchorPane?><?import org.controlsfx.control.CheckListView?><AnchorPane xmlns="http://javafx.com/javafx"&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; xmlns:fx="http://javafx.com/fxml"&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; fx:controller="checklist.Controller"><CheckListView fx:id="list"/></AnchorPane>
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Java