2012-09-27 128 views
2

好的,我有兩個類似的像這樣(圖形設置方式相同)和另一個顯示在底部的類。你可以看到我有兩個graphics2ds,我想同時顯示物品類是透明的和頂部的(物品類幾乎沒有任何東西,遊戲類完全覆蓋有圖片等)multiple graphics2d

有沒有辦法做到這一點?

當前物品類優先考慮遊戲類,因爲它被稱爲最後並完全阻止遊戲類。

public class game extends Canvas implements Runnable 
{ 

public game() 
{ 
    //stuff here 


    setBackground(Color.white); 
    setVisible(true); 

    new Thread(this).start(); 
    addKeyListener(this); 
} 

public void update(Graphics window) 
{ 
    paint(window); 
} 

public void paint(Graphics window) 
{ 
    Graphics2D twoDGraph = (Graphics2D)window; 

    if(back==null) 
     back = (BufferedImage)(createImage(getWidth(),getHeight())); 

    Graphics graphToBack = back.createGraphics(); 

//draw stuff here 

    twoDGraph.drawImage(back, null, 0, 0); 
} 


public void run() 
{  
try 
{ 

while(true) 
    { 
     Thread.currentThread(); 
     Thread.sleep(8); 
     repaint(); 
    } 
    }catch(Exception e) 
    { 
    } 
} 

} 

二類

public class secondary extends JFrame 
{ 
private static final int WIDTH = 800; 
private static final int HEIGHT = 600; 

public secondary() 
{ 
    super("Test RPG"); 
    setSize(WIDTH,HEIGHT); 

    game game = new game(); 
    items items = new items(); 

    ((Component)game).setFocusable(true); 
    ((Component)items).setFocusable(true); 
    getContentPane().add(game); 
    getContentPane().add(items); 

    setVisible(true); 
    setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); 
} 

public static void main(String args[]) 
{ 
    secondary run = new secondary(); 

} 
} 

回答

1

這裏是我的建議:

  • JComponent的子類,而不是帆布(你可能要一個輕量級的Swing組件而不是一個重量級AWT一個)
  • 然後不用擔心手動後緩衝爲您的繪圖 - 擺動確實爲您自動緩衝(並可能會使用硬件加速,而這樣做)
  • 一個組件繪製兩個項目和其餘的遊戲背景。沒有很好的理由分開做(即使你只改變了項目層,由於透明效果,背景需要重畫)
  • 大寫你的班級名稱,看到小寫的班級會讓我頭疼名字:-)

編輯

通常的做法是有一個代表遊戲如的可見區域類GameScreen,使用paintCompoent方法如下:

public class GameScreen extends JComponent { 
    .... 

    public void paintComponent(Graphics g) { 
    drawBackground(g); 
    drawItems(g); 
    drawOtherStuff(g); // e.g. animated explosions etc. on top of everything else 
    } 
} 
+0

我會在二級課堂上畫這個嗎?你會怎麼做?你建議什麼組件? – googleman2200

+0

我建議寫一個類似'GameScreen extends JComponent'的類。 GameScreen爲遊戲地圖和其上的任何項目執行所有繪圖。二級課程例如'MainFrame擴展JFrame'沒有繪圖,它只是作爲GameScreen的容器(以及後來可能添加的任何其他UI組件,例如菜單,狀態欄等等) – mikera

+0

所以我可以做類似如下的東西:gameScreen x = new gameScreen(); x.draw(somemap);在遊戲類和項目中做gameScreen i = new gameScreen(); i.draw(someitem);並且在gameScreen類中有一個繪製方法? – googleman2200