简单的JFrame程序但看不到JTextfield

时间:2012-12-04 22:54:36

标签: java swing jframe jpanel jtextfield

我正在尝试自己学习Swing。 我正在玩玩具程序,要求用户输入他们的名字。我将JLabel和JTextfield放入JPanel,用户可以在其中输入名称并提交。然而,我的JTextfield被压扁并且看不见,我无法显示它(我试过“setSize”无效)。

Invisible JTextField

这是我的代码:

import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTextField;


public class NamePrompt extends JFrame{


    private static final long serialVersionUID = 1L;

    String name;

    public NamePrompt(){

        setLayout(new BorderLayout());

        JLabel enterYourName = new JLabel("Enter Your Name Here:");
        JTextField textBoxToEnterName = new JTextField();
        textBoxToEnterName.setSize(40, 10);
        JPanel panelTop = new JPanel();
        panelTop.add(enterYourName);
        panelTop.add(textBoxToEnterName);

        JButton submit = new JButton("Submit");
        submit.addActionListener(new SubmitButton());
        JPanel panelBottom = new JPanel();
        panelBottom.add(submit);

        //Add panelTop to JFrame
        add(panelTop, BorderLayout.NORTH);
        add(panelBottom, BorderLayout.SOUTH);

        //JFrame set-up
        setTitle("Name Prompt Program");
        setSize(300, 150);
        setLocationRelativeTo(null);


    }



    public static void main(String[] args) {
        NamePrompt promptForName = new NamePrompt();
        promptForName.setVisible(true);


    }

1 个答案:

答案 0 :(得分:2)

JTextField textBoxToEnterName = new JTextField(20);

有关说明,请参阅new JTextField(columns)。 E.G。

NamePrompt

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

public class NamePrompt extends JFrame{

    private static final long serialVersionUID = 1L;

    String name;

    public NamePrompt(){

        setLayout(new BorderLayout());

        JLabel enterYourName = new JLabel("Enter Your Name Here:");
        JTextField textBoxToEnterName = new JTextField(21);
        //textBoxToEnterName.setSize(40, 10);
        JPanel panelTop = new JPanel();
        panelTop.add(enterYourName);
        panelTop.add(textBoxToEnterName);

        JButton submit = new JButton("Submit");
        //submit.addActionListener(new SubmitButton());
        JPanel panelBottom = new JPanel();
        panelBottom.add(submit);

        //Add panelTop to JFrame
        add(panelTop, BorderLayout.NORTH);
        add(panelBottom, BorderLayout.SOUTH);

        //JFrame set-up
        setTitle("Name Prompt Program");
        //setSize(300, 150);
        pack();
        setLocationRelativeTo(null);
    }

    public static void main(String[] args) {
        NamePrompt promptForName = new NamePrompt();
        promptForName.setVisible(true);
    }
}