2014-02-16 80 views
0

我正在關注YouTube上的Java遊戲編程系列,並且在我們向該程序添加一些代碼之前,所有這些都一直進展順利。爲程序的代碼是:運行此代碼時系統凍結

package com.fagyapong.rain; 

import javax.swing.*; 
import java.awt.*; 
import java.awt.image.*; 

public class Game extends Canvas implements Runnable{ 
    private static final long serialVersionUID = -247215114548172830L; 

    public static int width = 300; 
    public static int height = width/16 * 9; 
    public static int scale = 3; 

    private JFrame frame; 
    public Thread thread; 
    private boolean running = false; 

    public Game() { 

     // Setup Game window 
     Dimension size = new Dimension(width * scale, height * scale); 
     setPreferredSize(size); 

     frame = new JFrame(); 
    } 

    public synchronized void start() { 
     running = true; 
     thread = new Thread(this, "Display"); 
     thread.start(); 
    } 

    public synchronized void stop() { 

     running = false; 
     try { 
      thread.join(); 
     } 
     catch (InterruptedException e) { 
      e.printStackTrace(); 
     } 
    } 

    public void run() { 

     while (running) { 
      update(); 
      render(); 
     } 
    } 

    public void update() { 

    } 

    public void render() { 

     // Get the canvas' BufferStragy object 
     BufferStrategy bs = getBufferStrategy(); 

     if (bs == null) { 
      createBufferStrategy(3); 
      return; 
     } 

     Graphics g = bs.getDrawGraphics(); 

     g.setColor(Color.GRAY); 
     g.fillRect(0, 0, getWidth(), getHeight()); 
     g.dispose(); 
     bs.show(); 
    } 

    public static void main(String[] args) { 

     Game game = new Game(); 
     game.frame.setResizable(false); 
     game.frame.setTitle("Rain"); 
     game.frame.add(game); 
     game.frame.pack(); 
     game.frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); 
     game.frame.setLocationRelativeTo(null); 
     game.frame.setVisible(true); 

     game.start(); 
    } 
} 

下面是使所述系統凍結碼(已經在上面的代碼註釋)

Graphics g = bs.getDrawGraphics(); 

g.setColor(Color.GRAY); 
g.fillRect(0, 0, getWidth(), getHeight()); 
g.dispose(); 
bs.show(); 
+0

它不凍結我的系統。你究竟發生了什麼? –

+0

該程序運行並顯示一個窗口,但系統後來變得沒有響應 – Francis

+0

它是否達到峯值內存使用率? – jpaugh

回答

0

好的,我想出問題一點。我遇到了同樣的問題。對我來說問題是三重緩衝。相反,將代碼設置爲:

createBufferStrategy(2); 

這樣它只是雙緩衝。我沒有一臺夢幻般的電腦,所以我不得不將它設置爲1而不是2。那時,我的猜測是它根本就沒有緩衝。這是我讓它工作的方式。