【问题标题】:How to load background image properly?如何正确加载背景图片?
【发布时间】:2015-07-31 07:16:54
【问题描述】:

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

 //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);
}

【问题讨论】:

  • 尝试使用ImageIO.read而不是ImageIcon,它会阻塞并且在加载时间之前不会返回并将this作为ImageObserver传递给drawImage。无论如何,您的背景图像有多大?在某处我们可以用作测试的参考?
  • 哦,我会避免使用任何需要缩放图像的方法,这些方法要么运行缓慢,要么产生糟糕的输出。相反,请手动缩放图像,请参阅 this examplethis example 了解更多想法
  • 你为什么改变你上一个问题的图像加载代码:stackoverflow.com/q/31734399/131872?在框架可见之前,我不会启动您的后台线程。再次订购很重要。如果您开始休眠线程,则代码无法执行,这可能会影响图像的加载。
  • @camickr 那是因为即使我非常注意订单,在这种情况下也没有任何区别。

标签: java image swing graphics


【解决方案1】:

要将任何图像渲染到我使用JLabels 的帧上,您可以执行以下操作:

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

this.getContentPane().add(image);

只要父容器的布局是绝对(null)布局,就可以通过image.setBounds()方法调整image的位置。

【讨论】:

    猜你喜欢
    • 2021-06-04
    • 1970-01-01
    • 2017-08-17
    • 2015-08-24
    • 2012-08-14
    • 1970-01-01
    • 2016-12-14
    • 2020-04-27
    相关资源
    最近更新 更多