gpt4 book ai didi

JavaFX TextField 自动建议

转载 作者:行者123 更新时间:2023-12-04 16:17:56 31 4
gpt4 key购买 nike

我想让这个 TextField 像在 Lucene 中一样具有建议功能。我搜索了所有的网络,我只找到了 ComboBox。

TextField instNameTxtFld = instNameTxtFld();

private TextField instNameTxtFld() {
TextField txtFld = new TextField();
txtFld.setPrefSize(600, 75);
return txtFld;
}

之所以不能使用ComboBox的方法是因为如果我使用ComboBox,我无法将值输入到下面的数据库中。
private void goNext() {

if (nameTxtFld.getText() == null || nameTxtFld.getText().trim().isEmpty()
|| instNameTxtFld.getText()== null || instNameTxtFld.getText().trim().isEmpty()
|| addTxtArea.getText() == null || addTxtArea.getText().trim().isEmpty()) {
alertDialog.showAndWait();
} else {
String satu = idNumTxtFld.getText();
String dua = nameTxtFld.getText();
String tiga = addTxtArea.getText();
String empat = instNameTxtFld.getText();
int delapan = idType.getSelectionModel().getSelectedIndex();
String sembilan = timeStamp.getText();
try {
KonekDB.createConnection();
Statement st = KonekDB.conn.createStatement();
String sql = "INSERT INTO privateguest"
+ "(idNumber, name, address, institution, idType, startTime) "
+ "VALUES "
+ "('" + satu + "','" + dua + "','" + tiga + "','" + empat + "','" + delapan + "','" + sembilan + "')";

System.out.println(sql);
st.executeUpdate(sql);

} catch (SQLException ex) {

System.out.println(satu + " " + dua + " " + tiga + " " + empat + " " + delapan + " " + sembilan);
System.out.println("SQL Exception (next)");
ex.printStackTrace();
}
Frame3Private frame3 = new Frame3Private(english);
this.getScene().setRoot(frame3);
}

}

请帮助我制作最简单的代码来执行 TextField 建议/自动完成。

最佳答案

这是我基于 This 的解决方案.

public class AutocompletionlTextField extends TextFieldWithLengthLimit {
//Local variables
//entries to autocomplete
private final SortedSet<String> entries;
//popup GUI
private ContextMenu entriesPopup;


public AutocompletionlTextField() {
super();
this.entries = new TreeSet<>();
this.entriesPopup = new ContextMenu();

setListner();
}


/**
* wrapper for default constructor with setting of "TextFieldWithLengthLimit" LengthLimit
*
* @param lengthLimit
*/
public AutocompletionlTextField(int lengthLimit) {
this();
super.setLengthLimit(lengthLimit);
}


/**
* "Suggestion" specific listners
*/
private void setListner() {
//Add "suggestions" by changing text
textProperty().addListener((observable, oldValue, newValue) -> {
String enteredText = getText();
//always hide suggestion if nothing has been entered (only "spacebars" are dissalowed in TextFieldWithLengthLimit)
if (enteredText == null || enteredText.isEmpty()) {
entriesPopup.hide();
} else {
//filter all possible suggestions depends on "Text", case insensitive
List<String> filteredEntries = entries.stream()
.filter(e -> e.toLowerCase().contains(enteredText.toLowerCase()))
.collect(Collectors.toList());
//some suggestions are found
if (!filteredEntries.isEmpty()) {
//build popup - list of "CustomMenuItem"
populatePopup(filteredEntries, enteredText);
if (!entriesPopup.isShowing()) { //optional
entriesPopup.show(AutocompletionlTextField.this, Side.BOTTOM, 0, 0); //position of popup
}
//no suggestions -> hide
} else {
entriesPopup.hide();
}
}
});

//Hide always by focus-in (optional) and out
focusedProperty().addListener((observableValue, oldValue, newValue) -> {
entriesPopup.hide();
});
}


/**
* Populate the entry set with the given search results. Display is limited to 10 entries, for performance.
*
* @param searchResult The set of matching strings.
*/
private void populatePopup(List<String> searchResult, String searchReauest) {
//List of "suggestions"
List<CustomMenuItem> menuItems = new LinkedList<>();
//List size - 10 or founded suggestions count
int maxEntries = 10;
int count = Math.min(searchResult.size(), maxEntries);
//Build list as set of labels
for (int i = 0; i < count; i++) {
final String result = searchResult.get(i);
//label with graphic (text flow) to highlight founded subtext in suggestions
Label entryLabel = new Label();
entryLabel.setGraphic(Styles.buildTextFlow(result, searchReauest));
entryLabel.setPrefHeight(10); //don't sure why it's changed with "graphic"
CustomMenuItem item = new CustomMenuItem(entryLabel, true);
menuItems.add(item);

//if any suggestion is select set it into text and close popup
item.setOnAction(actionEvent -> {
setText(result);
positionCaret(result.length());
entriesPopup.hide();
});
}

//"Refresh" context menu
entriesPopup.getItems().clear();
entriesPopup.getItems().addAll(menuItems);
}


/**
* Get the existing set of autocomplete entries.
*
* @return The existing autocomplete entries.
*/
public SortedSet<String> getEntries() { return entries; }
}

您必须从“TextField”而不是“TextFieldWithLengthLimit”扩展,并删除带有“长度限制”的构造函数。

我使用静态方法来处理样式。此处用于在建议结果中“突出显示”输入的文本。这是这个类的方法代码:
/**
* Build TextFlow with selected text. Return "case" dependent.
*
* @param text - string with text
* @param filter - string to select in text
* @return - TextFlow
*/
public static TextFlow buildTextFlow(String text, String filter) {
int filterIndex = text.toLowerCase().indexOf(filter.toLowerCase());
Text textBefore = new Text(text.substring(0, filterIndex));
Text textAfter = new Text(text.substring(filterIndex + filter.length()));
Text textFilter = new Text(text.substring(filterIndex, filterIndex + filter.length())); //instead of "filter" to keep all "case sensitive"
textFilter.setFill(Color.ORANGE);
textFilter.setFont(Font.font("Helvetica", FontWeight.BOLD, 12));
return new TextFlow(textBefore, textFilter, textAfter);
}

您可以在 FXML(不要忘记“导入”)或构造函数中添加此“AutocompletionlTextField”。要在使用“条目”getter 时设置“建议”列表:
AutocompletionlTextField field = new AutocompletionlTextField();
field.getEntries().addAll(YOUR_ARRAY_OF_STRINGS);

在我的应用程序中似乎是这样:
enter image description here

希望能帮助到你。

关于JavaFX TextField 自动建议,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36861056/

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