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();
}
}
我想製作一個青蛙遊戲,並且無法創建流量。我能夠讓汽車在街道上移動,但是分隔車道的線路顯示一毫秒,然後在運行程序後消失。街道,河流,開始和結束都顯示出我想要的。我如何讓車道線不消失?ActionListener的作品,但繪畫不
他們的起始值我不知道如果我失去了一些東西,但在'paintComponent'方法肯定調用'repaint'會造成無限循環? – rodit
@羅迪特我拿出重漆,但它仍然做同樣的事情。我想到它必須處理Timer和t.start()。 – clopez