org.nuiton.jaxx.widgets.error.ErrorDialogUIHandler Maven / Gradle / Ivy
/*
* #%L
* JAXX :: Widgets
* %%
* Copyright (C) 2008 - 2024 Code Lutin, Ultreia.io
* %%
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Lesser Public License for more details.
*
* You should have received a copy of the GNU General Lesser Public
* License along with this program. If not, see
* .
* #L%
*/
package org.nuiton.jaxx.widgets.error;
import org.nuiton.jaxx.runtime.JAXXUtil;
import org.nuiton.jaxx.runtime.swing.SwingUtil;
import javax.swing.InputMap;
import javax.swing.JButton;
import javax.swing.JComponent;
import javax.swing.JFrame;
import javax.swing.JRootPane;
import javax.swing.KeyStroke;
import java.awt.Dialog;
import java.awt.Frame;
import java.io.PrintWriter;
import java.io.StringWriter;
/**
* Handler of ui {@link ErrorDialogUI}.
*
* @author Tony Chemit - [email protected]
* @since 2.0
*/
public class ErrorDialogUIHandler {
protected final ErrorDialogUI ui;
public ErrorDialogUIHandler(ErrorDialogUI ui) {
this.ui = ui;
}
public static void init(Frame frame) {
disposeUI();
ErrorDialogUI.instance = new ErrorDialogUI(frame);
ErrorDialogUI.instance.setModalityType(Dialog.ModalityType.TOOLKIT_MODAL);
}
public static void showError(Exception e) {
ErrorDialogUI instance = ErrorDialogUI.instance;
if (instance == null) {
instance = new ErrorDialogUI();
}
instance.getErrorMessage().setText(e.getMessage());
StringWriter w = new StringWriter();
try (PrintWriter writer = new PrintWriter(w)) {
e.printStackTrace(writer);
instance.getErrorStack().setText(w.toString());
}
instance.getErrorStack().setCaretPosition(0);
instance.pack();
SwingUtil.center(instance.getContextValue(JFrame.class, "parent"), instance);
instance.setVisible(true);
}
public static void disposeUI() {
ErrorDialogUI instance = ErrorDialogUI.instance;
if (instance != null) {
JAXXUtil.destroy(instance);
}
ErrorDialogUI.instance = null;
}
void $afterCompleteSetup() {
JRootPane rootPane = ui.getRootPane();
JButton close = ui.close;
rootPane.setDefaultButton(close);
InputMap inputMap = rootPane.getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW);
inputMap.put(KeyStroke.getKeyStroke("ESCAPE"), "close");
rootPane.getActionMap().put("close", close.getAction());
}
}