开发者社区> 问答> 正文

使用GridBagLayout布局,怎样设置组件大小,? 400 报错

使用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);
}



}

展开
收起
爱吃鱼的程序员 2020-05-30 22:16:16 568 0
1 条回答
写回答
取消 提交回答
  • https://developer.aliyun.com/profile/5yerqm5bn5yqg?spm=a2c6h.12873639.0.0.6eae304abcjaIB

    这个布局太麻烦,还不如设置顶层容器 setLayout(null);然后再其上面添加各种组件 用setBounds(x,y,w,h);设置大小,注意JLabel设置setBounds的时候 要setOpaque(true);然后再setBounds

    2020-05-30 22:16:17
    赞同 展开评论 打赏
问答地址:
问答排行榜
最热
最新

相关电子书

更多
低代码开发师(初级)实战教程 立即下载
冬季实战营第三期:MySQL数据库进阶实战 立即下载
阿里巴巴DevOps 最佳实践手册 立即下载