2016-12-10 85 views
0

每當我嘗試渲染圖形到我的JFrame時,它都不想顯示在JFrame上。圖形不會渲染爲JFrame

下面是渲染方法:

public void render(){ 
     BufferStrategy bs = this.getBufferStrategy(); 
     if(bs == null){ 
      this.createBufferStrategy(3); 
      return; 
     } 

     g = bs.getDrawGraphics(); 
     g.setColor(Color.RED); 
     g.fillRect(0, 0, 1000, 600); 

     g.dispose(); 
     bs.show(); 

} 

這是全班同學:

package FrameWork; 

import java.awt.Canvas; 
import java.awt.Color; 
import java.awt.Graphics; 
import java.awt.image.BufferStrategy; 

public class Battle extends Canvas implements Runnable{ 

boolean running = false; 
Thread thread; 
Window gameWindow; 
Handler handler= new Handler(); 
    public Graphics g; 
    private GameObject p, e; 
    private BattleWindow BattleWindow; 

    public Battle(GameObject Player, GameObject Enemy){ 
     p = Player; 
     e = Enemy; 

     BattleWindow = new BattleWindow(1000, 600, "Battle", p, e, this); 

    } 

public void init(){ 
     handler.addObject(e); 
     handler.object.add(p); 
     this.addKeyListener(new KeyInputBattle(handler)); 

} 

public void createLevel(){ 

} 

public synchronized void start(){ 
     if(running) 
      return; 

     running = true; 
     createLevel(); 
     thread = new Thread(this); 
    thread.start(); 
} 


@Override 
public void run() { 
     init(); 
     this.requestFocus(); 
     long lastTime = System.nanoTime(); 
     double amountOfTicks = 60.0; 
     double ns = 1000000000/amountOfTicks; 
     double delta = 0; 
     long timer = System.currentTimeMillis(); 
     int updates = 0; 
     int frames = 0; 
     while(running){ 
      long now = System.nanoTime(); 
      delta += (now - lastTime)/ns; 
      lastTime = now; 
      while(delta >= 1){ 
       tick(); 
       updates++; 
       delta--; 
      } 
      render(); 
      frames++; 

      if(System.currentTimeMillis() - timer > 1000){ 
       timer += 1000; 
       System.out.println("BATTLE - FPS: " + frames + " TICKS: " + updates); 
       frames = 0; 
       updates = 0; 
      } 
     } 
} 

public void tick(){ 
     handler.tick(); 
} 

public void render(){ 
     BufferStrategy bs = this.getBufferStrategy(); 
     if(bs == null){ 
      this.createBufferStrategy(3); 
      return; 
     } 

     g = bs.getDrawGraphics(); 
     g.setColor(Color.RED); 
     g.fillRect(0, 0, 1000, 600); 

     g.dispose(); 
     bs.show(); 

} 

    public void dispose(){ 
     running = false; 
    } 

} 
+0

您粘貼的代碼不會生成。請提供一個完整的示例。 –

+0

圖形應呈現給JPanel,而不是JFrame。 –

回答

0

你的代碼中包含很多錯誤,並不感到驚訝它不工作。這是什麼?

BattleWindow = new BattleWindow(1000, 600, "Battle", p, e, this); 

當你創建一個類的實例,你必須給它一個名字:

BattleWindow bw = new BattleWindow(1000, 600, "Battle", p, e, this); 

嘗試看看基本語法和java的規則,並試圖重申你的代碼。

+0

我知道我只是使用了錯誤的命名約定。我有一個對象戰鬥窗口,並命名我的變量BattleWindow。但更改名稱並不能解決問題。 – benbylife

+0

不,它不會',但你應該再看看你的代碼並清理它。 – Erninger

+0

好吧,我仍然需要一個解決方案... – benbylife