repaint()不更新JPanel

时间:2018-11-14 18:44:49

标签: java swing jpanel repaint

因此,我编写了一个程序,其中有一个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();

    }

1 个答案:

答案 0 :(得分:0)

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

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

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

然后在您的ActionListener中执行以下操作:

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

所有这些操作是再创建3个空面板。您不想再创建3个面板。您想将组件添加到现有面板中。

您需要做的是创建“中心”面板的单个实例,然后保留引用该面板的变量,以便将来可以更新面板。

因此,您需要在类中定义一个实例变量:

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();