Reputation: 79
Am trying to change the column widith of the column a jtable but when i compile the code,the widith remains the same.
jTable2.setBackground(Color.WHITE);
jTable2.setForeground(Color.BLACK);
jTable2.setShowHorizontalLines(true);
jTable2.setShowVerticalLines(true);
jTable2.setRowHeight(50);
jTable2.getTableHeader().getBackground().brighter();
jTable2.getTableHeader().setBackground(Color.RED);
jTable2.getTableHeader().setForeground(Color.blue);
column1= new ArrayList<> ();
column1.add("Transaction Id");
column1.add("Transaction Date");
column1.add("Narration");
column1.add("Value Date");
column1.add("Debit Amount");
column1.add("Credit Amount");
column1.add("Ledger Balance");
column1.add("Credit Account No.");
column1.add("Credit Account Name");
column1.add("Transaction Ref No.");
column1.add("Cheque No.");
column1.add("Transaction Type");
column1.add("Staff ID");
column1.add("Transaction Time");
**for (int i = 0; i < jTable2.getModel().getColumnCount(); i++) {
if (i == 2) {
column=jTable2.getColumnModel().getColumn(i);
column.setPreferredWidth(200);
} else {
column.setPreferredWidth(50);
}}**
JDBCConnectionPigs csx = new JDBCConnectionPigs();
Connection csx1 = csx.createConnection();
try {
csx1.setAutoCommit(false);
PreparedStatement ps1 = csx1.prepareStatement("SELECT * FROM bsanca01100000310");
ResultSet rst=ps1.executeQuery();
data5= new ArrayList<>();
int i=0;
while (rst.next())
{
data4= new ArrayList<> ();
data4.add(0, rst.getInt("trn_id")+"");
data4.add(1, rst.getDate("trn_date")+"");
data4.add(2, rst.getString("narration"));
data4.add(3, rst.getDate("value_date")+"");
data4.add(4, rst.getString("debit"));
data4.add(5, rst.getString("credit"));
data4.add(6, rst.getString("ledger_balance"));
data4.add(7, rst.getString("credit_account_no"));
data4.add(8, rst.getString("credit_account_name"));
data4.add(9, rst.getString("tra_ref_number"));
data4.add(10, rst.getString("chq_number"));
data4.add(11, rst.getString("trn_type"));
data4.add(12, rst.getString("staff_id"));
data4.add(13, rst.getTime("trn_time")+"");
data5.add(i, data4);
i++;
}
model= new MyTableModel(data5,column1);
jTable2.setModel(model);
csx1.setAutoCommit(true);
}
catch (SQLException ex) {
JOptionPane.showMessageDialog(null, ex.toString());
}
can any one help me to identify where where the problem is or a better way to implement this. Sorry for the bather because the question seam trivial but it has given me hard time.
Upvotes: 0
Views: 67
Reputation: 324197
jTable2.setModel(model);
The above statement is the problem. When you change the TableModel
of the table, the TableColumnModel
is recreated so you lose all the custom column widths.
You need to reset the column width AFTER you change the model.
Upvotes: 2