import java.awt.Component;
import java.awt.Container;
import java.awt.GraphicsEnvironment;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import javax.swing.JCheckBox;
import javax.swing.JComboBox;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTextArea;
public class GirdBagLayoutTest
{
public static void main(String[] args)
{
GirdBagLayoutFrame frame = new GirdBagLayoutFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
}
}
class GirdBagLayoutFrame extends JFrame
{
public GirdBagLayoutFrame()
{
setTitle("网格组事件");
setSize(300, 200);
Container con = getContentPane();
GirdBagLayoutPanel panel = new GirdBagLayoutPanel();
con.add(panel);
}
}
class GirdBagLayoutPanel extends JPanel
{
public JLabel lname, lsize;
public JComboBox cname, csize;
public JCheckBox bold, italic;
public JTextArea area;
public GirdBagLayoutPanel()
{
lname = new JLabel("Name");
lsize = new JLabel("Size");
String[] fonts = GraphicsEnvironment.getLocalGraphicsEnvironment()
.getAvailableFontFamilyNames();
cname = new JComboBox(fonts);
csize = new JComboBox(new String[]
{ "8", "12", "14", "16", "18", "20", "24", "26", "36" });
bold = new JCheckBox("Bold");
italic = new JCheckBox("Italic");
area = new JTextArea("欢迎来到太湖");
area.setLineWrap(true);//自动换行
//实例化网格组布局
GridBagLayout layout = new GridBagLayout();
//设置布局管理
setLayout(layout);
//实例化网格组布局的限制类(此类协助网格组布局类完成工作)
GridBagConstraints constraints = new GridBagConstraints();
constraints.anchor = GridBagConstraints.EAST;//居右对其
constraints.fill = GridBagConstraints.NONE;//不填充
constraints.weightx = 0; //水平方向不缩放
constraints.weighty = 0; //垂直方向不缩放 0代表不缩放 100代表缩放
addObj(constraints,0,0,1,1,lname);
addObj(constraints,0,1,1,1,lsize);
constraints.fill = GridBagConstraints.HORIZONTAL;//水平填充
constraints.weightx = 100;//水平缩放
addObj(constraints,1,0,1,1,cname);
addObj(constraints,1,1,1,1,csize);
constraints.weighty = 100;//垂直缩放
constraints.fill = GridBagConstraints.NONE;//不填充
constraints.anchor = GridBagConstraints.CENTER;//居中对其
addObj(constraints,0,2,2,1,bold);
addObj(constraints,0,3,2,1,italic);
constraints.fill = GridBagConstraints.BOTH;//水平垂直都填充
addObj(constraints,2,0,1,4,area);
}
//方法
public void addObj(GridBagConstraints gc,int x,int y,int w,int h,
Component c)//传递参数 Component 主键
{
gc.gridx = x;
gc.gridy = y;
gc.gridwidth = w;
gc.gridheight = h;
add(c,gc);
}
}