我正在学习Java,并且已经使用File
将Image
类型转换为IOException
,但是如何在{{1 }}?
Image
因为现在IntelliJ无法识别图像。
答案 0 :(得分:2)
在这种情况下-因为paintComponent
会经常被调用,并且您只想加载一次图像,请将图像放入字段中。
private Image image;
...() {
try {
File obraz = new File("C:\\Users\\ender\\Pictures\\logo.jpg");
image = ImageIO.read(obraz);
} catch (IOException ex) {
ex.printStackTrace();
}
}
...() throws IOException {
File obraz = new File("C:\\Users\\ender\\Pictures\\logo.jpg");
image = ImageIO.read(obraz);
}
@Override
public void paintComponent(Graphics g){
Graphics2D g2 = (Graphics2D) g;
if (image != null) {
g2.drawImage(image);
}
}
我展示了两种解决方案:
惯例是使用@Override
,因为这样会捕获public void paintComponent(Graphics2D g)
或public void painComponent(Graphics g)
等错字。