Search code examples
javauser-interfacelayout-managergrid-layout

Java: Gap in the beginning of a GridLayout


I'm trying to code a game in Java and I'm currently doing the title screen.

I want to have three buttons in the middle that are placed underneath each other. Those buttons are "Play", "Options" and "Quit".

I ordered the buttons using a GridLayout and now I want that to have a little gap between the top of the screen and the Play button. Could you tell me how to do that?

My current code looks something like this:

public class GamePanel extends JPanel {

    private JPanel optionsPanel;

    public GamePanel() {
        super(new FlowLayout());
        FlowLayout layout = (FlowLayout) getLayout();
        layout.setAlignment(FlowLayout.CENTER);

        GridLayout layout2 = new GridLayout(3,1);
        optionsPanel = new JPanel(layout2);
        add(optionsPanel);

        optionsPanel.add(new CustomButton("Play"));
        optionsPanel.add(new CustomButton("Options"));
        optionsPanel.add(new CustomButton("Quit"));
    }
}

Solution

  • Try something like this:

    optionsPanel.setBorder(BorderFactory.createEmptyBorder(10, 0, 0, 0));
    

    See also: https://docs.oracle.com/javase/8/docs/api/javax/swing/BorderFactory.html#createEmptyBorder-int-int-int-int-