【问题标题】:Java GridBagLayout positioningJava GridBagLayout 定位
【发布时间】:2016-12-04 01:00:14
【问题描述】:

我正在尝试使用 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);

}



}

原来是这样的

我真正想要的是这样的

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

【问题讨论】:

    标签: java swing layout-manager gridbaglayout


    【解决方案1】:

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

    【讨论】:

      【解决方案2】:

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

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

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2012-09-27
        • 2022-01-08
        • 2015-12-02
        • 2018-07-30
        • 2013-03-15
        • 2012-10-11
        • 2020-08-29
        相关资源
        最近更新 更多