Java GridBagLayout定位

时间:2016-12-04 01:00:15

标签: java swing layout-manager gridbaglayout

我试图用GridBagLayout创建一个窗口,这是我的代码:

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

}



}

结果是这样的enter image description here

我真正想要的是这样的

enter image description here

我知道我做错了但是我无法弄清楚我到底做错了什么,我读了oracle上的文档但是找不到一个东西,你能指出我做错了吗?怎么解决?非常感谢你

2 个答案:

答案 0 :(得分:3)

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

答案 1 :(得分:1)

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

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