1
下面的代碼應該顯示一個紅色的矩形,但事實上它不起作用。但是,如果我取消paint
方法,它的工作;看起來g.drawImage(app.img, 0, 0, f)
在main
方法不起作用。什麼是問題和解決方案?Graphics.drawimage不起作用
import javax.swing.*;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.awt.image.DataBufferByte;
public class LoadImageApp extends Component {
private static final int SCREEN_WIDTH = 400;
private static final int SCREEN_HEIGHT = 300;
BufferedImage img;
// public void paint(Graphics g) {
// g.drawImage(img, 0, 0, null);
// }
public LoadImageApp() {
img = new BufferedImage(SCREEN_WIDTH,
SCREEN_HEIGHT, BufferedImage.TYPE_3BYTE_BGR);
byte[] b = ((DataBufferByte) img.getRaster().getDataBuffer())
.getData();
for (int i = 0; i < img.getWidth() * img.getHeight(); i++) {
b[i * 3] = 0;
b[i * 3 + 1] = 0;
b[i * 3 + 2] = (byte)0xff;
}
}
public Dimension getPreferredSize() {
if (img == null) {
return new Dimension(100, 100);
} else {
return new Dimension(img.getWidth(null), img.getHeight(null));
}
}
public static void main(String[] args) {
JFrame f = new JFrame("Load Image Sample");
f.setDefaultCloseOperation(WindowConstants.DISPOSE_ON_CLOSE);
LoadImageApp app = new LoadImageApp();
f.add(app);
f.pack();
f.setVisible(true);
Graphics g = app.getGraphics();
g.drawImage(app.img, 0, 0, f);
}
}