views:

108

answers:

4

I have code like that:

    JPanel myPanel = new JPanel();
    myPanel.setLayout(new BoxLayout(myPanel, BoxLayout.Y_AXIS));

    JButton button = new JButton("My Button");
    JLabel label = new JLabel("My label!!!!!!!!!!!");

    myPanel.add(button);
    myPanel.add(label);

In this way I get elements with no distance between them. I mean, the "top" elements always touches the "bottom" element. How can I change it? I would like to have some separation between my elements?

I think about adding some "intermediate" JPanel (with some size) between my elements. But I do not think it is an elegant way to get the desired effect. Can somebody, pleas, help me with that?

+1  A: 

Use the Box class as an invisible filler element. This is how Sun recommends you do it.

BoxLayout tutorial.

Stefan Kendall
+2  A: 
    JPanel myPanel = new JPanel();
    myPanel.setLayout(new BoxLayout(myPanel, BoxLayout.Y_AXIS));

    JButton button = new JButton("My Button");
    JLabel label = new JLabel("My label!!!!!!!!!!!");

    myPanel.add(button);
    myPanel.add(Box.createVerticalStrut(20));
    myPanel.add(label);

will be one way of doing it.

Calm Storm
+2  A: 

You may want to consider GridLayout instead of BoxLayout, it has attributes Hgap and Vgap that let you specify a constant seperation between components.

GridLayout layout = new GridLayout(2, 1);
layout.setVgap(10);
myPanel.setLayout(layout);
myPanel.add(button);
myPanel.add(label);
M. Jessup
+3  A: 

If you're definitely intending to use BoxLayout to layout your panel, then you should have a look at the How to Use BoxLayout Sun Learning Trail, specifically the Using Invisible Components as Filler section. In short, with BoxLayout you can create special invisible components that act as spacers between your other components:

container.add(firstComponent);
container.add(Box.createRigidArea(new Dimension(5,0)));
container.add(secondComponent);
RTBarnard
In this case you could also use Box.createVerticalStrut(5). There is a complementary Box.createHorizontalStrut(int) as well. I prefer these when one of the dimensions is zero.
Geoff Reedy