首页 > 解决方案 > 在 jpanel 上调用 repaint 会导致其子级转移

问题描述

我目前正在开发一款游戏,我有一个带有自定义按钮和 jlabel 的 jpanel,当按下按钮时游戏开始。我试图通过使用paintComponent和paintChildren使该面板淡入计时器动画但是当我调用重绘按钮并且jlabel移到一边时:

https://i.stack.imgur.com/tgEe9.png

这是我的 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();
    }
}

}

标签: javaswingjpanelpaintcomponentrepaint

解决方案


推荐阅读