如何将字符串转换为ComboBoxModel

时间:2019-04-11 06:11:54

标签: java swing jframe jcombobox

我有2个jframe。我想要的是在第二个jframe的comboBox中可以看到nit“ 555”的值,输入的数据存储在CompanyClass中

enter image description here

enter image description here

comboBoxName.setModel(new CompanyClass().getNit());

getNit是一个字符串

2 个答案:

答案 0 :(得分:3)

请尝试以下声明

    String[] content = {"A", "B"}; // Here you can have model eg: CompanyClass
    JComboBox<String> cb = new JComboBox<String>();
    ComboBoxModel<String> model = cb.getModel();

    if (model instanceof DefaultComboBoxModel) {
        DefaultComboBoxModel dcbm = (DefaultComboBoxModel) model;
        dcbm.removeAllElements();
        for (String value : content) {
            dcbm.addElement(value);
        }
    }

答案 1 :(得分:1)

首先,您必须为模型定义标签。

String labels[] = { "A", "B", "C", "D", "E" };
DefaultComboBoxModel model = new DefaultComboBoxModel(labels);
JComboBox comboBoxName = new JComboBox();
comboBoxName.setModel(model);