为什么我不能将我的 JTextField 插入到我的 JPanel 中?

Why can't I insert my JTextField inside my JPanel?

我的 JTextField 没有显示,只有 paintComponent

public static final int WIDTH = 800;
public static final int HEIGHT = 600;

private JTextField txt;

public Painel(){
    super();
    setFocusable(true);
    setPreferredSize(new Dimension(WIDTH, HEIGHT));
    setLayout(new FlowLayout());
    txt = new JTextField();
    txt.setBounds(400, 300, 50, 20);
}

您必须在文本字段中设置列数或为其提供默认文本。以下代码应该适合您。我已经更新了之前的答案以使用 Gridbag 布局。但是,您仍然需要在 JTextField 中设置列​​数才能呈现它。

    public class TestFrame extends JFrame {

    public static void main(String[] args) {
        new TestFrame();
    }

    private TestFrame() throws HeadlessException {
        super();

        this.setLocationByPlatform(true);
        JPanel contentPane = new JPanel();
        contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
        setContentPane(contentPane);
        GridBagLayout gbl_contentPane = new GridBagLayout();
        gbl_contentPane.columnWidths = new int[] { 100, 0 };
        gbl_contentPane.rowHeights = new int[] { 0, 0, 0 };
        gbl_contentPane.columnWeights = new double[] { 0.0, 1.0, Double.MIN_VALUE };
        gbl_contentPane.rowWeights = new double[] { 0.0, 0.0, Double.MIN_VALUE };
        contentPane.setLayout(gbl_contentPane);

        JTextField textField = new JTextField();
        GridBagConstraints gbc_textField = new GridBagConstraints();
        gbc_textField.insets = new Insets(0, 0, 5, 0);
        gbc_textField.fill = GridBagConstraints.HORIZONTAL;
        gbc_textField.gridx = 1;
        gbc_textField.gridy = 0;
        contentPane.add(textField, gbc_textField);
        textField.setColumns(10);

        this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        this.pack();
        this.setVisible(true);
    }
}

希望这对您有所帮助。编码愉快!