0

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

不可见的 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);


    }
4

1 回答 1

2
JTextField textBoxToEnterName = new JTextField(20);

new JTextField(columns)解释。例如

名称提示

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);
    }
}
于 2012-12-04T22:57:31.310 回答