I have a JTable
which would be populated dynamically and I want the table to always resize to fit the number of rows. I don't want any scrolling because the table is in a panel and the contents of the panel needs to be printed.
I've tried this:
Dimension d = itemsTable.getPreferredSize();
//scrollPane.setPreferredSize(new Dimension(d.width,itemsTable.getRowHeight()*itemsTable.getRowCount()+10));
itemsTable.setPreferredScrollableViewportSize(new Dimension(d.width,itemsTable.getRowHeight()*itemsTable.getRowCount()+1))
But it doesn't seem to work.
public void getDetails(PosView pv){
Connection con = con();
DefaultTableModel model = (DefaultTableModel)pv.getItemsTable().getModel();
String date = null;
double total = 0.0, paid = 0.0;
try{
ps = con.prepareStatement("SELECT DISTINCT AMOUNT_PAYABLE, AMOUNT_PAID, BALANCE, DATE FROM SALES WHERE PAYMENT_ID = ?");
ps.setString(1, paymentId);
rs = ps.executeQuery();
while(rs.next()){
total = (rs.getDouble(1));
paid += (rs.getDouble(2));
date = rs.getString(4);
}
double balance = total - paid;
pv.setDate(date);
pv.setPaymentId(paymentId);
ps = con.prepareStatement("SELECT QUANTITY, ITEM_NAME, SELLING_PRICE, TOTAL FROM ITEMS_BOUGHT WHERE ID = ?");
ps.setString(1, paymentId);
rs = ps.executeQuery();
while(rs.next()){
Object data[] = {rs.getInt(1), rs.getString(2), rs.getDouble(3),rs.getDouble(4)};
model.addRow(data);
}
logActivity(userId, "PAYMENT RECEIPT "+ paymentId +" GENERATED", con);
pv.setTotal(total);
pv.setPaid(paid);
pv.setBalance(balance);
}catch(SQLException e){
showMessageDialog(null, e.getMessage());
}finally{
try {
if(ps!=null)
ps.close();
con.close();
}catch(Exception e){}
}
}
I don't think this is the best way. But as you insist i have put the code below.
Override
getPreferredScrollableViewportSize()
to return a multiple of the product of line height and row count. Each time a row is added,pack()
the enclosing window.