How to paint an image over the JPanel and add components in it

后端 未结 2 1439
佛祖请我去吃肉
佛祖请我去吃肉 2021-01-26 19:52

My application is a simple game of Brick Breaker. In order to paint the visuals of the application I\'m using the paintComponent method. The application also has several buttons

2条回答
  •  梦毁少年i
    2021-01-26 20:54

    The primary issue comes down to...

    Graphics2D g2d = (Graphics2D) g;
    g2d.scale(scale, scale);
    g2d.drawImage(background, 0, 0, null);
    

    The Graphics context passed to the paintComponent method is a shared resource, all the components rendered within the paint pass will use it. This means that any changes you make to it will also affect them. You should be especially aware of transformations (like translate and scale).

    A general practice is to make a snapshot of the state of Graphics context before you use it, this allows you to make changes to the copy with affecting the original, something like...

    Graphics2D g2d = (Graphics2D) g.create();
    g2d.scale(scale, scale);
    g2d.drawImage(background, 0, 0, null);
    g2d.dispose();
    

    The other issue is subPanel.setBackground(Constants.CLEAR);. I'm assuming that this is a alpha based color. Swing component's don't support alpha based colors, they are either fully opaque or fully transparent (although you can fake it). This is controlled through the use of setOpaque

    Now, I strongly recommend that you stop and go have a read through:

    • Performing Custom Painting
    • Painting in AWT and Swing

提交回复
热议问题