首页 > 解决方案 > 在 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);
}

标签: javafx-2

解决方案


该类FormatStringConverter需要使用Format参数构造。但是,您在没有参数的情况下构建了它。

提供 a Format,例如:

Format format = new MessageFormat("Bla bla");

cb.setConverter(new FormatStringConverter<ComboVal>(format);

FormatStringConverter已经定义了自己的方法toStringfromString方法,并将使用给定format的来解析和显示值。我怀疑这是你想要的,因为这是非常有限的。

所以我认为你最好只使用常规并为andStringConverter提供自定义实现。toStringfromString


推荐阅读