添加actionPerformed后,组合框中的项目减少。

问题描述 投票:0回答:1

我想在点击combobox中不同的项目后,立即更新我的表格。添加actionPerformed后,combobox只显示第一个项目,箭头不工作。我想在选择不同的项目并点击按钮后更新我的表格。按钮中的动作执行确实有效。我是否使用了错误的actionPerformed?

下面是我如何将项目添加到combobox的代码。

private void fillComboBox() {       
    try {
        DatabaseMetaData meta = (DatabaseMetaData) conn.getMetaData();
        rs = meta.getTables("db", null, null, new String[] {
          "TABLE"
        });
        while (rs.next()) {
            ComboBox.addItem(rs.getString("TABLE_NAME"));
        }            
    } catch(Exception e) {
        JOptionPane.showMessageDialog(null,e);         
    }
}

下面是我如何填充表格。

private void fillTable()
{
    String selectedValue = ComboBox.getSelectedItem().toString();
    String sql = "Select * from "+selectedValue;
    Statement stmt;
    try {
        stmt = conn.createStatement(rs.TYPE_SCROLL_INSENSITIVE,rs.CONCUR_UPDATABLE);
        rs = stmt.executeQuery(sql);
        Table.setModel(DbUtils.resultSetToTableModel(rs));
    } catch (SQLException ex) {
        Logger.getLogger(Welcome.class.getName()).log(Level.SEVERE, null, ex);
    }       
}

在点击按钮后,我更新了表格。

private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {                                         
    fillTable();
}  

工作正常,但我想在点击combobox中的新项目后立即更新表格。

编辑:我在 fillTable()之后添加了 fillComboBox()来解决这个问题。但是现在,即使在removeAll()之后,combobox中仍然有两个第一项。我该如何解决这个问题?

public Welcome() {
    initComponents();
    conn = MySqlConnect.ConnectDB();
    fillComboBox();
    fillTable();
    ComboBox.removeAll();
    fillComboBox();
    repaint();
}
java mysql netbeans combobox
1个回答
1
投票

我总是通过使用底层模型来动态改变一个组合框的内容,而不是通过实际的组合框。在你的GUI已经显示出来之后,我认为这个问题......使用模型,而不是JComboBox本身。

...
final var model = new DefaultComboBoxModel<String>();
while (rs.next()) {
    model.addElement(rs.getString("TABLE_NAME"));
}
...
ComboBox.setModel(model);
© www.soinside.com 2019 - 2024. All rights reserved.