我试图用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上的文档但是找不到一个东西,你能指出我做错了吗?怎么解决?非常感谢你
答案 0 :(得分:3)
所有按钮的网格宽度均为4而不是1。
答案 1 :(得分:1)
您可以使用不同的布局管理器嵌套每个面板,以实现所需的布局。
BorderLayout
创建一个主面板,并将此面板添加到框架BorderLayout.CENTER
FlowLayout
。然后将按钮添加到此面板。然后,可以将此面板添加到BorderLayout.PAGE_END
。