0

For my Java program I am actually using the simple library TableLayout as layout for my main JPanel body so that I can add any widget just by specifying its row and column index, for example"

body.add(new JLabel(
            "Search by date"),
            "1,8");

Now I would need to add two JScrollPane (one horizontal and one vertical) but they should include all the body and not just a single cell of the layout. Shall I add another JPanel? How can I do it?

mKorbel
  • 109,525
  • 20
  • 134
  • 319
SagittariusA
  • 5,289
  • 15
  • 73
  • 127

1 Answers1

2

Now I would need to add two JScrollPane (one horizontal and one vertical) but they should include all the body and not just a single cell of the layout. Shall I add another JPanel?

IMO, yes you should. Nesting Layouts is a common approach that could be applied in this way:

  • Create a new JScrollPane and set your panel as its viewport view.

  • Give the scroll pane a reasonable preferred size to enable the scroll bars if your panel's size exceeds this preferred size.

  • Have a wrapper panel with BorderLayout and add the scroll pane to its CENTER location.

In a nutshell:

JScrollPane scrollPane = new JScrollPane(yourPanel);
scrollPane.setPreferredSize(new Dimension(400, 300));

JPanel wrapperPanel = new JPanel(new BorderLayout());
wrapperPanel.add(scrollPane);

See also:

Community
  • 1
  • 1
dic19
  • 17,821
  • 6
  • 40
  • 69
  • I still need your help if you can. I have followed all your instructions and everything was fine. Yesterday I tried to add new items into the body (JButtons, JLabels...) and even if I had added the JScrollPane they are not shown when I scroll down the main page. In other words, I divided the main JPanel into 11 rows and 7 columns using tablelayout.jar by Oracle. If I add another row or two they are not shown and I do not know why. You can read the following link for further information. Can you help me? – SagittariusA Dec 13 '14 at 13:36
  • http://stackoverflow.com/questions/27446966/java-gui-tablelayout-how-to-add-more-many-widgets-in-a-jframe-with-a-scroll-bar – SagittariusA Dec 13 '14 at 13:37