public class GridLayout1 {
public static void main(String[] args) { JFrame jf=new JFrame(\网格布局管理器窗体\);
Container c=jf.getContentPane(); JPanel p=new JPanel();
p.setLayout(new GridLayout(2,5,20,20)); p.add(new JButton(\)); p.add(new JButton(\)); p.add(new JButton(\)); p.add(new JButton(\));
p.add(new JButton(\)); c.add(p,BorderLayout.CENTER);
jf.setSize(300,300); } }
jf.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); jf.setLocationRelativeTo(null); jf.setVisible(true);
8. GridBagLayout布局管理器问题及实现
import java.awt.BorderLayout; import java.awt.Container;
import java.awt.GridBagConstraints; import java.awt.GridBagLayout; import java.awt.GridLayout;
import javax.swing.JButton; import javax.swing.JFrame; import javax.swing.JPanel;
public class GridBagLayout1 {
public static void main(String[] args) { JFrame jf=new JFrame(\网格包布局管理器窗体\);
Container c=jf.getContentPane();
JPanel p=new JPanel();
GridBagLayout gr=new GridBagLayout();
p.setLayout(gr);
GridBagConstraints gc=new GridBagConstraints(); gc.fill=GridBagConstraints.BOTH; gc.gridx=0; gc.gridy=0; gc.gridwidth=2; gc.gridheight=1;
JButton bt1=new JButton(\); gr.setConstraints(bt1,gc); p.add(bt1,gc);
gc.gridx=2; gc.gridy=0; gc.gridwidth=1;
gc.gridheight=2;
JButton bt2=new JButton(\); gr.setConstraints(bt2,gc);
p.add(bt2,gc);
gc.gridx=0; gc.gridy=1;
gc.gridwidth=1; gc.gridheight=2;
JButton bt3=new JButton(\); gr.setConstraints(bt3,gc); p.add(bt3,gc);
gc.gridx=1; gc.gridy=1; gc.gridwidth=1; gc.gridheight=1;
JButton bt4=new JButton(\); gr.setConstraints(bt4,gc); p.add(bt4,gc);
gc.gridx=1; gc.gridy=2; gc.gridwidth=2;
gc.gridheight=1;
JButton bt5=new JButton(\); gr.setConstraints(bt5,gc); p.add(bt5,gc);
c.add(p,BorderLayout.CENTER);
jf.setSize(300,300); jf.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); }
}
jf.setLocationRelativeTo(null); jf.setVisible(true);
五、实验总结