the List of Items
对于您的第一种情况,在, 中使用监听器CheckListView
来检查是否添加了项目,或者,然后使用getSelectionModel().select(<Item>)
来选择它。
checkListView.getItems().addListener(new ListChangeListener<String>() {
@Override
public void onChanged(Change<? extends String> c) {
c.next();
if (c.wasAdded()) {
checkListView.getSelectionModel().select(c.getAddedSubList().get(0));
}
}
});
对于第二种情况,用于getCheckModel().getCheckedItems()
获取具有checked values
. 同样,检查一个项目是否已经added / removed
从列表中。
checkListView.getCheckModel().getCheckedItems().addListener(new ListChangeListener<String>() {
@Override
public void onChanged(ListChangeListener.Change<? extends String> c) {
c.next();
if(c.wasAdded()) {
System.out.println("Item Checked : " + c.getAddedSubList().get(0));
} else if (c.wasRemoved()) {
System.out.println("Item Unchecked : " + c.getRemoved().get(0));
}
}
});
完整的 MCVE -使用 ControlsFX 测试 - 8.40.9
import javafx.application.Application;
import javafx.collections.FXCollections;
import javafx.collections.ListChangeListener;
import javafx.collections.ObservableList;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.layout.VBox;
import javafx.stage.Stage;
import org.controlsfx.control.CheckListView;
public class Main extends Application {
public static void main(String[] args) {
launch(args);
}
@Override
public void start(Stage primaryStage) throws Exception {
final ObservableList<String> listOfItems = FXCollections.observableArrayList();
for (int i = 0; i <= 100; i++) {
listOfItems.add("Item " + i);
}
final CheckListView<String> checkListView = new CheckListView<>(listOfItems);
// Select the first checkListView element
checkListView.getItems().addListener(new ListChangeListener<String>() {
@Override
public void onChanged(Change<? extends String> c) {
c.next();
if (c.wasAdded()) {
checkListView.getSelectionModel().select(c.getAddedSubList().get(0));
}
}
});
// On CheckBox event
checkListView.getCheckModel().getCheckedItems().addListener(new ListChangeListener<String>() {
@Override
public void onChanged(ListChangeListener.Change<? extends String> c) {
c.next();
if(c.wasAdded()) {
System.out.println("Item Checked : " + c.getAddedSubList().get(0));
} else if (c.wasRemoved()) {
System.out.println("Item Unchecked : " + c.getRemoved().get(0));
}
}
});
Button button = new Button("Add");
button.setOnAction(e -> {
checkListView.getItems().add(0, "Itachi");
checkListView.requestFocus();
});
Scene scene = new Scene(new VBox(checkListView, button), 300, 275);
primaryStage.setTitle("Welcome");
primaryStage.setScene(scene);
primaryStage.show();
}
}
更新:用于检查新添加的项目复选框,而不是选择
利用 :
checkListView.getCheckModel().check(c.getAddedSubList().get(0));
代替
checkListView.getSelectionModel().select(c.getAddedSubList().get(0));
如果您希望它被选中并同时被选中,您可以使用both of them
.