简体   繁体   English

需要使用GridBagLayout的帮助

[英]Need help using GridBagLayout

I want to make the password label and text field below the ID..but i`m kind of new to GriBagLayout. 我想在ID ..下方设置密码标签和文本字段。但是我是GriBagLayout的新手。

I hope you can help me. 我希望你能帮助我。

Here is my code: 这是我的代码:

   class LoginPanel extends JPanel {//login components
        private JButton exitbtn = new JButton("Exit");
        private JLabel idLabel = new JLabel("Staff ID : ");
        private JTextField idJtf = new JTextField(10);
        private JLabel pwLabel = new JLabel("Password : ");
        private JPasswordField pwJtf = new JPasswordField(10);
        LoginPanel() {
           setOpaque(false);
           setLayout(new GridBagLayout());
           setBorder(BorderFactory.createEmptyBorder(10, 10, 10, 10));
           //add(new JLabel("Staff ID: ")); add(new JTextField(10));
           //add(new JLabel("Password: ")); add(new JPasswordField(10));
           add(idLabel);
           add(idJtf);
           add(pwLabel);
           add(pwJtf);
           //add(exitbtn);
        }      
}

就像阅读本教程一样简单:GridBagLayout

If you are familiar with creating HTML pages using tables, GridBagLayout should be easy for you 如果您熟悉使用表创建HTML页面,那么GridBagLayout应该很容易

Placing controls one below the other is like placing them to a table with single column. 将控件一个放置在另一个下方就像将它们放置在具有单列的表格中一样。 It means that you need to set 0 as a column number and [0..3] as row numbers: 这意味着您需要将0设置为列号,将[0..3]设置为行号:

GridBagConstraints c = new GridBagConstraints();
int rowNum = 0
c.gridx = 0;
c.gridy = rowNum;
add(idLabel, c);

c.gridy++;
add(idJtf, c);

c.gridy++;
add(pwLabel, c);

c.gridy++;
add(pwJtf, c);

However for such simple layout you can use another layout managers 但是对于如此简单的布局,您可以使用其他布局管理器

Do yourself a favor and stop using GridBagLayout. 帮个忙,停止使用GridBagLayout。 GridBagLayout is a layoutmanager from a previous era. GridBagLayout是上一个时代的布局管理器。 I'll realize it is in all the "official" Oracle Java docs but most people avoid it now a days (and for good reasons). 我会在所有“官方” Oracle Java文档中意识到这一点,但是大多数人现在已经避免了这一天(并且有充分的理由)。 A good alternative for complex layouts GridBag is meant to tackle is Jgoodies FormLayout ( http://www.jgoodies.com/freeware/libraries/forms/ ). 对于复杂布局,GridBag可以解决的一个很好的选择是Jgoodies FormLayout( http://www.jgoodies.com/freeware/libraries/forms/ )。 I'll guarantee you that you will maintain your sanity and your life's quality will improve measurably :-) 我向您保证,您将保持理智,生活质量将得到显着改善:-)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM