Skip to content
Advertisement

Swing BorderLayout: Make no space between buttons, no center gap

I have this code:

import javax.swing.*;
import java.awt.*;

public class Test extends JFrame {
    public Test()  {
        JPanel panel = new JPanel();

        JButton leftButton = new JButton("Left");
        JButton rightButton = new JButton("Right");
        JButton bottomButton  = new JButton("Bottom");

        Container container = getContentPane();
        container.add(leftButton, BorderLayout.LINE_START);
        container.add(rightButton, BorderLayout.LINE_END);
        container.add(bottomButton, BorderLayout.PAGE_END);

        pack();
        setVisible(true);
        setDefaultCloseOperation(EXIT_ON_CLOSE);
    }

    public static void main(String[] args) {
        Test test = new Test();
    }
}

When I run it, it shows:

enter image description here

However when I resize this window:

enter image description here

How do I make it so that buttons take up 100% of the windows, like this:

enter image description here

I tried to do this:

import javax.swing.*;
import java.awt.*;

public class Test extends JFrame {
    public Test()  {
        JPanel panel = new JPanel();

        JButton leftButton = new JButton("Left");
        JButton rightButton = new JButton("Right");
        JButton bottomButton  = new JButton("Bottom");

        panel.add(leftButton);
        panel.add(rightButton);

        Container container = getContentPane();
      //  container.add(leftButton, BorderLayout.LINE_START);
        //container.add(rightButton, BorderLayout.LINE_END);
        container.add(panel, BorderLayout.CENTER);
        container.add(bottomButton, BorderLayout.PAGE_END);

        pack();
        setVisible(true);
        setDefaultCloseOperation(EXIT_ON_CLOSE);
    }

    public static void main(String[] args) {
        Test test = new Test();
    }
}

but it worked even worse:

enter image description here

enter image description here

I also tried:

container.add(new JLabel(""), BorderLayout.CENTER);

but it gave the original result.

Advertisement

Answer

This layout can be easily achieved by using a GridLayout (green) for the buttons, in the CENTER of a BorderLayout (red) for the main GUI.

enter image description here

Advertisement