简体   繁体   中英

Reduce Spaces in a GridLayout Java Swing

Good day, please would like to know how to reduce the spaces between the labels and the Textboxes in this picture below and also how to create some spaces between the labels and the frame.Thank you.

登录页面

My code for this:

private void initUI(JFrame parent) {
    // private void initUI() {
   myPanel = new JPanel(new GridLayout(3,2,1,1));
   buttons_panel = new JPanel(new FlowLayout());

   username_label = new JLabel("Username: ");
   password_label = new JLabel("Password: ");
   username = new JTextField(20);
   password = new JPasswordField(20);

   ok = new JButton("Ok");
   ok.addActionListener(new ActionListener() {

        public void actionPerformed(ActionEvent e) {

        }
    });

    cancel = new JButton("Cancel");
    cancel.addActionListener(new ActionListener() {

        public void actionPerformed(ActionEvent e) {
           dispose();
        }
    });

    myPanel.add(username_label);
    myPanel.add(username);
    myPanel.add(password_label);
    myPanel.add(password);

    buttons_panel.add(ok);
    buttons_panel.add(cancel);

    getContentPane().add(myPanel, BorderLayout.CENTER);
    getContentPane().add(buttons_panel, BorderLayout.PAGE_END);

    pack();
    setResizable(false);
    setLocationRelativeTo(parent);
}

Should i be using GridBagLayout for this instead?..

All cells in GridLayout have equal size. You have to use GridBagLayout or SpringLayout or BoxLayout .

or use proper

1) Borders

2) set for Alignment ( left - right , top - bottom ) for

您还可以使用GridLayout hgaphgap参数,并添加匹配,空Border ,如图所示这里

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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