无法将 JLabel 或 JButton 添加到 JFrame。框架不会显示它

Cannot add JLabel or JButton to a JFrame. The frame won't show it

我是 Java 的新手。我正在尝试将 JLabel 添加到 JFrame 但它没有显示。我也试过添加 JButton 但它似乎不起作用。这几天我尝试了很多东西。

我的代码有什么问题吗?

public class F2 extends JPanel implements ActionListener {

    JFrame frame = new JFrame();
    JLabel label = new JLabel();
    int j = 2;
    ArrayList<Person> people = new ArrayList<>();

    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) {
        F2 f = new F2();

    }

    public F2() {
        j++;
        frame = new JFrame();
        frame.setSize(1380, 728);
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        Timer t = new Timer(20, this);
        t.restart();
        label.setText("Test");

        add(label);
frame.pack();
        frame.add(this);
        frame.setVisible(true);

        for (int i = 0; i < 100; i++) {
            people.add(new Person(0));
        }
    }

    public void paint(Graphics g) {
        super.paintComponent(g);
        Places p1 = new Places(g);
        for (Person p : people) {
            p.paint(g); //recall that each Person object has a paint method. We're passing g as the argument
        }
    }

    @Override
    public void actionPerformed(ActionEvent e) {
        repaint();
    }
}

正在复制 Alex Rudenko 的回答:

您应该已经将标签添加到您的面板,然后将您的面板添加到框架。现在您的空面板将替换标签。

this.add(label)
frame.add(this)

也许让它也可见并使用坐标和大小...或者只是从互联网上复制预制代码...您在主要 class 中使用 jpanel 的方式可能是把你弄糊涂了。