How can I add a space in between two buttons in a boxLayout?
Asked Answered
C

1

51

I have four buttons in a BoxLayout group. This is just a sample of two because it's all repeated code. I want to create a slight space between each button so they don't run into each other. I have tried practically every method in the .add(Box.Create....) and nothing worked.

    enter.add(Box.createVerticalGlue());
    enter.add(Box.createHorizontalGlue()); 
    //enter.add(new JSeparator(SwingConstants.HORIZONTAL));
    JButton float = new JButton("LOWER");
    float.add(Box.createVerticalGlue());
    float.add(Box.createHorizontalGlue());
Cerebrospinal answered 1/12, 2011 at 2:50 Comment(1)
I'm pretty sure that this code would not even compile because "float" is a reserved keyword and not allowed as an object name.Coverage
F
98

If you want to have space between components, you can either add an empty border to one or both components, or insert invisible components to provide the space. You can create invisible components with the help of the Box class.

since you already used glue with no success (I doubt why?), you may try something like Rigid area,

// Horizontal spacer
container.add(firstComponent);
container.add(Box.createRigidArea(new Dimension(5, 0)));
container.add(secondComponent);

Have a look at Using Invisible Components as Filler which gives you a lot of options and explanations.


ADDITIONAL INFORMATION, From Putting Space Between Components,

Three factors influence the amount of space between visible components in a container:

  • The layout manager

    Some layout managers automatically put space between components; others do not. Some let you specify the amount of space between components. See the how-to page for each layout manager for information about spacing support.

  • Invisible components

    You can create lightweight components that perform no painting, but that can take up space in the GUI. Often, you use invisible components in containers controlled by BoxLayout. See How to Use BoxLayout for examples of using invisible components.

  • Empty borders

    No matter what the layout manager, you can affect the apparent amount of space between components by adding empty borders to components. The best candidates for empty borders are components that typically have no default border, such as panels and labels. Some other components might not work well with borders in some look-and-feel implementations, because of the way their painting code is implemented. For information about borders, see How to Use Borders .

Farrel answered 1/12, 2011 at 3:17 Comment(2)
Shouldn't it be Dimension(0, 5) and not Dimension(5, 0)? For me Dimension(5, 0) does not do anything.Gymnastics
@AdrianZhang Thats correct! Dimension (5, 0) would be for Horizontal Space and Dimension (0, 5) for Vertical Space.Corron

© 2022 - 2024 — McMap. All rights reserved.