Java 如何从paintComponent()向GridBagLayout添加元素

Java 如何从paintComponent()向GridBagLayout添加元素,java,swing,jpanel,paintcomponent,gridbaglayout,Java,Swing,Jpanel,Paintcomponent,Gridbaglayout,在下面的代码中,在构造函数中正确创建标签并在屏幕上显示。请注意,它已添加到GridBagLayout()layout管理器中。然后,在我们从JPanel扩展覆盖的paintComponent()方法中,我们重置JPanel的内容并再次添加标签。但是,这次标签不会显示在屏幕上。我希望它能正常添加,但事实并非如此。为什么会这样 public class MyPanel extends JPanel { private final GridBagConstraints grid = new

在下面的代码中,在构造函数中正确创建标签并在屏幕上显示。请注意,它已添加到
GridBagLayout()
layout管理器中。然后,在我们从JPanel扩展覆盖的
paintComponent()
方法中,我们重置JPanel的内容并再次添加标签。但是,这次标签不会显示在屏幕上。我希望它能正常添加,但事实并非如此。为什么会这样

public class MyPanel extends JPanel {

    private final GridBagConstraints grid = new GridBagConstraints();

    public MyPanel () {
        setBounds(200, 200, 1000, 1000);
        setLayout(new GridBagLayout());
        setOpaque(false);
        setVisible(false);

        grid.anchor = GridBagConstraints.PAGE_END;

        JLabel oldLabel = new JLabel("This is an old Label");
        add(oldLabel, grid);
    }

    @Override
    public void paintComponent(Graphics g) {
        super.paintComponent(g);

        removeAll();

        JLabel newLabel = new JLabel("This is a new Label");
        add(newLabel, grid);

        revalidate();
        repaint();
    }

}

在本例中,组件是已知的,但在我的情况下,我有大量的组件是事先未知的,并且在程序中会发生变化。

正如对我问题的评论所说,我的方法是不正确的

在任何情况下都不允许
paintComponent
创建、添加或删除组件。绘画是由系统触发的,原因有很多,包括看似琐碎的事件,比如在窗口上移动鼠标。另外,不要从paintComponent方法调用
repaint
;这迫使Swing最终再次调用paintComponent,这意味着您已经创建了一个无限循环


解决方案是将组件添加到面板中,并在面板上调用
revalidate()

函数
paintComponent(Graphics g)
中不允许创建新的Swing或AWT元素。在调用
repaint
后,不断调用该函数以更新所有元素。在任何情况下,paintComponent都不应创建、添加或删除组件。绘画是由系统触发的,原因有很多,包括看似琐碎的事件,比如在窗口上移动鼠标。另外,不要从paintComponent方法调用
repaint
;这迫使Swing最终再次调用paintComponent,这意味着您已经创建了一个无限循环。感谢您的回复。如果无法将组件添加到paintComponent()中,您将如何显示它们?在我的示例中,组件是已知的,但在我的情况下,有大量的组件是事先未知的,并且在程序中会发生变化。(我将编辑问题以细化它)和程序期间的更改-因此,您可以将组件添加到面板并在面板上调用
revalidate()