ActionListener 有效但绘画无效

ActionListener works but painting doesn't

import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;


public class Game extends JComponent implements ActionListener {
    Timer t = new Timer(5, this);
    int wx;
    int rx = 10;
    int rx2 = 10;
    int carx = 10;
    int velX = 2;

    public static void main(String[] args) {
        JFrame window = new JFrame("Frogger");
        window.add(new Game());
        window.pack();
        window.setSize(800, 600);
        window.setLocationRelativeTo(null);
        window.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
        window.setVisible(true);


    }
    public void actionPerformed(ActionEvent e){
        carx+=velX;
        repaint();
    }


    @Override
    protected void paintComponent(Graphics g) {
        super.paintComponent(g);
        repaint();
        g.setColor(new Color(173, 216, 230));
        g.fillRect(0, 0, 800, 600); //background
        g.setColor(Color.lightGray);
        g.fillRect(0, 525, 800, 75); //start
        g.fillRect(0, 0, 800, 30); //end
        g.setColor(Color.black);
        g.fillRect(0, 275, 800, 250); //street
        g.setColor(Color.white);
        for (int n = 0; n < 16; n++) {
            g.fillRect(rx, 450, 20, 10);
            rx += 50;
        }
        for (int n = 0; n < 16; n++) {
            g.fillRect(rx2, 375, 20, 10);
            rx2 += 50;
        }
        g.fillRect(carx, 477, 60, 30);
        t.start();

    }

}

我正在尝试制作 Frogger 游戏,但在创建流量时遇到了问题。我能够让汽车穿过街道,但分隔车道的线会显示一毫秒,然后在我 运行 程序后消失。街道、河流、起点和终点都按照我的意愿出现。如何让车道线不消失?

您的操作存在一些问题。

首先,您在每次绘制组件时调用 t.start()。这是不必要的。不要这样做,而是创建一个布尔值来确定它是否是第一帧,然后启动它。执行此操作的方法如下:

boolean firstFrame = true;

@Override
public void paintComponent(Graphics g){
    super.paintComponent(g);
    if(firstFrame){
        t.start();
        firstFrame = false;
    }
    //rest of render code...
}

现在回答你如何阻止线条消失的问题。您似乎将整数 rxrx2 存储为游戏 class 的成员。这意味着当您添加到它们时,它们会保持添加状态直到重置。因此,每一帧,您必须将 rxrx2 重置为 10.

paintComponent的末尾添加这个。

rx = rx2 = 10;

这会将 rxrx2 都设置回它们的起始值 10。