我试图使用swing引擎在java中制作一个简单的游戏。但是目前我遇到滞后问题。这个简单的代码绘制一个圆圈并将其从框架的左上角移动到右下角,但它滞后很多。虽然我的电脑有点陈旧,i3 4gb内存,我认为应该设法执行此操作而不会滞后?
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.geom.Ellipse2D;
import javax.swing.JFrame;
import javax.swing.JPanel;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
import javax.swing.Timer;
public class Game extends JPanel implements ActionListener {
public Timer timer;
int x = 0;
int y = 0;
public Game() {
timer = new Timer(20, this);
timer.start();
}
@Override
public void paint(Graphics g) {
super.paint(g);
Graphics2D g2d = (Graphics2D) g;
g2d.fillOval(x, y, 15, 15);
}
public void actionPerformed(ActionEvent e) {
x++;
y++;
repaint();
}
public static void main(String[] args) throws InterruptedException {
JFrame frame = new JFrame("test");
Game game = new Game();
frame.add(game);
frame.setSize(600, 600);
frame.setVisible(true);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
}