2012-09-27 73 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