Java GridBagLayout定位

Java GridBagLayout positioning

我正在尝试使用 GridBagLayout 制作一个 window,这是我的代码:

   import java.awt.FlowLayout;
   import java.awt.GridBagConstraints;
   import java.awt.GridBagLayout;
   import java.awt.event.ActionEvent;
   import java.awt.event.ActionListener;

   import javax.swing.JButton;
   import javax.swing.JFrame;
   import javax.swing.JPanel;
   import javax.swing.JScrollPane;
   import javax.swing.JTextArea;

   public class ReadMessage extends JFrame implements ActionListener
   {
JButton Last;
JButton Delete;
JButton Store;
JButton Next;
JTextArea MessageBox;

public ReadMessage()
{
    setLayout(new FlowLayout());
    JPanel Panel = new JPanel();
    add(Panel);
    setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    Panel.setLayout(new GridBagLayout());
    GridBagConstraints c = new GridBagConstraints();


    MessageBox = new JTextArea();
    MessageBox.setEditable(false);
    JScrollPane scrollPane = new JScrollPane(MessageBox, JScrollPane.VERTICAL_SCROLLBAR_ALWAYS,
            JScrollPane.HORIZONTAL_SCROLLBAR_ALWAYS);
    MessageBox.setLineWrap(true);
    c.gridx = 0;
    c.gridy = 0;
    c.gridwidth = 4;
    c.weightx = 0.0;
    c.ipady = 300;
    c.ipadx = 300;
    Panel.add(scrollPane, c);


    Last = new JButton("Last");
    c.gridx = 0;
    c.gridy = 1;
    c.ipady = 0; 
    c.weightx = 0.5;
    Panel.add(Last, c);
    Last.addActionListener(this);

    Delete = new JButton("Delete");
    c.gridx = 1;
    c.gridy = 1;
    c.ipady = 0; 
    c.weightx = 0.5;
    Panel.add(Delete, c);
    Delete.addActionListener(this);

    Store = new JButton("Store");
    c.gridx = 2;
    c.gridy = 1;
    c.ipady = 0; 
    c.weightx = 0.5;
    Panel.add(Store, c);
    Store.addActionListener(this);

    Next = new JButton("Next");
    c.gridx = 3;
    c.gridy = 1;
    c.ipady = 0; 
    c.weightx = 0.5;
    Panel.add(Next, c);
    Next.addActionListener(this);

}



}

结果是这样的

我真正想要的是这样

我知道我做错了,但我不知道我到底做错了什么,我阅读了 oracle 上的文档,但找不到任何东西,你能指出我做错了什么,以及如何做修理它?非常感谢

您可以嵌套面板,每个面板使用不同的布局管理器来实现您想要的布局。

  1. 创建一个带有 BorderLayout 的主面板并将此面板添加到框架
  2. 将 JTextArea 添加到主面板的 BorderLayout.CENTER
  3. 为按钮创建第二个面板并使用 FlowLayout。然后将按钮添加到此面板。然后可以将此面板添加到 BorderLayout.PAGE_END.
  4. 处的主面板

所有按钮的网格宽度都是 4 而不是 1。