📄 trygridbaglayout.java
字号:
package com.libin.gridbaglayout;
import java.awt.Component;
import java.awt.Container;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import javax.swing.JButton;
import javax.swing.JComboBox;
import javax.swing.JFrame;
import javax.swing.JTextArea;
import javax.swing.JTextField;
public class TryGridBagLayout extends JFrame{
private Container content;
private GridBagLayout gbLayout;
private GridBagConstraints gbConstraints=new GridBagConstraints();
public TryGridBagLayout(){
this.setTitle("网格袋布局管理器使用");
this.setBounds(100,150,400,300);
content=this.getContentPane();
gbLayout=new GridBagLayout();
content.setLayout(gbLayout);
//创建相应相应的组件
JTextArea tx1=new JTextArea(8,5);
tx1.setText("abcdefghigklmnopqrstuvwxyz");
tx1.setLineWrap(true);
JTextArea tx2=new JTextArea(8,5);
tx1.setText("abcdefghigklmnopqrstuvwxyz");
tx1.setLineWrap(true);
JButton b1=new JButton("button1");
JButton b2=new JButton("button2");
JButton b3=new JButton("button3");
JTextField tf1=new JTextField("fadfadsfasfasfds");
String [] names={"James","Jhon","Mike"};
JComboBox combo1=new JComboBox(names);
//向容器中添加组件
gbConstraints.weightx=10;
gbConstraints.weighty=100;
gbConstraints.fill=GridBagConstraints.VERTICAL;
this.addMyComonpent(tx1,0,0,1,3);
gbConstraints.weightx=100;
gbConstraints.weighty=20;
gbConstraints.fill=GridBagConstraints.BOTH;
this.addMyComonpent(b1,0,1,2,1);
gbConstraints.weightx=100;
gbConstraints.weighty=100;
gbConstraints.fill=GridBagConstraints.BOTH;
this.addMyComonpent(b2,1,1,1,1);
gbConstraints.weightx=100;
gbConstraints.weighty=100;
gbConstraints.fill=GridBagConstraints.BOTH;
this.addMyComonpent(b3,1,2,1,1);
gbConstraints.weightx=100;
gbConstraints.weighty=20;
gbConstraints.fill=GridBagConstraints.BOTH;
this.addMyComonpent(combo1,2,1,2,1);
gbConstraints.weightx=10;
gbConstraints.weighty=50;
gbConstraints.fill=GridBagConstraints.HORIZONTAL;
this.addMyComonpent(tf1,3,0,2,1);
gbConstraints.weightx=100;
gbConstraints.weighty=50;
gbConstraints.fill=GridBagConstraints.BOTH;
this.addMyComonpent(tx2,3,2,1,1);
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
this.setResizable(false);
this.setVisible(true);
}
/*
* 为了添加组件方便,用户自定义一个向容器中添加组件的方法
* */
public void addMyComonpent(Component c,int row,int col,int width,int height){
gbConstraints.gridx=col;
gbConstraints.gridy=row;
gbConstraints.gridwidth=width;
gbConstraints.gridheight=height;
//让布局管理器对象为组件添加约束对象
gbLayout.setConstraints(c, gbConstraints);
//向容器中添加组件
content.add(c);
}
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
TryGridBagLayout app=new TryGridBagLayout();
}
}
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -