繁体   English   中英

JComboBox中来自枚举的人类可读值

[英]Human Readable Value from Enum in JComboBox

有没有一种方法可以从Enum的字段中提取信息并将其显示在JComboBox中而不是名称中? 如果我的问题不明确或不清楚,我谨向您致歉。

这是我正在使用的枚举的简化版:

 public enum Country {

    AF("af", "Afghanistan"),

    ...

    ZW("zw", "Zimbabwe");

    private String nameCode;

    private String displayName;

    private Country(String code, String name) {
        this.nameCode = code;
        this.displayName = name;
    }

    public String getNameCode() {
        return this.nameCode;
    }

    public String getDisplayName() {
        return this.displayName;
    }

    @Override
    public String toString() {
        return this.displayName;
    }

}

我在以下JComboBox中使用它:

JComboBox<Country> boxCountry = new JComboBox<>();
boxCountry.setModel(new DefaultComboBoxModel<>(Country.values()));
inputPanel.add(boxCountry);

但是,组合框显示枚举值的名称(AF,ZW等)。 有没有办法让它显示displayName呢? 我以为也许重写toString方法可以解决该问题,但这没什么区别。 尽管看起来很简单(而且很常见),但是我在Java中根本找不到任何东西(我确实找到了有关如何在C#中执行此操作的答案……太糟糕了,我不使用C#)。

先感谢您!

您的问题和代码不匹配。 JComboBox应该显示国家/地区的displayName,因为这是枚举的toString()重写返回的内容。

实际上,当我对其进行测试时,这就是我看到的:

import javax.swing.JComboBox;
import javax.swing.JOptionPane;
import javax.swing.JScrollPane;

public class TestCombo {
   public static void main(String[] args) {
      JComboBox<Country> countryBox = new JComboBox<Country>(Country.values());
      JOptionPane.showMessageDialog(null, new JScrollPane(countryBox));
   }
}

enum Country {

   AF("af", "Afghanistan"),

   US("us", "United States"),

   ZW("zw", "Zimbabwe");

   private String nameCode;

   private String displayName;

   private Country(String code, String name) {
       this.nameCode = code;
       this.displayName = name;
   }

   public String getNameCode() {
       return this.nameCode;
   }

   public String getDisplayName() {
       return this.displayName;
   }

   @Override
   public String toString() {
       return this.displayName;
   }

}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM