I have the following JavaFX's WebView used in Swing Application.

SimpleSwingBrowser

I wish to detect event when connection to server fail.

engine.getLoadWorker()
    .exceptionProperty()
    .addListener(new ChangeListener<Throwable>() {

        public void changed(ObservableValue<? extends Throwable> o, Throwable old, final Throwable value) {
            if (engine.getLoadWorker().getState() == FAILED) {
                SwingUtilities.invokeLater(new Runnable() {
                    @Override public void run() {
                        JOptionPane.showMessageDialog(
                                panel,
                                (value != null) ?
                                engine.getLocation() + "\n" + value.getMessage() :
                                engine.getLocation() + "\nUnexpected error.",
                                "Loading error...",
                                JOptionPane.ERROR_MESSAGE);
                    }
                });
            }
        }
    });

Strangely. That's won't work even I turn off my internet connection explicitly. engine.getLoadWorker().getState() will always return RUNNING.

Any step I had missed out?

有帮助吗?

解决方案

We should monitor state property instead of exception property.

engine.getLoadWorker().stateProperty().addListener(new ChangeListener<State>() {

    @Override
    public void changed(ObservableValue<? extends State> observable, State oldValue, final State newValue) {
        if (newValue == FAILED) {
            final int result = JOptionPane.showConfirmDialog(
                panel,
                MessagesBundle.getString("error_message_unable_connect_to_internet"),
                MessagesBundle.getString("error_title_unable_connect_to_internet"),
                JOptionPane.YES_NO_OPTION);

            if (result == JOptionPane.YES_OPTION) {
                if (loadedURL != null) {
                    engine.load(loadedURL);
                }
            }
        }
    }
});
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top