gpt4 book ai didi

java - 图像观察器不工作

转载 作者:太空宇宙 更新时间:2023-11-04 06:43:45 25 4
gpt4 key购买 nike

有人可以告诉我需要做什么才能让 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);
}
}

当图像处理完成时,您需要重新绘制JPanel,否则图像将不会显示。

关于java - 图像观察器不工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24338073/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com