Multi-layer jframe

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 will not change), so I make the 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);
}

This piece of code gives me the correct image that I want, but every time I redraw changingPanel, it staticPanelalso repaints (which clearly contradicts the whole idea of ​​drawing a static panel only once). Can someone show me what happened?

FYI I use javax.swing.Timer to recount and redraw the shift panel 24 times per second.

+3
3

, "" , . , .

, , , . .

+7

, . Swing . , , .

, SWING "" compnent, , , .

, . , .

+3

A very easy way is to use jxlayer . Contribute AbstractLayerUI and add this over your component. See here to get started.

+2
source

Source: https://habr.com/ru/post/1742396/


All Articles