Java:JComboBox不接受enum.values()

时间:2015-03-25 15:23:08

标签: java swing enums jcombobox

所以我正在练习一个练习程序,我试图在jcombobox中使用Enum。我相信这对我的程序是一个很好的决定,因为组合框中的选项是常量,并且它们还有分配给它们的替代值(除了常量值之外的字符串名称),所以我觉得枚举是最好的方法去吧。

不幸的是,我无法让组合框接受来自枚举常量的完整值列表。我在下面粘贴了完整的代码。我在这里做错了什么?

public enum CurrencyTypes{

    USD ("US Dollars"),
    BPS ("British Pound Sterling"),
    E ("European Euros"),
    RR ("Russian Rubles"),
    JY ("Japanese Yen"),
    CY ("Chinese Yuan"),
    IR ("Indian Rupees"),
    NIS ("New Israeli Shekels");

    private String typeName;


    private CurrencyTypes(String typeName){
        this.typeName = typeName;
    }

    public String getTypeName(){
        return typeName;
    }

}

在下面的Driver类中,当我尝试使用CurrencyTypes.values()中的值列表初始化currencyBox时,程序失败。它编译得很好,但是当我运行程序时,我得到了java.lang.ExceptionInInitializerError并且它崩溃了。

public class AccountDriver{

    private String[] stringArray = new String[] { "", "test1", "test2", "test3" };
    private JComboBox<String> stringBox;
    private JComboBox<CurrencyTypes> currencyBox;
    private JLabel stringSelection;
    private String stringResult;
    private JLabel etSelection;
    private CurrencyTypes[] currencyArray;
    private ArrayList<CurrencyTypes> currencyArrayL;


    public AccountDriver(){


        JFrame testFrame = new JFrame();
        testFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);


        stringBox = new JComboBox<String>(stringArray);
        stringBox.addItemListener(new StringBoxListener());


        stringSelection = new JLabel(stringResult);


        currencyBox = new JComboBox<CurrencyTypes>(CurrencyTypes.values());


        testFrame.setLayout(new GridLayout(2, 2));
        testFrame.add(stringBox);
        testFrame.add(stringSelection);
        testFrame.add(currencyBox);

        testFrame.setVisible(true);
        testFrame.pack();
    }

    public static void main(String[] args){
        new AccountDriver();
    }

    private class StringBoxListener implements ItemListener{
        public void itemStateChanged(ItemEvent e){
            stringResult = String.valueOf(stringBox.getSelectedItem());
            System.out.println(stringResult);
            stringSelection.setText(stringResult);
        }
    }

    private class CurrencyBoxListener implements ItemListener{
        public void itemStateChanged(ItemEvent e){

        }
    }

}

2 个答案:

答案 0 :(得分:1)

我对ENUM一无所知,但是......组合框渲染需要一个toString()实现来显示组合框中的值。也许这需要在枚举中实现?

  

并且它们还具有分配给它们的备用值(除了常量值之外的字符串名称),

您还可以使用要在组合框中显示的两个值创建自定义POJO。有关简单示例,请参阅Combo Box With Custom Renderer

答案 1 :(得分:0)

尝试:

new JComboBox(CurrencyTypes.values());
相关问题