简体   繁体   English

如何在不影响其他组件的情况下重新绘制组件

[英]How to repaint a component without affecting other components

I subclass JPanel to show animated images using a timer. 我将JPanel子类化,以使用计时器显示动画图像。 Here's the timer's task. 这是计时器的任务。

private class AnimationTimerTask extends TimerTask {
    @Override
    public void run() {
        // Change the current image

        repaint();
    }
}

Besides, I override the paintComponent method to draw the current image. 此外,我重写了paintComponent方法以绘制当前图像。

I use this class to create an object as the background and there is a label on it. 我使用此类创建一个对象作为背景,并在其上贴上标签。 I use the "setComponentZOrder" method to make sure the label is on the background. 我使用“ setComponentZOrder”方法来确保标签位于背景上。

At first, the label is shown normal. 首先,标签显示为正常。 But it was covered by the background after the background's image changed, which means the repaint method is called. 但是在背景图像更改后,背景覆盖了该背景,这意味着将调用repaint方法。

I guess the problem is caused by the repaint of the background object. 我猜问题是由背景对象的重新绘制引起的。

I replace the repaint() to getParent.repaint(), and the problem solved. 我将repaint()替换为getParent.repaint(),问题解决了。 But I don't think it's the right way. 但是我认为这不是正确的方法。

I'm honestly not sure if this is the right or wrong answer, so I hope others can chime in on this. 老实说,我不确定这是对还是错,所以我希望其他人能对此有所了解。 But there is something called the RepaintManager . 但是有些东西叫做RepaintManager That article says: 那篇文章说:

For most programs, the RepaintManager can be viewed as part of Swing's internal system and can virtually be ignored. 对于大多数程序,RepaintManager可以视为Swing内部系统的一部分,并且实际上可以忽略。 However, its API provides programs the option of gaining finer control over certain aspects of painting. 但是,其API为程序提供了对绘画某些方面进行更好控制的选项。

It has methods like this: 它具有如下方法:

public static RepaintManager currentManager(JComponent c)
public synchronized void addDirtyRegion(JComponent c, int x, int y, int w, int h) 
public Rectangle getDirtyRegion(JComponent aComponent)
public void markCompletelyDirty(JComponent aComponent) 

It's straight forward to use these methods to do what you want. 使用这些方法直接做您想要的事情。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM