repaint() 不更新 JPanel

repaint() not updating JPanel

所以我制作了一个程序,其中有一个 GUI,用户可以在其中输入烟花发射的参数,并且在屏幕中间有一个面板,当按下按钮时应该在该面板上绘制发射按下。然而,在我的程序中,JPanel 没有更新,也没有绘制任何内容。代码如下

//This is the method that build the JPanel in the center for the launch
public JPanel buildCenter() {
    JPanel center=new JPanel();
    center.setBackground(Color.black);
    center.setVisible(true);
    return center;
}


//This is the method the build the GUI, the buttons and such are in the other panels labeled top, west, east, etc.
public void buildGUI(){
    configureSliders();
    configureRadioButtons();
    JFrame frame=new JFrame();
    JPanel panel=new JPanel();
    JPanel top=new JPanel();
    panel.setLayout(new BorderLayout());
    Fireworks.setFont(new Font("Helvetica", Font.BOLD, 30));
    frame.setLayout(new BorderLayout());
    top.setLayout(new BoxLayout(top, BoxLayout.X_AXIS));
    top.add(Box.createHorizontalGlue());
    top.add(Fireworks);
    top.add(Box.createHorizontalGlue());
    frame.add(top, BorderLayout.NORTH);
    frame.add(panel, BorderLayout.CENTER);
    frame.setSize(1920,1080);
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    frame.setVisible(true);
    panel.add(buildCenterTop(),BorderLayout.NORTH);
    panel.add(buildCenter(), BorderLayout.CENTER);
    panel.add(buildwest(), BorderLayout.WEST);
    panel.add(buildeast(),BorderLayout.EAST);
    panel.add(Launch, BorderLayout.SOUTH);
    Launch.addActionListener(this);
}
//this is the action performed method where repaint won't work. fire is my fireworks object with the paintcomponent method for the launch.
@Override
public void actionPerformed(ActionEvent e) {
    if (e.getSource().equals(Launch)) {
        setColor();
        setTime();
        setExplosion();
        fire.setVelocity(veloslider.getValue());
        fire.setTheta(thetaslider.getValue());
        buildCenter().add(fire);
        buildCenter().repaint();
        buildCenter().validate();

    }

您的 buildCenter() 方法所做的只是创建一个黑色背景的空白面板。

然后将这个空白面板添加到框架中:

panel.add(buildCenter(), BorderLayout.CENTER);

然后在您的 ActionListener 中执行:

buildCenter().add(fire);
buildCenter().repaint();
buildCenter().validate();

这只是再创建 3 个空白面板。您不想再创建 3 个面板。您想将组件添加到现有面板。

您需要做的是创建 "center" 面板的单个实例,然后保留一个引用此面板的变量,以便您将来可以更新面板。

因此您需要在 class:

中定义一个实例变量
private JPanel centerPanel;

然后在 buildGui() 方法中创建面板:

//panel.add(buildCenter(), BorderLayout.CENTER);
centerPanel = buildCenter();
panel.add(buildCenter, BorderLayout.CENTER);

然后在您的 ActionListener 中您可以将组件添加到中心面板:

//buildCenter().add(fire);
//buildCenter().repaint();
//buildCenter().validate();
centerPanel.add( fire );
centerPanel.revalidate();
centerPanel.repaint();