user3058242
user3058242

Reputation: 15

More than one jTable with the same ResultSet in Java

Can you populate more than one jTable with the same resultSet?

public void tableDisplay() {

    String tableQuery = "SELECT foodQuantity,foodName FROM food ORDER BY RAND() LIMIT 3";
    ResultSet rs;
    PreparedStatement statement;
    try {

        statement = con.prepareStatement(tableQuery);
        rs = statement.executeQuery();
        jTable1.setModel(DbUtils.resultSetToTableModel(rs));
        jTable2.setModel(DbUtils.resultSetToTableModel(rs));

    } catch (SQLException ex) {
        System.out.println(ex.toString());
    }
}

The code compiles but the second table doesn't get any records from DB. The point is that I need to select random items from mySql table and I want to display them in few jTables.

Upvotes: 0

Views: 464

Answers (2)

Mnemonics
Mnemonics

Reputation: 699

How I populate a JTable with resultSet

try{
playerTableModel = (DefaultTableModel)playerTable.getModel();
            rs = controller.getPlayer();
            while (playerTableModel.getRowCount() > 0);
            int columns = playerTableModel.getColumnCount();
            Object[] rows = new Object[columns];
            while(rs.next()){

                    rows[0] = rs.getString(1);
                    rows[1] = rs.getString(2);
                    rows[2] = rs.getString(3);
                    rows[3] = rs.getString(4);

                    playerTableModel.addRow(rows);
}catch(Exception e){
                e.printStackTrace();
        }

Can't you just call same method for the second table too?

Upvotes: 1

DaveH
DaveH

Reputation: 7335

Without knowing too much about your code, I'd say that you need to call DbUtils.resultSetToTableModel(rs) once, and store the resulting table model in a local variable. Then, pass that local variable to the two setModel(...) methods

Upvotes: 3

Related Questions