문제

i'm trying to create a JFrame, add a JLabel(image) to the JFrame, however this requires me to throw IOException, wich messes up my run() in my main method.

could anyone tell me how I could throw an exception or another way how I can still use my run method to start things up?

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);

            }
        });
    }
}
도움이 되었습니까?

해결책

You can "catch" the exception to keep it from leaving that method:

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

Here the printStackTrace() will just print a message to the console if this exception does happen (for example, if the image file is not found). If there is no exception, the catch block is skipped.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top