【问题标题】:need help on reset/clear jcombobox values在重置/清除 jcombobox 值方面需要帮助
【发布时间】:2012-04-14 18:27:06
【问题描述】:

我使用下面的编码使用另一个 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


    【解决方案1】:

    【讨论】:

    • 非常有帮助。谢谢!
    【解决方案2】:

    在您的组合框中设置一个新模型:

    final List<String> values = new ArrayList<String>();
    
    while (rslt.next()) {
      values.add(rslt.getString(col));
    }
    
    jComboBox2.setModel(new DefaultComboBoxModel(values.toArray()));
    

    见DefaultComboBoxModel。


    不过,作为进一步的评论,根据您的查询中涉及多少延迟,您可能希望使用 SwingWorker 将此工作拆分为 EDT 和后台线程部分。

    【讨论】:

    • 感谢您的回复!我已经像你展示的那样在 combobox1 itemstatechanged 事件中设置了一个新模型,它起作用了! :) 感谢您的帮助!
    【解决方案3】:

    通常发生这种情况是因为您有一个与 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 ();
      }
    }
    

    【讨论】:

      猜你喜欢
      • 2012-01-15
      • 2010-10-09
      • 2021-09-10
      • 2010-12-17
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-01-27
      相关资源
      最近更新 更多