我正在尝试在JLabel下设置JTextField [英] I'm trying to set JTextField under JLabel

查看:153
本文介绍了我正在尝试在JLabel下设置JTextField的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试将文本字段放在JLabel下.当前,文本字段显示在同一行上.它应该在下方并居中.我需要帮助.

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

推荐答案

您可以简单地将GridLayout与单个列一起使用:

You could simply use a GridLayout with a single column:

setLayout(new GridLayout(0, 1));

请注意,GridLayout将忽略JTextFields的首选大小,因此使用构造函数JTextField(int columnSize)将无效,因此默认构造函数将起作用.

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.

我也将在此处删除内部间距,并在JFrame上添加边框:

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

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

这将产生一个看起来像

这篇关于我正在尝试在JLabel下设置JTextField的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆