Java – JFrame with multiple layers
I have a window with two layers: a static background and a foreground containing moving objects My idea is to draw the background only once (because it won't change), so I'll change the panel transparency and add it to the static background This is the following code:
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); } }; 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); }
This code gives me the correct image I want, but every time I redraw the changingpanel, the static panel will be redrawn (which obviously goes against the whole idea of drawing the static panel only once) Can someone tell me what's wrong?
For reference only, I use javax swing. Timer recalculates and redraws the change panel 24 times per second
Solution
When you repaint a transparent component over another component, you will still "dirty" the lower component, causing it to be repainted If you do not redraw the lower layer, you will get the trailing effect of the image above it
The only optimization available here is not to regenerate images used at lower levels Every time the above layer changes, you still need to draw the raster to the graphics buffer