有人可以告诉我要使ImageObserver工作需要做什么。我以为这样可以。我希望它在加载图像时打印一条消息,但它不...我在做什么错?这可能很容易回答。

import java.awt.Graphics;
import java.awt.Image;
import java.awt.image.BufferedImage;
import java.awt.image.ImageObserver;
import java.io.File;
import java.io.IOException;

import javax.imageio.ImageIO;
import javax.swing.JFrame;
import javax.swing.JPanel;


public class ImageTest extends JPanel implements ImageObserver {

    @Override
    public boolean imageUpdate(Image img, int infoflags, int x, int y,
            int width, int height) {
        if((infoflags & ALLBITS) == 0) {
            System.out.println("Processing still");
            return true;
        } else {
            System.out.println("Done processing");
            return false;
        }
    }

    public void paintComponent(Graphics g) {
        super.paintComponent(g);
        g.drawImage(img, 0, 0, this);
    }

    BufferedImage img;

    public ImageTest (){
        try {
            img = ImageIO.read(new File("res/soccer-ball.jpg"));
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }

    public static void main(String args[]) {
        JFrame f = new JFrame();
        f.setContentPane(new ImageTest());
        f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        f.setSize(1000, 1000);
        f.setVisible(true);
    }
}

最佳答案

无需将其放置在drawImage中,只需使用ToolKit来处理图像,您将在其中使用ImageObserver的实例准备图像

改变这个:

try {
        img = ImageIO.read(new File("res/soccer-ball.jpg"));
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }


至:

public class ImageTest extends JPanel implements ImageObserver {

@Override
public boolean imageUpdate(Image img, int infoflags, int x, int y,
        int width, int height) {
    if((infoflags & ALLBITS) == 0) {
        System.out.println("Processing still");
        return true;
    } else {
        System.out.println("Done processing");
        repaint();
        return false;
    }
}

public void paintComponent(Graphics g) {
    super.paintComponent(g);
    g.drawImage(img, 0, 0, this);
}

Image img;

public ImageTest (){
    Toolkit toolkit = Toolkit.getDefaultToolkit();
    img =  toolkit.getImage("res/soccer-ball.jpg");
    toolkit.prepareImage(img, -1, -1, this);
}

public static void main(String args[]) {
    JFrame f = new JFrame();
    f.setContentPane(new ImageTest());
    f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    f.setSize(1000, 1000);
    f.setVisible(true);
}
}


图像完成处理后,您需要在repaint JPanel的位置显示,否则图像将不会显示。

07-24 19:01