2014-11-05 10:50:54

JavaSwing JComboBox模拟html的select标签

JComboBox默认不支持name属性设置,getSelectedItem()默认返回的是String。实际上可以模仿原生的DefaultComboBoxModel实现一个自己的DefaultComboBoxModel。

DefaultComboBoxModel.java

package org.javaweb.swing.ui;
import java.util.Vector;
import javax.swing.AbstractListModel;
import javax.swing.ComboBoxModel;
/**
 * 实现默认ComboBoxModel
 *
 * @author yz
 */
public class DefaultComboBoxModel extends AbstractListModel implements ComboBoxModel {
    private Object selectedItem;
    Vector<JComboBoxItem> objects;
    public DefaultComboBoxModel(Vector<JComboBoxItem> objects) {
        this.objects = objects;
    }
    @Override
    public Object getSelectedItem() {
        if (selectedItem != null) {
            return selectedItem;
        } else {
            return objects.get(0).getValue();
        }
    }
    @Override
    public void setSelectedItem(Object newValue) {
        selectedItem = newValue;
    }
    @Override
    public int getSize() {
        return objects.size();
    }
    @Override
    public Object getElementAt(int i) {
        return objects.get(i);
    }
}

封装好了model对象,现在需要的是JComboBox的选中对象Item。我的想法是自己封装一个JComboBoxItem这样选中的时候返回JComboBoxItem对象。当DefaultComboBoxModel调用getSelectedItem的时候返回我们自己的JComboBox,再重写toString方法,这样可以按照自己的意愿只输出JComboBox的value。

JComboBoxItem.java

package org.javaweb.swing.ui;
/**
 * JComboBox选择项,JComboBox选中时getSelectedItem默认实现返回的只是字符串 JComboBoxItem
 * 类可以提供key、value. 模拟HTML的select标签
 *
 * @author yz
 */
public class JComboBoxItem {
    private String key;
    private String value;
    public JComboBoxItem(String key, String value) {
        this.key = key;
        this.value = value;
    }
    public String getKey() {
        return key;
    }
    public void setKey(String key) {
        this.key = key;
    }
    public String getValue() {
        return value;
    }
    public void setValue(String value) {
        this.value = value;
    }
    @Override
    public String toString() {
        return this.getValue();
    }
}

调用部分代码:

List<Type> typeList = typeDAO.getTypeByParentId(0);
        Vector<JComboBoxItem> ls = new Vector<JComboBoxItem>();
        for(Type t:typeList){
            ls.add(new JComboBoxItem(String.valueOf(t.getId()),t.getTypeName()));
        }
        jComboBox1 = new JComboBox(new DefaultComboBoxModel(ls));

点击事件后获取key value:

private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {                                         
        JComboBoxItem item = (JComboBoxItem) jComboBox1.getSelectedItem();
        System.err.println(item.getKey() + ":" + item.getValue());
    }

输出:10:New

发表回复