首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >多个graphics2d

多个graphics2d
EN

Stack Overflow用户
提问于 2012-09-27 10:12:47
回答 1查看 585关注 0票数 2

好的,我有两个类似的类(图形以相同的方式设置),另一个类显示在底部。如你所见,我想同时显示两个graphics2ds,items类是透明的,并且在顶部( items类几乎什么都没有,而游戏类被图片之类的东西完全覆盖)

有没有办法做到这一点?

目前,items类优先于游戏类,因为它被最后调用,并且完全阻塞了游戏类。

代码语言:javascript
复制
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)
  {
  }
}

}

二班

代码语言:javascript
复制
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();

}
}
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2012-09-27 10:31:07

以下是我的建议:

  • Extend JComponent而不是Canvas (你可能想要一个轻量级的Swing组件,而不是一个重量级的AWT组件)
  • 然后就不用为你的绘图手动提供后台缓冲了- Swing会自动为你做后台缓冲(在这样做的时候可能会使用硬件加速)
  • one component同时绘制两个项目和游戏背景的其余部分。没有好的理由单独做这件事(即使你只改变items图层,背景也需要重新绘制,因为effects)
  • Capitalise Your ClassNames的透明度,看到小写的类名会让我头疼:-)

编辑

通常,方法是使用一个类来表示游戏的可见区域,例如GameScreen,并使用如下的paintCompoent方法:

代码语言:javascript
复制
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
  }  
}
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/12613126

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档