I'm trying to set JTextField under JLabel

与世无争的帅哥 提交于 2019-12-11 14:06:26

问题


I'm trying to put the text field under the JLabel. Currently, the text field is displayed on the same line. It should be below and centered. I need assistance.

package Gui;

import javax.swing.*;
import java.awt.*;
import java.awt.GridLayout;

public class ShowGridLayout extends JFrame {

    public ShowGridLayout() {
        // Set GridLayout, 3 rows, 2 columns, and gaps 5 between
        // components horizontally and vertically
        setLayout(new GridLayout(3, 2, 5, 5));

        // Add labels and text fields to the frame

        JLabel firstname = new JLabel("First Name");
        add(firstname);

        JTextField fistnametextField = new JTextField(8);
        add(fistnametextField);

        JLabel mi = new JLabel("Mi");
        add(mi);

        JTextField miTextField = new JTextField(1);
        add(miTextField);

        JLabel lastname = new JLabel("Last Name");
        add(lastname);

        JTextField lastnameTextField = new JTextField(8);
        add(lastnameTextField);
    }

    /**
    * Main method
    */
    public static void main(String[] args) {
        ShowGridLayout frame = new ShowGridLayout();
        frame.setTitle("ShowGridLayout");
        frame.setSize(200, 125);
        frame.setLocationRelativeTo(null); // Center the frame
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setVisible(true);
    }
}

回答1:


You could simply use a GridLayout with a single column:

setLayout(new GridLayout(0, 1));

Note that GridLayout will ignore the preferred sizes of the JTextFields so using the constructor JTextField(int columnSize) will have no effect so the default constructor will do.

Also I would remove the internal spacing here and add a border to the JFrame:

(JComponent)getContentPane()).setBorder(   
      BorderFactory.createEmptyBorder(10, 10, 10, 10) );  

This would produce a frame that looks like




回答2:


You are creating a 3x2 grid. That is, 3 rows of 2 columns each. the first call to add() will put the component in row 1, col 1 and the second call will put the component in row 1 col 2. So they are next to each other. With GridLayout you do not have much control over this. If you want items to be one over the next you can try a 3x1 grid. Or you can try adding components in a different order. Or you can try a different layout manager such as GridBagLayout where you have more control.



来源:https://stackoverflow.com/questions/13893613/im-trying-to-set-jtextfield-under-jlabel

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!