JAVASwing GridBagLayout 布局

本文详细介绍了如何利用GridBagLayout实现灵活且精确的组件布局,以实例展示了如何通过GridBagConstraints调整输入框的位置和大小,最终实现美观且功能丰富的用户界面。

       用GridBagLayout可实现复杂可控的布局。

       以一个输入框为例:

      

       final  JTextField   username = new JTextField();

       final  JTextField   password = new JTextField();

       JPanel  regist = new JPanel();

       regist.setLayout(new GridBagLayout());
       regist.add(new JLabel("username:"),
                    new GridBagConstraints(0,0,1,1,
                                           0.0,0.0,
                                           GridBagConstraints.CENTER,
                                           GridBagConstraints.NONE,
                                           new Insets(2,2,2,2),
                                           0,0));
       
       
       regist.add(username,
                    new GridBagConstraints(1,0,1,1,
                                           0.0,0.0,
                                           GridBagConstraints.CENTER,
                                           GridBagConstraints.NONE,
                                           new Insets(2,2,2,2),
                                           200,0));
       
       regist.add(new JLabel("password"),
                    new GridBagConstraints(0,1,1,1,
                                           0.0,0.0,
                                           GridBagConstraints.CENTER,
                                           GridBagConstraints.NONE,
                                           new Insets(2,2,2,2),
                                           0,0));


       regist.add(password,
                    new GridBagConstraints(1,1,1,1,
                                           0.0,0.0,
                                           GridBagConstraints.CENTER,
                                           GridBagConstraints.NONE,
                                           new Insets(2,2,2,2),
                                           200,0));







 这里面用到了GridBagConstraints 来定义组件的位置排列信息。

最终的效果如下:

后面输入框的长度可以修改值200 来改变。

具体GridBagConstraints 可参见GridBagConstraints


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值