2012-04-14 46 views
4

即时通讯使用下面的编码使用另一个jcombobox将值添加到jcombobox,我需要根据在jcombobox1中选择的一个获取值添加值到jcombobox2,而不追加值,所以有人可以告诉我选择另一个选项时重置或清除组合框值的方法?下面 是我的编码,我是新来的Java和NetBeans因此,如果有人能帮我会感激:)重置/清除jcombobox值需要帮助

Class.forName("com.mysql.jdbc.Driver").newInstance(); 
    Connection con = DriverManager.getConnection("jdbc:mysql://localhost/database1", "root", "senura123"); 
    Statement stat = (Statement) con.createStatement(); 
    String val=jComboBox1.getSelectedItem().toString(); 
    String check; String col; 
    if ("Vehicles".equals(val)){ 
     check = "select reg_no from vehicle;"; 
     col="reg_no"; 
    } 
    else if ("Travel Guides".equals(val)){ 
     check = "select username from travelguide;"; 
     col="username"; 
    } 
    else{ 
     check = "select username from transportofficer"; 
     col="username"; 
    }     
    ResultSet rslt = stat.executeQuery(check); 
    while (rslt.next()) { 
     jComboBox2.addItem(rslt.getString(col));        
    } 
} 

回答

1

设置一个模型到您的组合框:

final List<String> values = new ArrayList<String>(); 

while (rslt.next()) { 
    values.add(rslt.getString(col)); 
} 

jComboBox2.setModel(new DefaultComboBoxModel(values.toArray())); 

DefaultComboBoxModel


作为进一步的评论,但是,这取决于有多少潜伏涉及您的查询,您可能想起来拆分本作品使用SwingWorker EDT和后台线程的部分。

+0

感谢您的回复!我已经设置了一个像你展示的新模型,在combobox1 itemstatechanged事件中,它工作! :) 谢谢您的帮助! – senrulz 2012-04-16 11:07:44

0

通常它发生,因为你有一个事件相关联的JComboBox。如果您在JComboBox中有控制项目可以解决问题,例如:

jComboBoxExample.addActionListener (new ActionListener() { 
    public void actionPerformed (ActionEvent e) { 
     do_run(); 
   } 
}); 



public void do_run() { 
    int n=jComboBoxPerfilDocumentos.getItemCount(); <--THIS IS THE SOLUTION 
  if (n> 0) { 
    String x = jComboBoxPerfilDocumentos.getSelectedItem(). ToString(); 
  } 
}