Hi,
I have a JTable which I put into a JScrollPane. I want the auto
resize mode to be JTable.AUTO_RESIZE_OFF...so that the scroll bars will
appear upon resizing columns. However, I want the columns to initially
fill the width of the table.
I've tried...
[code]
int tableWidth = table.getPreferredSize().width;
int colWidth = tableWidth / table.getColumnCount();
table.setAutoResizeMode(JTable.AUTO_RESIZE_OFF);
for (int i = 0; i < colModel.getColumnCount(); i++) {
colModel.getColumn(i).setPreferredWidth(colWidth);
colModel.getColumn(i).setWidth(colWidth);
colModel.getColumn(i).setMinWidth(colWidth);
}
[/code]
....problem is that the columns dont get the right size b/c of
AUTO_RESIZE_OFF. If i dont set that autoresize mode, the columns are
the right size, but when user adjusts the size of a column they don't
get the scroll bars.
any suggestions?
Java and Swing - 14 Jun 2006 13:22 GMT
Well this is a bit hackish feeling, but does the job.
table = createMyTable();
table.setAutoResizeMode(JTable.AUTO_RESIZE_OFF);
scroller = new JScrollPane(table);
Runnable r = new Runnable() {
public void run() {
while (!table.isShowing()) {
try {
Thread.sleep(100);
}
catch (Exception e) {}
}
Runnable runner = new Runnable() {
public void run() {
TableColumnModel colModel = table.getColumnModel();
int tWidth = table.getParent().getSize().width;
int colWidth = tWidth / table.getColumnCount();
for (int i = 0; i < colModel.getColumnCount(); i++) {
colModel.getColumn(i).setPreferredWidth(colWidth);
}
}
};
SwingUtilities.invokeLater(runner);
}
};
new Thread(r).start();
:)