SpiroMarshes SpiroMarshes - 1 year ago 112
Java Question

Java how to disable JPanel components automatic vertical resizing

I've ran into a pretty annoying problem. The JPanel is adding a vertical gap between components, and I need to get rid of that.
I'm trying to get this (Blue lines are the space I want to get rid of):

enter image description here

To look like this:

enter image description here

Here is my current class:

public class SummaryPanel extends JPanel
private JLabel bagelLabel;
private JLabel toppingLabel;
private JLabel coffeeLabel;
private JLabel shotsLabel;

private JLabel subtotal;
private JLabel tax;
private JLabel total;

private JPanel selectionsPanel;
private JPanel totalPanel;

public SummaryPanel()
bagelLabel = new JLabel("No bagel $0.00");
toppingLabel = new JLabel("No topping $0.00");
coffeeLabel = new JLabel("No coffee $0.00");
shotsLabel = new JLabel("(Includes 0 shots) $0.00");

subtotal = new JLabel("");
tax = new JLabel("");
total = new JLabel("");

setLayout(new GridLayout(2,1));

selectionsPanel = new JPanel();

selectionsPanel.setLayout(new GridLayout(4,1));
selectionsPanel.add(coffeeLabel );
selectionsPanel.add(shotsLabel );

totalPanel = new JPanel();
totalPanel.setLayout(new GridLayout(3,1));



Answer Source

Its controlled by the layout manager.

setLayout(new GridLayout(2,1));

You are using a GridLayout so each of the two components gets the same space.

    selectionsPanel.setLayout(new GridLayout(4,1));

In turn each JLabel get a quarter of the total space available to each panel.

Instead you could use a BorderLayout:

//setLayout(new GridLayout(2,1)); setLayout(new BorderLayout);

Then when you add components to the panel you use:

add(selectionsPanel, BorderLayout.PAGE_START);
add(totalsPanel, BorderLayout.PAGE_END);

Now the preferred sizes will be respected.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download