如何在 JFrame 中排列组件

How to arrange components in a JFrame

我正在尝试获得一个 JTextArea,其下方居中有一个 "save" JButton,如果可能的话,可能在组件之间以及框架的组件之间有一点填充。我试过摆弄布局管理器、面板等,但似乎无法获得我想要的结果。只是在寻找最简单的方法来做到这一点。谢谢。

建议:

  • GUI 容器的整体布局可以是 BorderLayout。
  • 添加包含 JTextArea 的 JScrollPane BorderLayout.CENTER。
  • 创建一个 JPanel 来容纳 JButton,不要给它一个特定的布局管理器。它现在将使用 JPanel 的默认 FlowLayout 并将组件在水平方向居中。
  • 将您的 JButton 添加到最后一个 JPanel。
  • 将相同的 JPanel 添加到 GUI 的 BorderLayout.PAGE_END(底部)位置。

例如:

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

public class SimpleLayout extends JPanel {
    private static final int ROWS = 20;
    private static final int COLS = 60;
    private JTextArea textArea = new JTextArea(ROWS, COLS);
    private JButton button = new JButton("Button");

    public SimpleLayout() {
        JPanel buttonPanel = new JPanel();
        buttonPanel.add(button);

        setLayout(new BorderLayout());
        add(new JScrollPane(textArea), BorderLayout.CENTER);
        add(buttonPanel, BorderLayout.PAGE_END);
    }

    private static void createAndShowGui() {
        SimpleLayout mainPanel = new SimpleLayout();

        JFrame frame = new JFrame("SimpleLayout");
        frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
        frame.getContentPane().add(mainPanel);
        frame.pack();
        frame.setLocationByPlatform(true);
        frame.setVisible(true);
    }

    public static void main(String[] args) {
        SwingUtilities.invokeLater(() -> {
            createAndShowGui();
        });
    }
}