2015-06-25 75 views
0
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的作品,但繪畫不

+0

他們的起始值我不知道如果我失去了一些東西,但在'paintComponent'方法肯定調用'repaint'會造成無限循環? – rodit

+0

@羅迪特我拿出重漆,但它仍然做同樣的事情。我想到它必須處理Timer和t.start()。 – clopez

回答

0

你在做什麼有幾個問題。

首先,您每次繪製組件時都調用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存儲爲Game類的成員。這意味着當你添加到他們,他們保持添加,直到重置。因此,每一幀,您必須將rxrx2重置爲10.

paintComponent的末尾添加此項。

rx = rx2 = 10; 

這將設置兩個rxrx2回10

+0

謝謝!這解決了我的問題。 – clopez

+0

@clopez很高興能幫到你! – rodit

相關問題