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

时间:2017-01-30 02:51:52

标签: java swing jpanel jtextfield

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

1 个答案:

答案 0 :(得分:0)

您必须在文本字段中设置列数或为其指定默认文本。以下代码应该适合您。我已经更新了上一个使用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);
    }
}

希望这会有所帮助。快乐的编码!