具有多层的JFrame [英] JFrame that has multiple layers

查看:146
本文介绍了具有多层的JFrame的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个具有两层的窗口:静态背景和包含移动对象的前景.我的想法是只绘制背景一次(因为它不会改变),所以我使更改的面板透明,并将其添加到静态背景的顶部.这是此代码:

I have a window that has two layers: a static background and a foreground that contains moving objects. My idea is to draw the background just once (because it's not going to change), so I make the changing panel transparent and add it on top of the static background. Here is the code for this:

public static void main(String[] args) {
    JPanel changingPanel = new JPanel() {

        @Override
        public void paintComponent(Graphics g) {
            super.paintComponent(g);
            g.setColor(Color.RED);
            g.fillRect(100, 100, 100, 100);
        }
    };
    changingPanel.setOpaque(false);

    JPanel staticPanel = new JPanel();
    staticPanel.setBackground(Color.BLUE);
    staticPanel.setLayout(new BorderLayout());
    staticPanel.add(changingPanel);

    JFrame frame = new JFrame();
    frame.add(staticPanel);
    frame.setSize(800, 600);
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    frame.setVisible(true);
}

这段代码为我提供了我想要的正确图像,但是每次我重新绘制changingPanel时,staticPanel也会被重新绘制(这显然与只绘制一次静态面板的整个想法背道而驰).有人可以告诉我怎么了吗?

This piece of code gives me the correct image I want, but every time I repaint changingPanel, staticPanel gets repainted as well (which is obviously against the whole idea of painting the static panel just once). Can somebody show me what's wrong?

仅供参考,我正在使用javax.swing.Timer每秒重新计算和重新绘制更改面板24次.

FYI I am using the javax.swing.Timer to recalculate and repaint the changing panel 24 times every second.

推荐答案

当您在另一个组件上方重新绘制透明组件时,仍然会弄脏"下部组件,从而导致其重新绘制.如果不重新粉刷较低的图层,则会在其顶部获得图像的拖尾效果.

When you repaint a transparent component above another, you still 'dirty' the lower component, causing it the be repainted. If you didn't repaint the lower layer, you would get a smearing effect of the image on top of it.

此处唯一可用的优化是不重新生成较低级别上使用的图像.每次更改上面的图层时,仍需要将栅格绘制到图形缓冲区.

The only optimisation available here is not regenerating the image used on the lower level. The raster still needs to be painted to the graphics buffer every time the layer above changes.

这篇关于具有多层的JFrame的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆