java - 如何用数据库中的值填充组合框?

标签 java mysql swing sqlexception

如何插入包含数据库中的值的组合框 我想从数据库中选择并添加到组合框中 我有两堂课:

构造函数Database()第一类

//constructeur 
Database()   
                  {  

 void remplir_Jcomb() {
           Connection conn = null;
           Statement  st = null;
           String rq1 = "SELECT region  FROM  rg";
           String rq2 = "SELECT ACTELS  FROM  rg";

        // - Paramètres de connexion à la base de données
           String url = "jdbc:mysql://localhost/réseau";
           String login = "root";
           String password = "";
           String driver = "com.mysql.jdbc.Driver";

           try {

            //comboBox_gouver.removeAllItems();
               try {
                    Class.forName(driver);
                    conn = DriverManager.getConnection(url,login,password);
                    } catch (ClassNotFoundException e) {
                        e.printStackTrace();
                         }

               st = conn.createStatement();
               ResultSet rs1 = st.executeQuery(rq1);
               ResultSet rs2 = st.executeQuery(rq2);

               while ((rs1.next())&&(rs2.next())) {
                comboBox_gouver.addItem(rs1.getString(1));
                comboBox_ACTELS.addItem(rs2.getString(1));
               }
               st.close();
               rs1.close();
               rs2.close();
               conn.close();

           }  catch (SQLException e) { 
                e.printStackTrace();}

            }
        }

界面swing第二类包含两个JComboBox 调用构造函数Database()

private Database BD= new Database();  
    public Region() {


//first JComboBox
    comboBox_gouver = new JComboBox<String>();
            BD.remplir_Jcomb();
                sl_contentPanel.putConstraint(SpringLayout.NORTH, lbl_gouver, 5, SpringLayout.NORTH, comboBox_gouver);
                sl_contentPanel.putConstraint(SpringLayout.NORTH, comboBox_gouver, 5, SpringLayout.NORTH, contentPanel);
                sl_contentPanel.putConstraint(SpringLayout.WEST, comboBox_gouver, 16, SpringLayout.EAST, lbl_gouver);
                sl_contentPanel.putConstraint(SpringLayout.EAST, comboBox_gouver, -26, SpringLayout.EAST, contentPanel);
                contentPanel.add(comboBox_gouver);

comboBox_ACTELS = new JComboBox<String>();
        sl_contentPanel.putConstraint(SpringLayout.NORTH, lbl_ACTELS, 5, SpringLayout.NORTH, comboBox_ACTELS);
        sl_contentPanel.putConstraint(SpringLayout.NORTH, comboBox_ACTELS, 6, SpringLayout.SOUTH, comboBox_gouver);
        sl_contentPanel.putConstraint(SpringLayout.WEST, comboBox_ACTELS, 90, SpringLayout.EAST, lbl_ACTELS);
        sl_contentPanel.putConstraint(SpringLayout.SOUTH, comboBox_ACTELS, -29, SpringLayout.SOUTH, contentPanel);
        sl_contentPanel.putConstraint(SpringLayout.EAST, comboBox_ACTELS, -26, SpringLayout.EAST, contentPanel);
        contentPanel.add(comboBox_ACTELS);
}}

错误:

java.sql.SQLException: Operation not allowed after ResultSet closed
    at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:1073)
    at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:987)
    at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:982)
    at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:927)
    at com.mysql.jdbc.ResultSetImpl.checkClosed(ResultSetImpl.java:794)
    at com.mysql.jdbc.ResultSetImpl.next(ResultSetImpl.java:7139)
    at tn.pack.ACTEL.Database.remplir_Jcomb(Database.java:94)
    at tn.pack.ACTEL.Region.<init>(Region.java:75)
    at tn.pack.ACTEL.Region.main(Region.java:41)

最佳答案

1) 从 Db 填充数据(使用 finally block 关闭打开的对象,因为在所有情况下都会执行此代码)

void whatever {

   Connection conn = null;
   Statement  st1 = null;

   try {
       st1 = conn.createStatement();

   }  catch (SQLException e) { 
      e.printStackTrace();
   }  finally { 
      try {
          st1.close();
          rs1.close();
          rs2.close();
          conn.close();
      } catch (SQLException ex) {
          //
      } 
   }
} 

2) 在 Db Statement 内填充数据(注意 API Java6/Java7 之间的差异),

  • ComboBoxModel -JComboBox(ComboBoxModel aModel)/JComboBox(ComboBoxModel<E> aModel)

  • arrays of Objects/Elements -JComboBox(Object[] items)/JComboBox(E[] items)

  • Vector of Objects/Elements -JComboBox(Vector items)/JComboBox(Vector<E> items)

如果 Sql block 结束,则将数组类型添加到 JComboBox

编辑:

import java.awt.*;
import java.awt.event.*;
import java.util.ArrayList;
import javax.swing.*;

public class ComboBoxListeners {

    private JFrame f;
    private JComboBox comboBox;
    private JLabel label = new JLabel();
    private DefaultComboBoxModel comboBoxModel = new DefaultComboBoxModel();

    public ComboBoxListeners() {
        comboBox = new JComboBox(comboBoxModel);
        comboBox.addItemListener(new ItemListener() {

            @Override
            public void itemStateChanged(ItemEvent e) {
                if ((e.getStateChange() == ItemEvent.SELECTED)) {
                    String str = comboBox.getSelectedItem().toString();
                    label.setText("Selected Value From JComboBox is :   " + str);
                }
            }
        });
        label.setPreferredSize(new Dimension(400, 30));
        JButton btnAdd = new JButton(new AbstractAction("Append Items") {

            private static final long serialVersionUID = 1L;

            @Override
            public void actionPerformed(ActionEvent e) {
                addNewItemsFromDatabase();
            }
        });
        JButton btnRefresh = new JButton(new AbstractAction("Refresh Items") {

            private static final long serialVersionUID = 1L;

            @Override
            public void actionPerformed(ActionEvent e) {
                refreshItemsFromDatabase();
            }
        });
        f = new JFrame("ComboBox ItemListeners");
        f.setLayout(new GridLayout(0, 1, 15, 15));
        f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        f.add(comboBox);
        f.add(label);
        f.add(btnAdd);
        f.add(btnRefresh);
        f.setLocation(150, 150);
        f.pack();
        f.setVisible(true);
    }

    public void addNewItemsFromDatabase() {
        ArrayList<Integer> ageList = new ArrayList<Integer>();
        for (int i = 1; i <= 5; ++i) {
            ageList.add(i);
        }
        for (final Integer i : ageList) {
            EventQueue.invokeLater(new Runnable() {

                public void run() {// updates to the Swing GUI must be done on EDT
                    comboBoxModel.addElement(i);
                }
            });
        }
    }

    public void refreshItemsFromDatabase() {
        comboBoxModel = new DefaultComboBoxModel();
        ArrayList<Integer> ageList = new ArrayList<Integer>();
        for (int i = 1; i <= 5; ++i) {
            ageList.add(i);
        }
        for (final Integer i : ageList) {
            EventQueue.invokeLater(new Runnable() {

                public void run() {// updates to the Swing GUI must be done on EDT
                    comboBoxModel.addElement(i);
                }
            });
        }
        comboBox.setModel(comboBoxModel);
    }

    public static void main(String[] args) {
        SwingUtilities.invokeLater(new Runnable() {

            @Override
            public void run() {
                ComboBoxListeners comboBoxListeners = new ComboBoxListeners();
            }
        });
    }
}

关于java - 如何用数据库中的值填充组合框?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10094518/

相关文章:

PHP mysqli 测试运行

java - 为什么在此程序中的任何时候都没有调用 Paint() 方法?

java - 如何使用 swing 制作类似调色板的菜单?

java - 在 Swing 中创建带有图标的多个菜单栏

java - JDBC 模板运行缓慢

Java - 实例化对象后卡住

php - 使用 PHP 和 MySQL 通过 current_timestamp 生成站点地图

java - 使用Java程序填写Git凭证

java - 动态按钮单击更新其他 JButton

MySQL 连接和正则表达式