keupsonite keupsonite - 5 months ago 31
Java Question

Make scrollable a JPanel child with GridBagLayout

I've some problem to make a JPanel component to be scrollable... I've spent more than 3 hours to make this works, but without success and that is why I ask your help!

The Window class:

public class Window extends JFrame {
public Window(String title) {
super();

Dimension dimension = IHM.getDimension();

this.setTitle(title);
this.setSize(dimension.width, dimension.height);
this.setLocationRelativeTo(null);
this.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
this.setMaximumSize(dimension);
this.setMinimumSize(dimension);
this.setContentPane(new Container());
this.setBackground(IHM.getBlue());
this.pack();
this.setVisible(true);
}
}


The Container class:

public class Container extends JPanel {
public static Boolean debug = true;
private Dimension lastDimension = new Dimension(0, 0);

public Container() {
// Layout
GridBagLayout layout = new GridBagLayout();
GridBagConstraints gbc = new GridBagConstraints();

// Panel configurations
this.setLayout(layout);

/**
* HEADER
*/
gbc.gridx = 0;
gbc.gridy = 0;
gbc.gridwidth = GridBagConstraints.REMAINDER;
gbc.gridheight = 1;

this.add(new HeaderPanel(), gbc);

/**
* LEFT
*/
gbc.gridx = 0;
gbc.gridy = 1;
gbc.gridwidth = 1;
gbc.fill = GridBagConstraints.BOTH;

JPanel leftPanel = new LeftPanel();

JScrollPane leftPanelScrollable = new JScrollPane(leftPanel);

leftPanelScrollable.setViewportView(leftPanel);
leftPanelScrollable.setHorizontalScrollBarPolicy(JScrollPane.HORIZONTAL_SCROLLBAR_ALWAYS);
leftPanelScrollable.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS);
leftPanelScrollable.setBounds(10, 10, leftPanel.getWidth() - 50, leftPanel.getHeight() - 50);

this.add(leftPanelScrollable, gbc);

// ...
}
}


And the leftPanel class:

public class LeftPanel extends JPanel {
private static Dimension dimension = new Dimension(IHM.getWidth() / 2, IHM.getHeight() - 220);

public LeftPanel() {
this.setPreferredSize(dimension);

// Add the labels
this.addLabel();

// Add the radios
this.addRadios();

this.setAutoscrolls(true);
}
}


Please see the screenshots, I don't have any scrollbar :(

The result in picture:

http://i.stack.imgur.com/q40Ct.png

Do you have any idea about the problem? Thanks in advance!

Answer

After removing the defined size and preferredSize for each JPanel, after set the GridBagConstraints weighty, weightx and fill to GridBagConstraints.BOTH and finally use the setBoxLayout(new BoxLayout(this, BoxLayout.Y_AXIS)) for my leftPanel, everything works well! Thanks anyway everybody.

Final result