在 java swing 面板中放置按钮的布局

问题描述

我正在尝试以类似于此处显示的方式放置我的按钮:

我尝试过使用 ResponseEntity<List<MyObject>>,在列和行之间有一些空格,但无济于事。我怎样才能做到这一点?

解决方法

有多种方法可以实现这一点,具体取决于您想要实现的目标,个人而言,我会使用 GridBagLayout,但那是因为我喜欢它 ;)

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);
        }

    }
}

您也可以使用多个面板来做一些事情,但这取决于您的需求