Tomi S
Tomi S

Reputation: 197

The easiest way to populate JTable from query

+-------+------+------+  
|  name | level| score|  
+-------+------+------+  
|  data | data | data |  
+-------+------+------+  

This is how I would like to show in JTable.

//SQL

static String[][] executeQuery(){  
  blabla;

  rs = stmt.executeQuery(sql);  
  int i=0;  
  while(rs.next()){  
    query[0][i++] = rs.getString("name ");  
    query[1][i] = rs.getString("level");  
    query[2][i] = rs.getString("score");  
  }  
  return query;  
}  

//MAIN  
JPanel panel = new JPanel();

String[][] getScores = executeQuery();  
Object[][] data = getScores ;  
String[] columnNames = {"name ","level","score"};  

JTable table = new JTable (data, columnNames);  
table.setEnabled(false);  
panel.add(table);  

JOptionPane.showMessageDialog(null, panel);

Result of this is is 3x3 table which is not properly oriented. Dont know why?
My question is: do you have some other example or do you see some errors i made ..
I have only this example but its too complicated for me - beginner:
http://www.rgagnon.com/javadetails/java-0309.html

Upvotes: 0

Views: 11824

Answers (1)

camickr
camickr

Reputation: 324108

The easiest way is to add the data to a DefaultTableModel. See the "Table From Database Example" code found in the Table From Database article.

Upvotes: 2

Related Questions