我的应用程序是一个简单的打砖块游戏。为了绘制应用程序的视觉效果,我使用 PaintComponent 方法。该应用程序还有几个使用以下代码添加的按钮:
levelMenu = new JPanel() {
@Override
public void paintComponent(Graphics g) {
super.paintComponent(g);
Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
double scale = screenSize.getHeight()/1080;
Graphics2D g2d = (Graphics2D) g;
g2d.scale(scale, scale);
g2d.drawImage(background, 0, 0, null);
}
};
levelMenu.setLayout(new FlowLayout());
JPanel subPanel = new JPanel(new GridLayout(20, 2, 10, 10));
subPanel.setBackground(Constants.CLEAR);
subPanel.add(new JLabel());
subPanel.add(new JLabel());
for (JButton level: levelList) {
subPanel.add(level);
}
subPanel.add(new JLabel());
subPanel.add(back);
levelMenu.add(subPanel);
this.add(levelMenu);
The issue Im having is that the buttons are being added, but also they seem to be painted in the background image of the application:
右侧的按钮不起作用,只是图像。任何解决此问题的线索。
主要问题归结为...
Graphics2D g2d = (Graphics2D) g;
g2d.scale(scale, scale);
g2d.drawImage(background, 0, 0, null);
The Graphics
上下文传递给paintComponent
方法是共享资源,在绘制通道中渲染的所有组件都将使用它。这意味着您对其所做的任何更改也会影响它们。您应该特别注意转换(例如translate
and scale
).
一般做法是制作状态快照Graphics
使用它之前的上下文,这允许您对副本进行更改并影响原始内容,例如......
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
现在,我强烈建议您停下来阅读一下:
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)