在 JPanel 中居中 JTextArea

Centre JTextArea in JPanel

我不敢相信没有答案...我只想将 JTextArea 置于 JPanel 的中心。我为此使用 BoxLayout。当我 运行 我的程序时, JTextArea 占据了整个屏幕。这是为什么?

public class BLayout extends JFrame implements ActionListener {

    public BLayout() {
        super("GUI Testing");
        setSize(500, 500);
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

        JPanel choosePanel = new JPanel();
        choosePanel.setLayout(new BoxLayout(choosePanel, BoxLayout.X_AXIS));
        choosePanel.setBackground(Color.BLUE);

        JTextArea text = new JTextArea(1, 10);
        text.setLineWrap(true);
        text.setEditable(false);
        text.setText("Welcome to Library Search.\n\n"
                + "Choose a command from the \"Commands\""
                + " menu above for adding a reference, "
                + "searching references, or quitting the program.");
        choosePanel.add(text);
        add(choosePanel);
    }

如何让文本区域位于面板中间而不占据整个屏幕?

I am using BoxLayout for this. When I run my program, the JTextArea takes up the whole screen. Why is this?

因为这就是 BoxLayout 的工作方式。您可以改用 GridBagLayout,它默认将组件置于容器中,例如

import java.awt.EventQueue;
import java.awt.GridBagLayout;
import javax.swing.JFrame;
import javax.swing.JTextArea;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;

public class BLayout extends JFrame {

    public BLayout() {
        super("GUI Testing");
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        setLayout(new GridBagLayout());


        JTextArea text = new JTextArea(7, 40);
        text.setLineWrap(true);
        text.setWrapStyleWord(true);
        text.setEditable(false);
        text.setText("Welcome to Library Search.\n\n"
                + "Choose a command from the \"Commands\""
                + " menu above for adding a reference, "
                + "searching references, or quitting the program.");
        add(text);
    }

    public static void main(String[] args) {
        EventQueue.invokeLater(new Runnable() {
            @Override
            public void run() {
                try {
                    UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
                } catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
                    ex.printStackTrace();
                }

                BLayout frame = new BLayout();
                frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
                frame.pack();
                frame.setLocationRelativeTo(null);
                frame.setVisible(true);
            }
        });
    }
}