0
votes

I am a newbie in Swing and I am using a JTable object in order to display some information. Basically the frame contains a JPanel -> GridBagLayout manager. The JPanel contains a JLabel ("Status Table"), a JScrollPane which contains the JTable, the "Sort by" JButton and a JComboBox.

How can I set the width of the columns/ column headers in order to completely display the text contained in them?

I tried to use

table.getColumnModel().getColumn(i).setPreferredWidth(my_width); 

but the problem is that in order to achieve the results I want, the sum of all the columns' widths is larger than the JScrollPane's width, so nothing will happen, they will remain the same as before.

I tried to use the setSize method for JScrollPane in order to resize it to be as large as the window... but because of the GridBagLayout manager it seems that it cannot get larger than a certain size, which still doesn't fit the text.

Additional info: The JTable is built from a model that I've implemented and the only GridBagConstraints that I've modified are gridx, gridy and fill = BOTH.

table

1

1 Answers

3
votes

See the Table Column Adjuster for an easy way to size each column.

Only the table should be added to the scrollpane. You may also need to use:

table.setAutoResizeMode( JTable.AUTO_RESIZE_OFF );

To allow each column to be displayed at its preferred size.

the sum of all the columns' widths is larger than the JScrollPane's width, so nothing will happen,

You have a problem with the gridbag constaints. The component should grow to fill all the space. Maybe it will be easier to use a BorderLayout. Add the scrollpane to the center and add the other components to the north/south. You can nest panels with different layout managers to get your desired layout.