我正在使用 ControlsFX 中的 CheckComboBox 控件项目。
但我想创建一个自定义规则:
当您单击 Item0 时,它应该清除所有其他选择。 如果再次单击 Item0,它将保持选中状态。 如果您选择 Item(X),它将清除 Item0 并选择 Item(X)。
这个想法是 Item0 应该是“All”选项。
编辑:此解决方案适用于 ControlsFX。
最佳答案
我对 ControlsFX 不太熟悉,但稍微搞了一下,我想我找到了解决您问题的方法。下面是一个完整的例子。我希望评论能解决任何问题。
import org.controlsfx.control.CheckComboBox;
import javafx.application.Application;
import javafx.collections.FXCollections;
import javafx.collections.ListChangeListener;
import javafx.collections.ObservableList;
import javafx.scene.Scene;
import javafx.scene.layout.VBox;
import javafx.stage.Stage;
public class Main extends Application {
public void start(Stage mainStage) throws Exception {
ObservableList<String> items = FXCollections.observableArrayList();
items.addAll(new String[] { "All", "Item 1", "Item 2", "Item 3", "Item 4" });
CheckComboBox<String> controll = new CheckComboBox<String>(items);
controll.getCheckModel().getCheckedItems().addListener(new ListChangeListener<String>() {
public void onChanged(ListChangeListener.Change<? extends String> c) {
while (c.next()) {
if (c.wasAdded()) {
if (c.toString().contains("All")) {
// if we call the getCheckModel().clearChecks() this will
// cause to "remove" the 'All' too at least inside the model.
// So we need to manually clear everything else
for (int i = 1; i < items.size(); i++) {
controll.getCheckModel().clearCheck(i);
}
} else {
// check if the "All" option is selected and if so remove it
if (controll.getCheckModel().isChecked(0)) {
controll.getCheckModel().clearCheck(0);
}
}
}
}
}
});
Scene scene = new Scene(controll);
mainStage.setScene(scene);
mainStage.show();
}
public static void main(String[] args) {
launch(args);
}
}
关于java - 自定义检查组合框,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46960776/