使用GridBagLayout布局,怎样设置组件大小,? 400 报错
我使用使用GridBagLayout布局,结果JComboBox都特别小,JTextArea无法显示。这是怎么回事啊?
代码如下:class IncomeExpeses{
final static int WIDTH = 400;
final static int HEIGHT = 200;
public static JFrame ieframe;
public static JPanel iepane;
public static JLabel label1;
public static JLabel label2;
public static JLabel label3;
public static JLabel label4;
public static JLabel label5;
public static JLabel label6;
public static JComboBox date;
public static JComboBox item;//支出项目
public static JTextField money;
public static JComboBox account;
public static JTextArea message;
public static JButton save;
public static JButton cancel;
static GridBagLayout gbl = new GridBagLayout();
public void add(Component c,GridBagConstraints constraints,int x,int y,int w,int h){
constraints.gridx = x;
constraints.gridy = y;
constraints.gridwidth = w;
constraints.gridheight = h;
gbl.setConstraints(c, constraints);
iepane.add(c);
}
public IncomeExpeses() {
//定义组件
iepane = new JPanel();
iepane.setLayout(gbl);
label1 = new JLabel("收入日期:");
label2 = new JLabel("收入项目:");
label3 = new JLabel("收入金额:");
label4 = new JLabel("收入账户:");
label5 = new JLabel("备注:");
date = new JComboBox();
item = new JComboBox();
money = new JTextField(10);
account = new JComboBox();
message = new JTextArea();
save = new JButton("保存");
cancel = new JButton("取消");
GridBagConstraints constraints = new GridBagConstraints();
constraints.anchor = GridBagConstraints.WEST;
constraints.fill = GridBagConstraints.NONE;
constraints.weightx = 4;
constraints.weighty = 5;
add(label1,constraints,0,0,1,1);
add(label2,constraints,2,0,1,1);
add(label3,constraints,0,1,1,1);
add(label4,constraints,2,1,1,1);
add(label5,constraints,0,2,1,1);
add(date,constraints,1,0,1,1);
add(item,constraints,3,0,1,1);
add(money,constraints,1,1,1,1);
add(account,constraints,3,1,1,1);
add(message,constraints,1,2,GridBagConstraints.RELATIVE,2);
add(save,constraints,1,4,1,1);
add(cancel,constraints,2,4,1,1);
ieframe = new JFrame();
ieframe.setSize(WIDTH,HEIGHT);
ieframe.setContentPane(iepane);
ieframe.setResizable(false) ;
ieframe.setVisible(true) ;
ieframe.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
}
这个布局太麻烦,还不如设置顶层容器 setLayout(null);然后再其上面添加各种组件 用setBounds(x,y,w,h);设置大小,注意JLabel设置setBounds的时候 要setOpaque(true);然后再setBounds
版权声明:本文内容由阿里云实名注册用户自发贡献,版权归原作者所有,阿里云开发者社区不拥有其著作权,亦不承担相应法律责任。具体规则请查看《阿里云开发者社区用户服务协议》和《阿里云开发者社区知识产权保护指引》。如果您发现本社区中有涉嫌抄袭的内容,填写侵权投诉表单进行举报,一经查实,本社区将立刻删除涉嫌侵权内容。