Swing 计时器和性能不佳(Java、Swing)

问题描述 投票:0回答:1

我对 Swing Timer 有疑问。我正在尝试为 JPanel 创建一个“滑动”动画,按下按钮时它会从侧面滑入。这实际上工作得很好,但是当我想让它再次滑出时,我会遇到性能极差的情况。注意:JPanel 位于 JLayeredPane 中,并且其下方还有其他组件(这一点很重要)。

这是滑入的代码:

int boundsTo = GlobalValue.getLargeInformationBarWidth();
        final int[] boundsNow = {0};
        inSlideTimer = new Timer(1, ae -> {
            if (boundsTo > boundsNow[0]){
                boundsNow[0] = boundsNow[0] + 3;
                JourneyPlannerBarController.getInstance().getInformationBar().setBounds(0, 0, boundsNow[0], window.getFrame().getHeight());
                JourneyPlannerBarController.getInstance().getInformationBar().revalidate();
                JourneyPlannerBarController.getInstance().getInformationBar().repaint();
            } else {
                inSlideTimer.stop();
                inSlideTimer = null;
            }
        });
        inSlideTimer.start();
        JourneyPlannerBarController.getInstance().setupLargeJourneyPlannerBar();
}

这是滑出的代码:

int boundsTo = 0;
final int[] boundsNow = {GlobalValue.getLargeInformationBarWidth()};
inSlideTimer = new Timer(1, ae -> {
        if (boundsTo <= boundsNow[0]) {
            boundsNow[0] = boundsNow[0] - 3;
            JourneyPlannerBarController.getInstance().getInformationBar().setBounds(0, 0, boundsNow[0], window.getFrame().getHeight());
            JourneyPlannerBarController.getInstance().getInformationBar().revalidate();
            JourneyPlannerBarController.getInstance().getInformationBar().repaint();

        } else {
            inSlideTimer.stop();
            inSlideTimer = null;
            JourneyPlannerBarController.getInstance().clearJourneyPlannerBar();
            CanvasController.repaintCanvas();
        }
});
inSlideTimer.start();
}

可以看出,这两块代码几乎相同,但性能差异确实很大。我一直在尝试阅读 SwingWorker、EDT 等内容,但到目前为止我还没有找到任何可以帮助我的内容。

java swing
1个回答
0
投票

你说滑入和滑出是相同的程序。对于用户界面来说,它们还不是,到目前为止。

滑入菜单时,每次迭代都会变宽,因此 UI 需要反复重新绘制菜单。底层组件逐渐隐藏,因此无需执行任何操作。

滑出时,菜单每次迭代都会变细,因此UI需要反复重新绘制菜单。但现在底层组件变得可见,它们也需要重新绘制。根据渲染整个 UI 所需的时间,这对 UI 来说显然需要更多工作。

如果你想阻止(或加速),你可以

  • 抓取整个菜单的图像(如屏幕截图)
  • 抓取整个底层 UI 的图像(如屏幕截图)

滑出时,创建一个覆盖整个窗口的组件。对于滑出的每次迭代,重复绘制背景图像,然后在顶部绘制菜单图像。这会快得多,并且一旦完成动画,您就可以删除此静态图像并允许用户再次访问完整的 UI。

© www.soinside.com 2019 - 2024. All rights reserved.