How do I make JTable
respect the default size of TableColumn
that I specify? The column should still be shrinkable/extendable for the user, but the default should match the value I set
Here’s a small demo that reproduces what I consider a problem
Instead of 10 pixels, the table sets the size of the column to 225 pixels. Even calling setWidth()
instead of setPreferredWidth()
has no effect
package demos.table;
import javax.swing.*;
import javax.swing.table.DefaultTableModel;
public class SOTableDemo {
public static void main(String[] args) {
SwingUtilities.invokeLater(() -> {
JFrame frame = new JFrame("Simple JTable Demo");
Object[][] data = {
{"John", 25},
{"Doe", 30},
{"Jane", 22},
{"Smith", 28}
};
Object[] columns = {"Name", "Age"};
DefaultTableModel model = new DefaultTableModel(data, columns);
JTable table = new JTable(model);
table.getColumnModel().getColumn(1).setPreferredWidth(10); // I want JTable to respect that
JScrollPane scrollPane = new JScrollPane(table);
frame.add(scrollPane);
frame.pack();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLocationRelativeTo(null);
frame.setVisible(true);
});
}
}
Here’s the code that calculates that nonsensical 225. I have no idea why JTable
does that (or, frankly, what it does), but I don’t like it at all. I want it to stop it
// javax.swing.JTable#adjustSizes(long, javax.swing.JTable.Resizable2, boolean)
double f = (double)(target - totalLowerBound)/(totalUpperBound - totalLowerBound);
newSize = (int)Math.round(lowerBound+f*(upperBound - lowerBound));
How can I control the default size of a TableColumn
?
Heneh is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.