且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何在JPanel上绘制图像并在其中添加组件

更新时间:2023-09-24 21:46:40

主要问题归结于...

The primary issue comes down to...

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

传递给paintComponent方法的Graphics上下文是共享资源,在绘制过程中呈现的所有组件都将使用它.这意味着您对其进行的任何更改也会影响它们.您应该特别注意转换(例如translatescale).

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).

通常的做法是在使用Graphics上下文状态之前对其进行快照,这使您可以在影响原始文档的情况下对副本进行更改,例如...

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();

另一个问题是subPanel.setBackground(Constants.CLEAR);.我假设这是基于alpha的颜色. Swing组件不支持基于Alpha的颜色,它们是完全不透明的或完全透明的(尽管您可以伪造它).这是通过使用setOpaque

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