package Test04;
import java.awt.Container;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.Insets;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.WindowConstants;
public class GridBag2 extends JFrame
{
public GridBag2()
{
Container c1 = getContentPane();
setLayout(new GridBagLayout());
setTitle("这是一个网格布局的窗体");
setSize(500,400);
setVisible(true);
setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
final JButton button1 = new JButton("A");
final GridBagConstraints grid1 = new GridBagConstraints();
grid1.gridx = 0;
grid1.gridy = 0;
grid1.weightx = 10;
grid1.fill = GridBagConstraints.HORIZONTAL;
c1.add(button1, grid1);
final JButton button2 = new JButton("B");
final GridBagConstraints grid2 = new GridBagConstraints();
grid2.gridy = 0;
grid2.gridx = 1;
grid2.insets = new Insets(0, 5, 0, 0);
grid2.weightx = 20;
grid2.fill = GridBagConstraints.HORIZONTAL;
c1.add(button2,grid2);
final JButton button3 = new JButton("C");
final GridBagConstraints grid3 = new GridBagConstraints();
grid3.gridy = 0;
grid3.gridx = 2;
grid3.gridheight = 2;
grid3.insets = new Insets(0, 5, 0, 0);
grid3.weightx = 30;
grid3.fill = GridBagConstraints.BOTH;
c1.add(button3,grid3);
final JButton button4 = new JButton("D");
final GridBagConstraints grid4 = new GridBagConstraints();
grid4.gridy = 0;
grid4.gridx = 3;
grid4.gridheight = 4;
grid4.insets = new Insets(0, 5, 0, 5);
grid4.weightx = 40;
grid4.fill = GridBagConstraints.BOTH;
c1.add(button4,grid4);
final JButton button5 = new JButton("E");
final GridBagConstraints grid5 = new GridBagConstraints();
grid5.gridy = 1;
grid5.gridx = 0;
grid5.gridwidth = 2;
grid5.insets = new Insets(5, 0, 0, 0);
grid5.fill = GridBagConstraints.HORIZONTAL;
c1.add(button5,grid5);
final JButton button6 = new JButton("F");
final GridBagConstraints grid6 = new GridBagConstraints();
grid6.gridy = 2;
grid6.gridx = 0;
grid6.insets = new Insets(5, 0, 0, 0);
grid6.weightx = 40;
grid6.fill = GridBagConstraints.HORIZONTAL;
c1.add(button6,grid6);
final JButton button7 = new JButton("G");
final GridBagConstraints grid7 = new GridBagConstraints();
grid7.gridy = 2;
grid7.gridx = 1;
grid7.gridwidth = 2;
grid7.gridheight = 2;
grid7.insets = new Insets(5, 5, 0, 0);
grid7.weightx = 40;
grid7.fill = GridBagConstraints.BOTH;
c1.add(button7,grid7);
final JButton button8 = new JButton("H");
final GridBagConstraints grid8 = new GridBagConstraints();
grid8.gridy = 3;
grid8.gridx = 0;
grid8.insets = new Insets(5, 0, 0, 0);
grid8.fill = GridBagConstraints.BOTH;
c1.add(button8,grid8);
}
public static void main(String[] args)
{
new GridBag2();
}
}
在学习Java的过程中,我练习的一段代码,调试了很多次,不知道失败的原因,特此记录一下。
出现的错误是container.add(button1,grid1),不识别约束,各种百度,没有找到原因,后来尝试将setlayout放置到最前面,问题解决了。
应该是没有先设置布局模式,加入约束时,不成功。