gpt4 book ai didi

JavaFX - 过滤组合框

转载 作者:行者123 更新时间:2023-12-02 18:58:22 25 4
gpt4 key购买 nike

我想要一个组合框,它可以在用户键入时过滤列表项。它应该按如下方式工作:

  • 输入时,文本字段应显示一种可能的选择,但用户尚未输入的单词部分应突出显示。
  • 当他打开列表时,下拉菜单应该只显示可能的选项?
  • 在缩小可能的项目范围后,用户应使用箭头键选择剩余项目之一。
  • 过滤并不那么重要,跳到第一个匹配的选择也可以。

有类似的东西吗?

最佳答案

就下拉列表的过滤而言。将可能选项的列表包装在 FilteredList 中不是最好的解决方案吗?

MCVE:

import javafx.application.Application;
import javafx.application.Platform;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.collections.transformation.FilteredList;
import javafx.scene.Scene;
import javafx.scene.control.ComboBox;
import javafx.scene.control.TextField;
import javafx.scene.layout.HBox;
import javafx.stage.Stage;

public class MCVE extends Application {
public void start(Stage stage) {
HBox root = new HBox();

ComboBox<String> cb = new ComboBox<String>();
cb.setEditable(true);

// Create a list with some dummy values.
ObservableList<String> items = FXCollections.observableArrayList("One", "Two", "Three", "Four", "Five", "Six",
"Seven", "Eight", "Nine", "Ten");

// Create a FilteredList wrapping the ObservableList.
FilteredList<String> filteredItems = new FilteredList<String>(items, p -> true);

// Add a listener to the textProperty of the combobox editor. The
// listener will simply filter the list every time the input is changed
// as long as the user hasn't selected an item in the list.
cb.getEditor().textProperty().addListener((obs, oldValue, newValue) -> {
final TextField editor = cb.getEditor();
final String selected = cb.getSelectionModel().getSelectedItem();

// This needs run on the GUI thread to avoid the error described
// here: https://bugs.openjdk.java.net/browse/JDK-8081700.
Platform.runLater(() -> {
// If the no item in the list is selected or the selected item
// isn't equal to the current input, we refilter the list.
if (selected == null || !selected.equals(editor.getText())) {
filteredItems.setPredicate(item -> {
// We return true for any items that starts with the
// same letters as the input. We use toUpperCase to
// avoid case sensitivity.
if (item.toUpperCase().startsWith(newValue.toUpperCase())) {
return true;
} else {
return false;
}
});
}
});
});

cb.setItems(filteredItems);

root.getChildren().add(cb);

Scene scene = new Scene(root);
stage.setScene(scene);
stage.show();
}

public static void main(String[] args) {
launch();
}
}

关于JavaFX - 过滤组合框,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19010619/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com