添加 JTextField 会产生空的 JFrame

问题描述

我对此很陌生,我正在学习一个教程,一切都很好。但是,当添加 JTextField 时,JFrame 会变成纯灰色背景。我正在调用从 Main.java 生成 JFrame 的 GUI 类,因此我尝试仅使用 Main.java 中的文本字段生成 JFrame,但它有同样的问题。向文本字段添加删除组件也没有做任何事情。将它放在面板中没有帮助(面板与标签配合良好)。

public class GUI extends JFrame {

    JButton button;
    
    GUI(){
        this.setTitle("Visualization");
        this.setSize(1200,800);
        this.setResizable(false);
        this.setLayout(null);
        this.setVisible(true);
        this.setDefaultCloSEOperation(JFrame.EXIT_ON_CLOSE);

        ImageIcon image = new ImageIcon("Default/WhiteCatPFP.jpg");
        this.setIconImage(image.getimage());
        //this.getContentPane().setBackground(Color.BLACK);

        Border border = BorderFactory.createLineBorder(Color.green,3);

        JLabel label = new JLabel();
        label.setForeground(Color.GREEN);
        label.setText("bro,do you even code?");
        label.setBackground(Color.BLACK);
        label.setHorizontalAlignment(JLabel.CENTER);
        label.setopaque(true);
        label.setBorder(border);
        label.setFont(new Font(this.getFont().getName(),Font.PLAIN,30));
        //label.setVerticalAlignment(JLabel.TOP);
        //label.setFont(new Font("MV Boli",20));

        button = new JButton();
        button.setFocusable(false);
        button.setForeground(Color.GREEN);
        button.setBackground(Color.BLACK);
        button.setopaque(true);
        button.setBorder(border);
        button.setText("Baka");
        button.setFont(new Font(this.getFont().getName(),20));
        button.setBounds(50,10,100,90);
        button.addActionListener(e -> System.out.println("Epic")); // Called lambda

        JTextField aTextField = new JTextField("Hello"); // <-------------------- Error inducing!
        aTextField.setBounds(0,400,200);

        JPanel panelOne = new JPanel();
        panelOne.setBounds(0,200);
        panelOne.setLayout(new BorderLayout());

        JPanel panelTwo = new JPanel();
        panelTwo.setBounds(0,200,200);
        panelTwo.setLayout(new BorderLayout());

        JPanel panelThree = new JPanel();
        panelThree.setBounds(0,200);
        panelThree.setLayout(new BorderLayout());

        panelOne.add(label);
        panelTwo.add(button);
        panelThree.add(aTextField);
        this.add(panelOne);
        this.add(panelTwo);
        this.add(panelThree);
    }
}

有很多东西是为了笔记,我宁愿为这个特定项目使用空布局(除非这是错误的来源),右边的空白区域用于我稍后添加内容.

注意:没有文本字段,其他一切都显示正常。即使只是定义文本字段 JTextField aTextField = new JTextField(); 使 JFrame 成为灰色背景。也没有崩溃。

非常感谢任何帮助!

解决方法

我正在学习教程

如果教程使用的是空布局,则摆脱教程。没有理由使用空布局。 Swing 旨在与布局管理器一起使用(原因太多,无法在此处列出)。

阅读 Layout Managers 上的 Swing 教程以获得正确的演示代码。教程代码将向您展示如何正确创建 Swing 框架。从教程中的演示代码开始,然后进行更改。

但是,当添加 JTextField 时,JFrame 会变成纯灰色背景。

文本字段与您的问题无关。

问题是需要在框架可见之前将组件添加到框架中。 setVisible( true ) 语句应该是构造函数中的最后一条语句。