需要帮助重置/清除jcombobox值

问题描述 投票:4回答:3

我使用下面的编码使用另一个jcombobox将值添加到jcombobox我需要根据jcombobox1中选择的一个值将值添加到jcombobox2而不附加值,所以有人可以告诉我重置或清除组合框的方法选择其他选项时的值?下面是我的编码,我是java和netbeans的新手,所以如果有人可以帮助我会感激不尽:)

    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));                               
    }
 }
java swing reset jcombobox
3个回答
9
投票

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
投票

通常它会发生,因为您有一个与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 ();
  }
}
© www.soinside.com 2019 - 2024. All rights reserved.