SagittariusA
SagittariusA

Reputation: 5427

Swing: how to add two JScrollPanes with TableLayout?

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?

Upvotes: 0

Views: 239

Answers (1)

dic19
dic19

Reputation: 17971

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:

Upvotes: 2

Related Questions