所以我从来没有使用过 Swing Worker,但我听说这是一种加载图像的好方法,因为它允许在后台处理我认为的图像。在尝试实现它的过程中,我遇到了图像未绘制的问题。我没有任何错误,但屏幕似乎是白色的。谁能看看我的代码并告诉我哪里出错了?
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.Image;
import java.awt.Toolkit;
import java.io.IOException;
import java.net.URL;
import javax.imageio.ImageIO;
import javax.swing.Icon;
import javax.swing.ImageIcon;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.SwingWorker;
public class Screen extends JPanel{
//Screen Vairables
public static JFrame frame = new JFrame("Soul Voyage");
public Dimension size = new Dimension((int)Toolkit.getDefaultToolkit().getScreenSize().width,(int)Toolkit.getDefaultToolkit().getScreenSize().height);
Graphics draw;
public Screen(){
//Screen Creation
frame.setSize(size);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setResizable(false);
frame.setVisible(true);
//Other
}
@Override
public void paintComponent(Graphics g){
draw = g;
super.paintComponent(g);
new ImageLoader().execute();
g.dispose();
}
public static void main(String[] args) {
Screen s = new Screen();
frame.add(s);
}
class ImageLoader extends SwingWorker{
private ImageIcon image;
@Override
protected Icon doInBackground() throws IOException {
Image picture = ImageIO.read(new URL("Background.jpg"));
image = new ImageIcon(picture);
image.paintIcon(frame, draw, size.width, size.height);
return image;
}
}
}