Redandwhite
Redandwhite

Reputation: 2549

Why am I not getting a functioning JScrollPane?

I have a JFrame window, and I'd like to add a scrollable JTable towards the middle of it. I have a method, called collectionTableScrollPane() that generates the JScrollPane (and I know this is guaranteed to work).

I then proceed to add it to my mainPanel panel. However, I'd like there to be some forced 30px padding on the left and right of the JScrollPane. Logically, I would create a holding JPanel with a centred FlowLayout, and add Box.createHorizontalStrut(30) either side of the JScrollPane.

JPanel tableHolderPanel = new JPanel(new FlowLayout());
mainPanel.add(tableHolderPanel);
tableHolderPanel.add(Box.createHorizontalStrut(30));
tableHolderPanel.add(collectionTableScrollPane());
tableHolderPanel.add(Box.createHorizontalStrut(30));

However, I'm getting a strange result, where the JScrollPane in the middle of the window (denoted by the arrows) sort of becomes ineffectual.

Does anyone know what the problem is?

1

Note that the JTable contains four rows, of which only two are visible.

Upvotes: 3

Views: 130

Answers (3)

gontard
gontard

Reputation: 29540

I had some issues in the past when i used a JScrollPane inside a panel with a FlowLayout. The behaviour could be tricky, when the content grow, the horizontal scrollbar may appear or the FlowLayout should add a new line.

In your case, i will replace the FlowLayout by a BorderLayout :

JPanel tableHolderPanel = new JPanel(new BorderLayout());
mainPanel.add(tableHolderPanel);
tableHolderPanel.add(Box.createHorizontalStrut(30), BorderLayout.WEST);
tableHolderPanel.add(collectionTableScrollPane(), BorderLayout.CENTER);
tableHolderPanel.add(Box.createHorizontalStrut(30), BorderLayout.EAST);

Upvotes: 3

mKorbel
mKorbel

Reputation: 109823

BoxLayout accepting size that came from JComponents, the same issue with default FlowLayout pre_implemented for JPanel

  1. you have to returns PreferredSize by overrode JPanel nested JScrollPane,

  2. use another LayoutManager, e.g. GridBagLayout or todays MigLayout

  3. use NestedLayout, by using BorderLayout where you put two JLabels (e.i. that returns PreferredSize) to the EAST and WEST area

  4. everything depends if you really to want to create the empty area and if shoud be resiziable or not

Upvotes: 1

MadProgrammer
MadProgrammer

Reputation: 347334

As far as I'm aware, Box is suppose to be used with the BoxLayout, this may be causing you some issues. Instead, why not use a EmptyBorder on the tableHolderPane

Upvotes: 2

Related Questions