JTextField在启动时没有出现在JPanel中

taz*_*boy 5 java swing jpanel jtextfield layout-manager

JTextField是因为当我将鼠标移动到它应该是鼠标图标变为光标的位置时,当我点击它时就显示出来了.但它在发布时是看不见的.我错过了什么?

public class JavaSwingTextfield extends JFrame {
    private static final long serialVersionUID = 1L;

    JTextField myTextField;

    public JavaSwingTextfield(){

        /***** JFrame setup *****/

        // Set the size of the window
        setSize(600,600);

        // Make the application close when the X is clicked on the window
        setDefaultCloseOperation(EXIT_ON_CLOSE);

        // Makes the JFrame visible to the user
        setVisible(true);

        /***** JFrame setup END *****/


        /***** JButton setup *****/

        // Create a JLabel and set its label to "Start"
        myTextField = new JTextField("Start");

        // Set the label's size
        myTextField.setSize(100, 50);

        // Put the label in a certain spot
        myTextField.setLocation(200, 50);

        // Set a font type for the label
        //Font myFont = new Font("Serif", Font.BOLD, 24);
        //myTextField.setFont(myFont);

        // Add the label to the JFrame
        add(myTextField);

        /***** JButton setup END *****/

    }


    /***** The main method *****/
    public static void main(String[] args){ 

        new JavaSwingTextfield();

    }

}
Run Code Online (Sandbox Code Playgroud)

Dav*_*amp 11

  • 使用Event Dispatch Thread用于创建GUI组件
  • setVisible(..)在将所有组件添加到之前不要调用JFrame(这是上面的代码片段实际错误+1到@Clark)
  • 不要不必要地扩展JFrame课程
  • 在设置可见之前不要打电话setSize(..),而只是简单地打电话JFrame#pack()JFrame
  • 不要叫setSize()JTextField,而看它的构造函数:JTextField(String text,int columns)
  • 使用适当的LayoutManagers,请参阅此处以获取一些示例:布局管理器的可视指南

这是我做的一个例子(基本上你的代码有修复):

import javax.swing.JFrame;
import javax.swing.JTextField;
import javax.swing.SwingUtilities;

public class JavaSwingTextfield {

    private JTextField myTextField;

    public JavaSwingTextfield() {
        JFrame frame = new JFrame();
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        
        myTextField = new JTextField("Start");
        
        // Add the label to the JFrame
        frame.add(myTextField);
        
        //pack frame to component preferred sizes
        frame.pack();
        frame.setVisible(true);
    }

    public static void main(String[] args) {
        //Create UI on EDT
        SwingUtilities.invokeLater(new Runnable() {
            @Override
            public void run() {
                new JavaSwingTextfield();
            }
        });
    }
}
Run Code Online (Sandbox Code Playgroud)