无法弄清楚如何在java中重叠图像

时间:2011-09-26 01:37:37

标签: java swing graphics jframe jpanel

所以我决定把编程作为一种兴趣,现在正在努力创建一个老虎机,并在教程的帮助下完成。但是,我遇到了重叠图像的问题。我使用照片编辑器创建了一个.png文件,我想要成为背景,有三个透明盒子供插槽动画师使用。

绘制背景的代码:

  public class SlotMachineBackground extends JPanel
        {
          private ImageIcon image;

      public void paintComponent (Graphics g)
      {
        super.paintComponent (g);
        image = new ImageIcon ("/Users/Documents/slotmachine.png");
        image.paintIcon (this, g, 0,0);
      }
    }//end class
然后我做了插槽动画师:

public class SlotAnimator extends JPanel implements ActionListener
{
  private Timer animator;
  private ImageIcon imageArray []= new ImageIcon [22];
  int currentFrame = 0;
  int slotNumber = 1;
  int box = 1;
  SlotMachine m = new SlotMachine ();
  String [] mP = m.returnTurn();

  public SlotAnimator (int delay)
  {
    for (int i = 1; i < 22; i += 2)
      imageArray [i] = new ImageIcon ("/Users/Documents/blank.gif");
    for (int i = 0; i < 21; i ++)
    {
      if (i == 0 || i == 8 || i== 12)
        imageArray [i] = new ImageIcon ("/Users/Documents/cherry.gif");
      if ( i == 2 || i == 6 || i == 16)
        imageArray[i] = new ImageIcon ("/Users/Documents/1bar.gif");
      if (i == 4)
        imageArray [i] = new ImageIcon ("/Users/Documents/seven.gif");
      if (i== 10 || i == 14)
        imageArray[i] = new ImageIcon ("/Users/Documents/2bar.gif");
      if (i == 18)
        imageArray[i] = new ImageIcon ("/Users/Documents/3bar.gif");
      if (i==20)
        imageArray [i] = new ImageIcon ("/Users/Documents/jackpot.gif");
    }

    animator = new Timer (delay, this);
    animator.start();

    }

  public void paintComponent (Graphics g)
  {  
    super.paintComponent (g);

    if (currentFrame >= imageArray.length)
    {
      animator.stop();
      ImageIcon im = m.findPicture (mP[box]);
      box++;
      im.paintIcon (this, g, 0, 0);
    }
    imageArray [currentFrame].paintIcon (this, g, 0, 0);
  }

  public void actionPerformed (ActionEvent e)
  {
    repaint();

     currentFrame ++;
  }
}//end class

接下来,我尝试将两者合并为一个JFrame:

public class SlotAnimatorTest 
{
  public static void main (String [] args)
  {
    JFrame frame = new JFrame (); 
    SlotMachineBackground b = new SlotMachineBackground ();


    SlotAnimator a0 = new SlotAnimator (45);
    SlotAnimator a1 = new SlotAnimator (90);
    SlotAnimator a2 = new SlotAnimator (180);


    frame.add (b);
    frame.add(a0);
    frame.setSize (1500,1500);
    frame.setVisible (true);

  }
}

然而,只有动画师出现了。我很难过,因为你可以说我还是个业余爱好者。无论如何,提前感谢您的任何建议!!

1 个答案:

答案 0 :(得分:7)

这主要是布局问题,我建议您阅读有关它们的教程:The Layout Tutorials

在您的情况下,JLayeredPane可能会运行良好。它使用默认的null布局,因此如果您要使用它,则需要指定组件的大小和位置,但您也可以告诉它组件的z顺序,从而能够将老虎机放入最低位置和在较高位置上排名靠前的东西。同样,本教程将帮助您了解详细信息:JLayeredPane Tutorial

另外,你真的不应该在paintComponent方法中读取任何文件,特别是一个不会改变的图像文件 - 每次你重新读取图像的感觉是什么当图像没有改变时重新绘制图像,你可以将它存储在类中的变量中?所以在类的构造函数中读取一次,然后将其保存在变量中。