Java抛出异常@Override

时间:2014-04-22 20:36:56

标签: java bluej

我试图创建一个JFrame,将JLabel(图像)添加到JFrame,但是这需要我抛出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);

            }
        });
    }
}

1 个答案:

答案 0 :(得分:1)

您可以"catch" the exception阻止其离开该方法:

try {
   c = ImageIO.read(new File("poker table.jpg"));
} catch(IOException e) {
   e.printStackTrace();
}

如果发生此异常(例如,如果未找到图像文件),printStackTrace()将仅向控制台打印消息。如果没有异常,则跳过catch块。