1

I kept on searching and nothing shows a good answer, I'm a bit new to the in depth parts of Java, so just asking.. How to resize or dynamically resize the JTable depending on its rows, instead of having a vertical scrollbar?

My method (not working):

After I add data into the table I then resize the table by its parent JScrollPane, since table resize automatically with its rows, but scroll pane doesn't but rather just stays the same before data was added. I've already tried these methods:

itemTable.setPreferredScrollableViewportSize(...);
jScrollPane.setPreferredSize(...);//using the itemTable width and height
jScrollPane.setSize(...);//using the itemTable width and height

Still nothing works, can someone help me? Or maybe other solutions?

Andrew Thompson
  • 168,117
  • 40
  • 217
  • 433
  • 1
    *"How to resize or dynamically resize the `JTable` depending on its rows, instead of having a vertical scrollbar?"* ... ***Why?*** I have a few other questions if you can convince me that it is a good idea to toss aside a technique ('use a scroll pane') which would be the path of least surprise for the user and has been successfully implemented in tens of thousands of GUIs over the decades. – Andrew Thompson Jun 02 '21 at 06:34
  • The reason is, I'm trying to print a panel with a table on it for much easier and organize display of items, so I want the table to show all its rows, because we can't scroll on the paper. – Schweizer_Ken Jun 02 '21 at 06:38
  • Producing a paper report is a totally different process from producing a GUI. For the GUI, use a JScrollPane. For the paper report, use a report writer library, or [create the report](https://docs.oracle.com/javase/tutorial/2d/printing/printable.html) yourself, considering each sheet of paper as the location of a BufferedImage. – Gilbert Le Blanc Jun 02 '21 at 10:40
  • Don't attempt to set the preferred size of Swing components!!! It is the job of the layout manager to set a components size/location. If you change the preferred scrollable viewport size, then you need to `revalidate()` the parent panel containing the scrollpane. Check out: https://stackoverflow.com/questions/67506793/reset-jtable-depending-on-content-number-of-rows/67522733#67522733 for an example to get you started. – camickr Jun 02 '21 at 14:21

0 Answers0