为了说明我的意思,我们可以参考 Microsoft Excel。我想要的是这样的:
我正在使用 JavaFX 21 和 ControlsFX 11.2,并且目前正在使用 ControlsFX CheckComboBox,它工作得很好,但我确实需要 CheckComboBox 可搜索或至少可搜索前缀,因为当它出现时滚动列表非常困难长。
这是我的controlsFX CheckComboBox(你可以看到滚动它是多么烦人):
ControlsFX SearchableComboBox 也很棒,但只允许您一次选择一件事,并且多选功能是必需的。
我真正需要的是这两个人在一起生个孩子😂。但我找不到最好的方法。我尝试实现一个 CheckComboBoxUtils 类,但它似乎不起作用,因为它仍然只是在我的应用程序中将自身呈现为常规 CheckComboBox(我是一个 Java/JavaFX 新手)。
这是我的 CheckComboBoxUtils 类,我尝试在其中添加搜索功能:
package com.cartunesks.casa_pos;
import org.controlsfx.control.CheckComboBox;
import javafx.collections.ObservableList;
import javafx.scene.control.TextField;
import javafx.scene.layout.StackPane;
public class CheckComboBoxUtils {
public static void makeSearchable(CheckComboBox<String> checkComboBox) {
TextField searchField = new TextField();
searchField.setPromptText("Search");
StackPane button = (StackPane) checkComboBox.lookup(".combo-box-base");
button.getChildren().add(0, searchField);
ObservableList<String> items = checkComboBox.getItems();
searchField.textProperty().addListener((observable, oldValue, newValue) -> {
checkComboBox.getCheckModel().clearChecks(); // Clear checks when searching
if (newValue.isEmpty()) {
checkComboBox.getItems().setAll(items); // Restore full list when empty
return;
}
ObservableList<String> filteredItems = items.filtered(item -> item.toString().toLowerCase().contains(newValue.toLowerCase()));
checkComboBox.getItems().setAll(filteredItems);
});
}
}
我这样称呼它:
CheckComboBoxUtils.makeSearchable(makeCheckComboBox);
如果这很困难,我愿意接受其他解决方案。就像也许调整 ControlsFX CheckListView 并添加一个动态过滤项目列表的搜索栏?只是我的一个想法,但它确实不是最佳的,因为我更喜欢让现有的 CheckComboBox 可搜索。
对于像我这样正在寻找解决方案的新手,这里有一个简单有效的解决方案!它不是最漂亮的,但可以完成工作。
在复选框旁边添加一个文本字段,并添加一个监听器来过滤 CheckComboBox 中的 Observable 列表。
这就是它最终的样子:
将此方法添加到我的控制器中:
public void makeCheckComboBoxSearch() {
String searchText = makeTextField.getText().toLowerCase();
ObservableList<String> filteredItems = FXCollections.observableArrayList(
makes.stream().filter(item -> item.toLowerCase().startsWith(searchText)).collect(Collectors.toList())
);
makeCheckComboBox.getItems().setAll(filteredItems);
}
这就是我在initialize()方法中调用它的方式
//Lamda function to dynamically filter the CheckComboBox and show the CheckComboBox as the user types
makeTextField.textProperty().addListener((observable, oldValue, newValue) -> {
makeCheckComboBoxSearch(); // Filter items on text change
makeCheckComboBox.show(); // Open the dropdown
});