我正在尝试创建一个 JFrame,向 JFrame 添加一个 JLabel(image),但这需要我抛出 IOException,这会弄乱我的 main 方法中的 run() 。
谁能告诉我如何抛出异常或以其他方式如何仍然使用我的 run 方法来启动?
public class Swing extends JFrame {
Swing ex;
BufferedImage c;
ImageIcon image;
public Swing() throws IOException {
c = ImageIO.read(new File("poker table.jpg"));
image = new ImageIcon(c);
this.c = c;
initUI();
setTitle("MyApplication");
setSize(1370, 770);
setLocationRelativeTo(null);
setDefaultCloseOperation(EXIT_ON_CLOSE);
}
public void initUI() {
JLabel label = new JLabel(new ImageIcon(c));
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
Swing ex = new Swing();
ex.setVisible(true);
}
});
}
}
最佳答案
您可以"catch" the exception防止它离开该方法:
try {
c = ImageIO.read(new File("poker table.jpg"));
} catch(IOException e) {
e.printStackTrace();
}
如果确实发生此异常(例如,如果未找到图像文件),则 printStackTrace()
将仅向控制台打印一条消息。如果没有异常,则跳过 catch
block 。
关于Java抛出异常@Override,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23229685/