I am using a JScrollPane
to display a JTable
. I want the columns in the table to have a minumum size, so that when you shrink the screen the horizontal scrolling appears; but I also want them to be able to expand when the screen gets wider. With the current code, tha columns does not get pass their minimum value, it's just that the viewport stop showing the entire table and does not activates the horizontal scroll bar. Is there a method ti set at which width the scroll bar should appear?
Here's some of the code i have:
private void addTable(JTable table){
initColumnSizes(table);
JPanel tablePanel = new JPanel(new BorderLayout());
JScrollPane scrolled = new JScrollPane(table);
scrolled.getViewport().setMinimumSize(tableSize);
scrolled.setMinimumSize(tableSize);
scrolled.setPreferredSize(tableSize);
scrolled.setBorder(border);
tablePanel.add(scrolled, BorderLayout.CENTER);
//more stuff
}
Here is the code for the initColumns method, in case you need it
private void initColumnSizes(JTable table) {
TableModel model = table.getModel();
TableColumn column = null;
Component comp = null;
int headerWidth = 0;
int cellWidth = 0;
TableCellRenderer headerRenderer =
table.getTableHeader().getDefaultRenderer();
for (int i = 0; i > table.getColumnCount(); i++) {
column = table.getColumnModel().getColumn(i);
comp = headerRenderer.getTableCellRendererComponent(
table, column.getHeaderValue(),
false, false, 0, 0);
headerWidth = comp.getPreferredSize().width;
comp = table.getDefaultRenderer(model.getColumnClass(i)).
getTableCellRendererComponent(
table, model.getValueAt(0, i),
false, false, 0, i);
cellWidth = comp.getPreferredSize().width;
column.setPreferredWidth(Math.max(headerWidth, cellWidth));
column.setMinWidth(column.getPreferredWidth());
}
}