Reputation: 13
I have JButton in the front panel. When it is clicked it should display the data in table format. I have assigned the data and column names to JTable parameter but it is not visible in the front end. I confirmed the values are assigned correctly but not sure why table is not visible in the panel. Here is my code:
private void disPlayDataActionPerformed(java.awt.event.ActionEvent evt) {
// TODO add your handling code here:
sql = "select * from persons";
try {
Statement st = con.createStatement();
ResultSet rs = st.executeQuery(sql);
ResultSetMetaData metaData = rs.getMetaData();
int columnCount=metaData.getColumnCount();
String[]columnNames=new String[columnCount];
for(int i=0;i< columnNames.length;i++){
columnNames[i]=metaData.getColumnName(i+1);
}
ArrayList<String[]> rows=new ArrayList<>();
while(rs.next()){
String[]currentrow=new String[columnCount];
for(int i=0;i<columnCount;i++){
currentrow[i]=rs.getString(i+1);
}
rows.add(currentrow);
}
String[][] rowsArray=new String[rows.size()][columnCount];
rowsArray=rows.toArray(rowsArray);
JTable jt=new JTable(rowsArray,columnNames);
jPanel2.add(jt);
jt.setVisible(true);
} catch (SQLException ex) {
Logger.getLogger(EmployeePanel.class.getName()).log(Level.SEVERE, null, ex);
}
finally{
}
}
Upvotes: 1
Views: 1734
Reputation: 347184
Swing's layout API is lazy, it's designed this way. You need to tell it when you're ready for it revalidate the container hirarcy.
JTable jt=new JTable(rowsArray,columnNames);
jPanel2.add(jt);
jPanel2.revalidate();
jPanel2.repaint();
Without knowing your full code, generally speaking, it's much easier to simply have a main JTable
and change it's model when ever you need to.
Upvotes: 0
Reputation: 4207
can you try this one,
JTable jt=new JTable(rowsArray,columnNames);
jt.setBounds(30,40,200,300); // you can put dimension as per your wish...
JScrollPane sp=new JScrollPane(jt);
jPanel2.add(sp);
// code fore set visible true to jpanel2...
Upvotes: 1