0

I'm trying to place my buttons in a manner similar to what has been shown here:

I've tried using the GridLayout, with some amount of spaces between columns and rows, but to no avail. How can I achieve this?

Andrew Thompson
  • 168,117
  • 40
  • 217
  • 433
Jayajit
  • 25
  • 5
  • Looks like something for BorderLayout: https://docs.oracle.com/javase/tutorial/uiswing/layout/border.html – BeUndead Apr 27 '21 at 10:52
  • 3
    Yes, a `BorderLayout` as suggested by @BeUndead is what I'd use, with panels using `FlowLayout` to center the `Up` / `Down` buttons in the `PAGE_START` & `PAGE_END` of the border layout. Add a large `EmptyBorder` with most padding on the left / right to complete the GUI as seen. **BTW:** `GridLayout` would not be able to make that GUI because it makes all cells equal size and will not let them 'overlap' each other in different rows. A `GridBagLayout` might be able to, but it's simpler to use a combo of border and flow layout. – Andrew Thompson Apr 27 '21 at 10:54
  • 4
    See also [this answer](https://stackoverflow.com/a/10862262/418556) which takes a more polished look to the GUI for this type of direction based control. It breaks up an image and displays it in a series of labels and buttons appearing (ironically) in a `GridLayout`. – Andrew Thompson Apr 27 '21 at 11:03
  • I'd use a `GridBagLayout`, because I do :P – MadProgrammer Apr 27 '21 at 11:56

1 Answers1

4

There are a number of ways you might achieve this depending on what you want to achieve, personally, I'd use a GridBagLayout, but that's because I like it ;)

Buttons

import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.SwingUtilities;

public class Test {

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

    public Test() {
        SwingUtilities.invokeLater(new Runnable() {
            @Override
            public void run() {
                JFrame frame = new JFrame();
                frame.add(new TestPane());
                frame.pack();
                frame.setVisible(true);
            }
        });
    }

    public class TestPane extends JPanel {

        public TestPane() {
            setLayout(new GridBagLayout());
            GridBagConstraints gbc = new GridBagConstraints();
            gbc.gridwidth = 2;
            //gbc.fill = GridBagConstraints.HORIZONTAL;

            gbc.gridx = 1;
            add(new JButton("Up"), gbc);
            gbc.gridx = 0;
            add(new JButton("Left"), gbc);
            gbc.gridx = 2;
            add(new JButton("Right"), gbc);
            gbc.gridx = 1;
            add(new JButton("Down"), gbc);
        }

    }
}

You could also do something using multiple panels, but that would depend on your desired needs

MadProgrammer
  • 343,457
  • 22
  • 230
  • 366