我正在伸出手,因为我在使用自定义FilterComboBox时遇到NochSuchMethodException,因为我没有提供空构造函数。构造函数需要扩展组合框的Items。
Combobox控制:
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-Datei:
<?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中指定方法以获取相关参数? 非常感谢和最诚挚的问候
答案 0 :(得分:1)
在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>
(包含所有必要的进口)。