Zhao Yi
Zhao Yi

Reputation: 2465

How to make a JTable's width >= the enclosing scroll pane's width?

I want to make the table width at least fitting the enclosing scroll pane's width, and if it's getting larger, the horizontal scroll bar is used.

None of JTable's auto resize modes suits my need: AUTO_RESIZE_OFF does allow the table to be resized larger than the scroll pane's width, but it can't limit the table's minimal width; the other modes don't allow the table width to be larger than the scroll pane's width at all.

I have tried to set the minimal size as below but it didn't work:

JTable table = new JTable(myModel);
JScrollPane scrollPane = new JScrollPane(table);
table.setAutoResizeMode(JTable.AUTO_RESIZE_OFF);

// After the table is displayed.
table.setMinimalSize(scrollPane.getSize());

Any idea to achieve that?

Upvotes: 1

Views: 1448

Answers (1)

mKorbel
mKorbel

Reputation: 109815

I have tried to set the minimal size as below but it didn't work:

table.setMinimalSize(scrollPane.getSize());

  • JTable and JScrollPane can't returns reasonable Min, Max and PreferredSize

  • you can to fit (on applications startup) JScrollPanes dimension to JTable by using table.setPreferredScrollableViewportSize(table.getPreferredSize()); (carefully with number of row, otherwise you have to calculating a Dimension instead of JTable.getP...) for JFrame.pack(), on runtime must be validated by revalidate() and repaint() for container nested JScrollPane, don't do that

  • don't reinvent the wheel, to use Fixed Column Table of Table Column Adjuster by @camickr, which one isn't clear from your description, depends of your ...

a JTable's width >= the enclosing scroll pane's width?

  • couldn't be reversed this idea

Upvotes: 3

Related Questions