【问题标题】:JavaFX ComboBox displaying object not it's propertyJavaFX ComboBox 显示对象而不是它的属性
【发布时间】:2018-05-21 12:21:40
【问题描述】:

我已经用组合框构建了 GUI。我有ObservableList<SimpleTableObject> types 应该显示材料的类型。看起来是这样的

 material_comboBox_type.getItems().addAll(types);

    material_comboBox_type.setCellFactory((ListView<SimpleTableObject> 
    param) -> {
          final ListCell<SimpleTableObject> cell = new 
     ListCell<SimpleTableObject>() {                
            @Override
            public void updateItem(SimpleTableObject item, boolean empty) {
                super.updateItem(item, empty);
                if (item != null) {

                    setText(item.getName().get());//return String, actuall name of material

                }
                else {
                    setText(null);
                }
            }
        };
        return cell;
    });

现在的问题是:当我单击组合框时,它会根据需要显示名称。但是当我选择一个而不是字符串属性时,会显示一个对象本身,看起来像classes.SimpleTableObject@137ff5c

我怎样才能实现它?

【问题讨论】:

    标签: javafx combobox observablecollection


    【解决方案1】:

    组合框中的选定项目显示在名为buttonCell 的单元格中。因此,您需要设置纽扣电池以及电池工厂(在下拉菜单中生成电池)。

    为此,将单元实现重构为(命名的)内部类可能更容易:

    private static class SimpleTableObjectListCell extends ListCell<SimpleTableObject> {
    
        @Override
        public void updateItem(SimpleTableObject item, boolean empty) {
            super.updateItem(item, empty);
            if (item != null) {
    
                setText(item.getName().get());//return String, actuall name of material
    
            }
            else {
                setText(null);
            }
        }
    
    }
    

    然后:

    materialComboBoxType.setCellFactory(listView -> new SimpleTableObjectListCell());
    materialComboBoxType.setButtonCell(new SimpleTableObjectListCell());
    

    【讨论】:

    • 该类也可以在方法中声明。您也可以简单地使用工厂来创建纽扣电池:materialComboBoxType.setButtonCell(materialComboBoxType.getCellFactory().call(null));
    • @fabian materialComboBoxType.call(null) -> materialComboBoxType.getCellFactory().call(null)
    【解决方案2】:

    好的,我用转换器做了这个:

    material_comboBox_type.setConverter(new StringConverter<SimpleTableObject>() {
            @Override
            public String toString(SimpleTableObject object) {
                return object.getName().get();
            }
    
            @Override
            public SimpleTableObject fromString(String string) {
                throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
            }
        });
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-08-07
      • 1970-01-01
      • 1970-01-01
      • 2022-01-23
      相关资源
      最近更新 更多