java - 在 jpanel 上调用 repaint 会导致其子级转移
问题描述
我目前正在开发一款游戏,我有一个带有自定义按钮和 jlabel 的 jpanel,当按下按钮时游戏开始。我试图通过使用paintComponent和paintChildren使该面板淡入计时器动画但是当我调用重绘按钮并且jlabel移到一边时:
这是我的 jpanel 的代码:
public class PlayAgainScreen extends JPanel implements ActionListener {
private final int UNIT_SIZE;
private final Timer timer;
private int actPer = 0;
public PlayAgainScreen(SnakePanel snakePanel, boolean justLaunched) {
this.UNIT_SIZE = SnakePanel.UNIT_SIZE;
this.setLayout(new GridBagLayout());
GridBagConstraints gbc = new GridBagConstraints();
this.setPreferredSize(new Dimension(UNIT_SIZE * 20, UNIT_SIZE * 15));
this.setBackground(new Color(0, 0, 0, 0));
PlayButton playButton = new PlayButton(snakePanel, justLaunched);
Image image = new ImageIcon(Objects.requireNonNull(getClass().getClassLoader().getResource("snake_logo.png"))).getImage();
image = image.getScaledInstance((int) (this.getPreferredSize().height * 0.5), (int) (this.getPreferredSize().height * 0.5), Image.SCALE_SMOOTH);
JLabel label = new JLabel(new ImageIcon(image));
gbc.insets = new Insets(0, UNIT_SIZE, 0, 0);
gbc.gridx = 0;
gbc.gridy = 0;
this.add(playButton, gbc);
gbc.gridx = 1;
this.add(label, gbc);
timer = new Timer(17, this);
timer.start();
}
@Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
Graphics2D g2D = (Graphics2D) g;
g2D.setColor(new Color(0x543200));
g2D.fillRoundRect(0, 0, this.getWidth(), this.getHeight(), UNIT_SIZE, UNIT_SIZE);
}
@Override
protected void paintChildren(Graphics g) {
super.paintChildren(g);
Graphics2D g2D = (Graphics2D) g;
g2D.setColor(new Color(0, 0, 0, (int) (255 - actPer * 255 / 30F)));
g2D.fillRoundRect(0, 0, this.getWidth(), this.getHeight(), UNIT_SIZE, UNIT_SIZE);
}
@Override
public void actionPerformed(ActionEvent e) {
actPer++;
repaint();
if (actPer == 30) {
timer.stop();
}
}
}
解决方案
推荐阅读
- gstreamer - 如何使用 GStreamer 和 Bellagio 加载专有的 OMX 组件
- css - [react 和 Material-UI]:Appbar(NavBar) 没有选择材质 ui css
- django - 如何创建包含产品和金额的交付模型?
- c# - 防止基于长度的消息帧篡改?
- python - 如何连接列表中的所有数字?
- d3.js - d3中具有不同线条颜色的折线图
- angular - 如何以角度添加我在本地存储中的标头令牌
- node.js - 异步 mongodb 查询的问题
- azure-api-management - Azure API 管理器中的威胁防护和机器人检测策略
- excel - 如何在循环 VBA 中创建 vba 循环?