Java 如何绘制在try/catch中创建的图像?
我正在学习Java,我已经使用Java 如何绘制在try/catch中创建的图像?,java,intellij-idea,try-catch,awt,Java,Intellij Idea,Try Catch,Awt,我正在学习Java,我已经使用IOException将文件类型转换为图像,但是如何在try/catch之外使用新的图像 试试看{ File obraz=新文件(“C:\\Users\\ender\\Pictures\\logo.jpg”); 图像=图像读取(obraz); }捕获(IOEX异常){ 例如printStackTrace(); } } 公共组件(图形g){ 图形2d g2=(图形2d)g; g2.绘图图像(图像); } 因为现在IntelliJ无法识别图像。在这种情况下-由于将经常
IOException
将文件
类型转换为图像
,但是如何在try/catch
之外使用新的图像
试试看{
File obraz=新文件(“C:\\Users\\ender\\Pictures\\logo.jpg”);
图像=图像读取(obraz);
}捕获(IOEX异常){
例如printStackTrace();
}
}
公共组件(图形g){
图形2d g2=(图形2d)g;
g2.绘图图像(图像);
}
因为现在IntelliJ无法识别图像。在这种情况下-由于将经常调用
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);
}
}
我展示了两种解决方案:
- 现在捕获异常:但是应该做一些事情,向用户提供一条错误消息,说明logo.jpg文件不存在
- 通过抛出来传递异常,通常是更好的解决方案
惯例是使用
@Override
,因为这样可以捕获诸如public void paintComponent(Graphics2D g)
或public void paintComponent(Graphics g)
之类的打字错误。在这种情况下,会经常调用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);
}
}
我展示了两种解决方案:
- 现在捕获异常:但是应该做一些事情,向用户提供一条错误消息,说明logo.jpg文件不存在
- 通过抛出来传递异常,通常是更好的解决方案
惯例是使用
@Override
,因为这样可以捕捉到诸如公共void paintComponent(Graphics2D g)
或公共void paintComponent(Graphics g)
谢谢,我真的很感激谢谢,我真的很感激