【问题标题】:How to store the JComboBox item in 2 variables?如何将 JComboBox 项存储在 2 个变量中?
【发布时间】:2014-03-10 18:54:11
【问题描述】:

我有一个由 hashmap 填充的 Jcombo 框(每个 JComboBox 项与一个 hashmap 对象相等 - 由 2 个值格式化:一个键和一个值)。 当我使用 getSelectedItem() - 返回类似的东西:key=value;

我需要将键存储在一个变量中,将值存储在另一个变量中。

我该怎么做? JComboBox 是否存在另一种方法来为 JComboBox 的每个项目存储 2 个值?

【问题讨论】:

    标签: select hashmap key jcombobox


    【解决方案1】:

    我收到了你的问题。这是一个非常简单的 JComboBox 类。你可以通过阅读代码来了解过程并根据需要进行修改

    import java.util.ArrayList;
    import java.util.Map;
    import javax.swing.DefaultComboBoxModel;
    import javax.swing.JComboBox;
    
    public class JComboBoxPair<K, E> extends JComboBox<E> {
    
    private ArrayList<Object> key_array;
    
    public JComboBoxPair() {
        this.key_array = new ArrayList<>();
    }
    
    public void setModel(Map<String, String> map) {
        DefaultComboBoxModel boxModel = new DefaultComboBoxModel(map.values().toArray());
        super.setModel(boxModel);
        key_array.clear();
        key_array = new ArrayList<>(map.keySet());
    }
    
    public String[] getSelectedItemInfoArray() {
        String[] ar = new String[2];
        ar[0] = key_array.get(super.getSelectedIndex()).toString();
        ar[1] = super.getSelectedItem().toString();
        return ar;
    }
    
    @Override
    public String getSelectedItem() {
        return super.getSelectedItem().toString();
    }
    
    public String getSelectedKey() {
        return key_array.get(super.getSelectedIndex()).toString();
    }
    
    }
    

    【讨论】:

      猜你喜欢
      • 2012-07-10
      • 1970-01-01
      • 2018-01-31
      • 1970-01-01
      • 2014-04-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-02-16
      相关资源
      最近更新 更多