gpt4 book ai didi

java - 将项目集合提供给 java FXML 中的自定义扩展组合框

转载 作者:行者123 更新时间:2023-11-30 11:09:26 27 4
gpt4 key购买 nike

我伸出援手是因为在使用我的自定义 FilterComboBox 时出现 NochSuchMethodException,因为我没有提供空的构造函数。构造函数需要扩展组合框的项目。

组合框控件:

import javafx.beans.value.ObservableValue;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.scene.control.ComboBox;
import javafx.scene.control.TextField;

public class FilterComboBoxTB extends ComboBox<String> {

private ObservableList<String> initialList;

public FilterComboBoxTB(ObservableList<String> items) {
super(items);
super.setEditable(true);
this.initialList = items;
this.configAutoFilterListener();
}

private void configAutoFilterListener() {
final FilterComboBoxTB currentInstance = this;
this.getEditor().textProperty().addListener(new ChangeListener<String>() {
@Override
public void changed(ObservableValue<? extends String> observable, String oldValue, String newValue) {
final TextField editor = currentInstance.getEditor();
final String selected = currentInstance.getSelectionModel().getSelectedItem();
if (selected == null || !selected.equals(editor.getText())) {
filterItems(newValue, currentInstance);
currentInstance.show();
}

}
});
}

private void filterItems(String filter, ComboBox<String> comboBox) {
ObservableList<String> filteredList = this.readFromList(filter, initialList);
comboBox.setItems(filteredList);
}

private ObservableList<String> readFromList(String filter, ObservableList<String> originalList) {
ObservableList<String> filteredList = FXCollections.observableArrayList();
for (String item : originalList) {
if (item.toLowerCase().indexOf(filter.toLowerCase())>-1) {
filteredList.add(item);
}
}
return filteredList;
}
}

FXML 数据集:

<?xml version="1.0" encoding="UTF-8"?>

<?import javafx.scene.layout.BorderPane?>
<?import javafx.scene.control.Label?>
<?import presentation.controls.FilterComboBoxTB?>

<BorderPane>
<top>
<FilterComboBoxTB **Method="GetItemsToPassToConstructor()"** />
</top>
<center>
<Label text="Some data here"/>
</center>
</BorderPane>

如何在FXML中指定方法获取相关参数?非常感谢和最好的问候

最佳答案

在 JavaFX 8(但不是早期版本)中,您可以通过使用 @NamedArg 注释构造函数参数来实现此目的。如果您按如下方式更新控件:

public class FilterComboBoxTB extends ComboBox<String> {

private ObservableList<String> initialList;

public FilterComboBoxTB(@NamedArg("items") ObservableList<String> items) {
super(items);
// code as before ...
}

// ...
}

然后在你的 FXML 中做

<FilterComboBoxTB>
<items>
<FXCollections fx:factory="observableArrayList">
<String value="Item 1" />
<String value="Item 2" />
<String value="Item 3" />
</FXCollections>
</items>
</FilterComboBoxTB>

(包含所有必要的导入)。

关于java - 将项目集合提供给 java FXML 中的自定义扩展组合框,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28159261/

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