javafx-2 - 在 javafx 的 ComboBox.setConverter 中使用 FormatStringConverter 的问题
问题描述
我必须使用组合框来关联值列表(键、值)。Key 是要存储在数据库中的值,Value 是要在组合框中显示的描述。
例如:
Key / value
C1 Code one
C2 Choice two
C3 Choice three
...
例如,检索选定的值“选择二”我想接收代码 C2。
为了将元素存储在项目中,我定义了 ComboVal 类。
定义我的组合框,我被困在 setConverter 函数的定义上。编译器给我以下错误:
错误:(1093, 49) java:类 javafx.util.converter.FormatStringConverter 中的构造函数 FormatStringConverter 不能应用于给定类型;必需:java.text.Format;发现:没有参数
原因:实际参数列表和形式参数列表的长度不同
代码:
class ComboVal {
String[] dato = {null, null};
ComboVal (String Key, String Value)
{
setValue(Key, Value);
}
ComboVal ()
{
setValue(null, null);
}
String getValue ()
{
return dato[1];
}
String getKey ()
{
return dato[0];
}
void setValue (String Key, String Value)
{
dato[0] = Key;
dato[1] = Value;
}
}
classe myclass {
....
/*
Parameter ctrl is a List containing information for dynamic creation of combobox
*/
void mothod (List ctrl)
{
VBox box = new VBox();
box.getChildren().add(new Label(ctrl. label));
ObservableList items = FXCollections.observableArrayList();
ComboBox<ComboVal> cb = new ComboBox<>();
cb.setId(ctrl.name);
cb.setItems(items);
//----->>> compiler report error in the next row <<<<<<<<
cb.setConverter(new FormatStringConverter<ComboVal>() {
@Override
public String toString (ComboVal object)
{
return (object.getValue());
}
@Override
public ComboVal fromString (String string)
{
return null;
}
});
ctrl.options.forEach((k, v) -> {items.add(new ComboVal(k, v));});
cb.setCellFactory(new Callback<ListView<ComboVal>, ListCell<ComboVal>>() {
@Override
public ListCell<ComboVal> call (ListView<ComboVal> p)
{
return new ListCell<ComboVal>() {
@Override
protected void updateItem (ComboVal item, boolean empty)
{
super.updateItem(item, empty);
if (item == null || empty)
{
setGraphic(null);
}
else
{
setGraphic(new Text(item.getValue()));
}
}
};
}});
box.getChildren().add(cb);
}
解决方案
该类FormatStringConverter
需要使用Format
参数构造。但是,您在没有参数的情况下构建了它。
提供 a Format
,例如:
Format format = new MessageFormat("Bla bla");
cb.setConverter(new FormatStringConverter<ComboVal>(format);
FormatStringConverter
已经定义了自己的方法toString
和fromString
方法,并将使用给定format
的来解析和显示值。我怀疑这是你想要的,因为这是非常有限的。
所以我认为你最好只使用常规并为andStringConverter
提供自定义实现。toString
fromString
推荐阅读
- php - 如何从价格计算中显示总计
- angular - 我在 WebLogic 12c 上部署的 Angular 应用程序重定向到 localhost 而不是实际的主机名
- vue.js - 材质图标字体文件 url 不正确
- flutter - 没有为“Uri”类型定义运算符“+”
- react-native - @walletconnect/client 抛出错误:尝试解析模块加密时
- python - 为什么多处理的每个进程开销不断增加?
- laravel - 如何向未经授权的客户隐藏网站的 Vue.js 管理面板代码
- reactjs - 如何防止 react-router 搞乱 API 路由
- linux - do_trap() 会导致 page_fault 吗?
- c++ - 如何从文本文件中按降序对时间戳进行排序