请问各位:
    Swing的JComboBox控件怎样实现值和显示分离,达到例如web中combox控件一样的效果:
<select name="DownloadTrag" class="select_short">
<option value="1">未下载</option>
<option value="2">已下载</option>
<option value="">全部</option>
</select>
    即JComboBox显示的是未下载,而我getSelectItem()拿到的值是1

解决方案 »

  1.   

    import java.awt.BorderLayout;
    import java.awt.Container;
    import java.awt.event.ActionEvent;
    import java.awt.event.ActionListener;
    import javax.swing.JButton;
    import javax.swing.JComboBox;
    import javax.swing.JDialog;
    import javax.swing.JFrame;
    import javax.swing.JOptionPane;class Item
    {
    private String id;
    private String name;
    public String getId()
    {
    return id;
    }
    public void setId(String id)
    {
    this.id = id;
    }
    public String getName()
    {
    return name;
    }
    public void setName(String name)
    {
    this.name = name;
    }
    public Item(String id,String name)
    {
    this.id=id;
    this.name=name;
    }
    public String toString()
    {
    return name;
    }
    }
    public class JComboBoxTest
    {
    public static void main(String[] args)
    {
    final JFrame frame=new JFrame("JComboBox Demo");
    final JComboBox comboBox=new JComboBox();
    comboBox.addItem(new Item("a","nameA"));
    comboBox.addItem(new Item("b","nameB"));
    comboBox.addItem(new Item("c","nameC"));
    comboBox.addItem(new Item("d","nameD"));
    Container c=frame.getContentPane();
    c.setLayout(new BorderLayout());
    c.add(comboBox,BorderLayout.NORTH);
    JButton b=new JButton("OK");
    c.add(b,BorderLayout.SOUTH);
    b.addActionListener(new ActionListener(){ public void actionPerformed(ActionEvent e)
    {
    int index=comboBox.getSelectedIndex();
    // JOptionPane.showMessageDialog(frame, comboBox.getItemAt(index));
    Item item=(Item)comboBox.getItemAt(index);
    System.out.println("the Id is: "+item.getId()+"     the name is: "+item.getName());
    }
    });
    frame.setSize(200,200);
    frame.setVisible(true);
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    }
    }
    你可以这样,自定义一个类,包括id和value属性,然后重写它的toString方法
    具体自己看上面的代码
      

  2.   

    简单点:JComboBox里面的item可以是一个对象 而一个对象可以有几个变量 那几个变量就可以代表你的web的下拉列表的 值 和 名称 啦
      

  3.   

    jComboBox2.getSelectedItem()可以得到显示的的字符串例如"aa","bb","cc";而jComboBox2.getSelectedIndex()可以得到索引例如1,2,3,完全可以把索引当成值使用
      

  4.   

    可以在一个ArrayList(名为:list)里存储对应的值,在JComboBox(名为:cb)里选择了某个Item时,那么她所对应的值就是:list.get(cb.getSelectedIndex()).toString()
      

  5.   

    只是一个对象object,而显示的内容是object.toString()方法返回的值,因此重写toString()方法即可