数据库里的字段  id name 
我要在Java swi中的JCombox 里面显示
  选中name下拉列表对应的索引 就是name字段的Id  
name要显示在下拉列表里面 用 addItem就可以
id   下拉列表索引怎么添加啊?

解决方案 »

  1.   

    Jcombox 如何向HTML里面的下拉列表框一样<html>
    <select>
    <option value="3">张三</option>
    <option value="5">李四</option>
    <option value="7">王五</option>
    </select>
    </html>这样可以和数据库的 id 和 姓名对应起来。
    Id和name都是动态获取的  
    怎么添加到JCombox里面
      

  2.   

    看到swing直接走人,还是swt好。
      

  3.   

    在SWING当中需要程序员利用某种机制确保你想要的String和id之间的关联,这个有很多种实现思路
    这里用的是封装为一个JavaBean,代码贴出来如下
    import javax.swing.*;import java.awt.*;
    import java.awt.event.*;public class ComboBoxDemo2 extends JFrame{

    private City[] cities=null;
    private JComboBox comboBox=new JComboBox();

    public ComboBoxDemo2(String title){
    super(title);

    //添加几个数据
    cities=new City[3];
    cities[0]=new City(1,"北京");
    cities[1]=new City(2,"上海");
    cities[2]=new City(3,"广州");

    for(int i=0;i<cities.length;i++){
    comboBox.addItem(cities[i]);
    }


    comboBox.addActionListener(new ActionListener(){ public void actionPerformed(ActionEvent e) {
    // TODO Auto-generated method stub

    City selectCity=(City)comboBox.getSelectedItem();
    System.out.println(selectCity.getId()+selectCity.getName());
    }

    });

    comboBox.setEditable(true);

    Container contentPane=this.getContentPane();
    contentPane.setLayout(new FlowLayout());
    contentPane.add(comboBox);

    this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    this.pack();
    this.setLocationRelativeTo(null);
    this.setVisible(true);
    }

    /**
     * @param args
     */
    public static void main(String[] args) {
    // TODO Auto-generated method stub
    new ComboBoxDemo2("Hello");
    }
    }class City{
    int id;
    String name;

    public City(int id ,String name){
    this.id=id;
    this.name=name;
    } public int getId() {
    return id;
    } public void setId(int id) {
    this.id = id;
    } public String getName() {
    return name;
    } public void setName(String name) {
    this.name = name;
    }

    public String toString(){
    return this.name;
    }

    }
    也可以用键值对保证两个属性直接的关联,比如可以用HashTable或HashMap,不过这个方法是单向关联,不推荐,