2017-03-11 46 views
0

我遇到問題,我的JFrame不斷閃爍白色和黑色,但我只將顏色設置爲黑色。我認爲它與while(running){}位有關。JFrame屏幕閃爍白色和黑色

它只是永遠變成白色和黑色,直到我關閉它。我真的不知道發生了什麼事。我只是開始使用JFrame,所以我確信我只是放了一些錯誤的代碼。

public class Game extends Canvas implements Runnable { 

    private static final long serialVersionUID = 1L; 

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

    private Thread thread; 

    private JFrame frame; 

    public Game() { 
     Dimension window = new Dimension(width * scale, height * scale); 
     setPreferredSize(window); 
     frame = new JFrame(); 
    } 

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

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

    public void run() { 
     while (running) { 
      render(); 
     } 
    } 

    public void update() { 

    } 

    public void render() { 
     BufferStrategy buffer = getBufferStrategy(); 

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

     Graphics g = buffer.getDrawGraphics(); 

     g.setColor(Color.BLACK); 
     g.drawRect(0, 0, getWidth(), getHeight()); 

     g.dispose(); 
     buffer.show(); 
    } 

    public static void main(String[] args) { 
     Game game = new Game(); 

     game.frame.setResizable(false); 
     game.frame.setTitle("Game"); 
     game.frame.add(game); 
     game.frame.pack(); 
     game.frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE); 
     game.frame.setLocationRelativeTo(null); 
     game.frame.setVisible(true); 

     game.start(); 
    } 
} 
+0

請在這裏發佈您的代碼。我知道它在鏈接中,但它們是規則。 – byxor

+0

@byxor它說我的帖子主要是代碼,所以我不能這樣做... – GoldShovel

+0

是啊,有一種叫做[MCVE](http://stackoverflow.com/help/mcve)的東西,你應該試着提供。這個「不垃圾郵件代碼」規則有助於提高問題的質量。 – byxor

回答

1

解決它自己...我使用的方法的drawRect()和我閱讀文檔,網頁和它說,它只能繪製矩形的輪廓。所以我只是做的drawRect() 我也改變緩衝區爲2.

對不起,浪費你的時間。