这个问题类似于Paint on a glass pane without repainting other components。但是我不知道如何应用那里提供的解决方案。

我的问题是我们有一个非常复杂的RootPane,许多组件,并且重新绘制它很昂贵。我们还在JFrame的GlassPane上运行了一个动画。我注意到动画的每个滴答声都按照应有的方式重新绘制了动画,但同时也导致基础RootPane上的所有内容也都被重新绘制。

我尝试使用各种代码覆盖RootPane的paint()方法,但是它总是会导致RootPane上的组件被擦除并产生大量闪烁,这可能是由于在动画期间事物更新时子组件试图重新绘制自身而导致的:

pnlContent = new JRootPane() {
   @Override
   public void paint(Graphics g) {
      OurGlassPaneWithAnimation glass = ...
      if (glass != null && glass.animation != null && glass.animation.isAlive()) {
         //Animation running, do something cool so root pane still looks good without repainting out the wazoo
      } else { super.paint(g); }
   }
};


将动画放在GlassPane中也许不是一个好主意?不过,我们已经将其更改为位于居中的JPanel中。还是有一个很好的方法使用GlassPane做到这一点,并将对背景RootPane的重绘保持在最小程度?

最佳答案

@MadProgrammer感谢您提出做repaint(rect)而不是仅仅repaint()解决问题的建议。现在,我们可以将动画fps提高到所需的最高水平,并且不会显着影响其背后的RootPane的加载时间。这是代码片段。

while (keepOnAnimating) {
   BufferedImage bi = vFrames.elementAt(0);
   if (bi != null) {
      // This only repaints area of image rect
      // Prevents lots of repaints from happening in rootpane behind glasspane.
      int x = getWidth() / 2 - bi.getWidth() / 2;
      int y = getHeight() / 2 - bi.getHeight() / 2;
      jc.repaint(x, y, bi.getWidth(), bi.getHeight());
  } else {
     jc.repaint();
  }
  ...
}

关于java - 防止GlassPane重绘上的RootPane重绘,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/29784969/

10-09 03:55