如何正确加载背景图像?

时间:2015-07-31 07:16:54

标签: java image swing graphics

我正在创建一个游戏,我的背景图像在我的框架后加载而不是它。我不想这样,请我帮忙。 主要问题是当我运行程序时,我的背景图像需要一点时间才会出现,我真的希望它同时加载框架。

 //constructor of class that extends JFrame 
    public mousework2(){
      super("shoot-em-up");
     //p1 is a JPanel
      p1=new CreateImage();
      this.add(p1);
      ImageIcon img=new ImageIcon("ballfall3.jpg");
      Image minImage=img.getImage();
      this.setIconImage(minImage);
      this.getContentPane();
      Thread t= new recMove(this);
       t.start();
      this.setSize(Width,Height);
      this.setResizable(true);
      this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
      this.requestFocus(true);
      this.setVisible(true);
     }



    //the thread class
    class recMove extends Thread{
         JFrame b;
        public boolean running=true;
        //public boolean gameover=false;
          public recMove(JFrame b){
             this.b=b;
      }

          public void run(){
         while(running){
           b.repaint();
           try{
            Thread.sleep(100);
          }
         catch(InterruptedException e){}
          }

       }
    }
class CreateImage extends JPanel implements MouseListener{
//constructor
 public CreateImage(){
         super(true);
      //Background image
      ImageIcon pic=new ImageIcon("ballfall3.jpg");
      //pixMage is a gloal variable in the outer class of type Image 
      pixMage=pic.getImage();
       MediaTracker tracker = new MediaTracker(this);
            tracker.addImage(pixMage,0);
            try {
              tracker.waitForID(0);
            }
            catch (InterruptedException e)
            {}

      pixMage=pixMage.getScaledInstance(200,-1,Image.SCALE_DEFAULT);
  }
   public void paintComponent(Graphics g){
           super.paintComponent(g);
         g.drawImage(pixMage,0,0,Width,Height,null);
}

1 个答案:

答案 0 :(得分:0)

要将任何图像渲染到框架上我使用JLabel s,您可以执行以下操作:

ImageIcon pic = new ImageIcon("ballfall3.jpg");
JLabel image = new JLabel(pic);

this.getContentPane().add(image);

如果父容器的布局是绝对(null)布局,则可以通过使用方法image来调整image.setBounds()的位置。