Package com.nexirius.framework.application

Source Code of com.nexirius.framework.application.DialogManager$PopupRunnable

//{HEADER
/**
* This class is part of jnex 'Nexirius Application Framework for Java'
*
* Copyright (C) Nexirius GmbH, CH-4450 Sissach, Switzerland (www.nexirius.ch)
*
* <p>This library is free software; you can redistribute it and/or<br>
* modify it under the terms of the GNU Lesser General Public<br>
* License as published by the Free Software Foundation; either<br>
* version 2.1 of the License, or (at your option) any later version.</p>
*
* <p>This library is distributed in the hope that it will be useful,<br>
* but WITHOUT ANY WARRANTY; without even the implied warranty of<br>
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU<br>
* Lesser General Public License for more details.</p>
*
* <p>You should have received a copy of the GNU Lesser General Public<br>
* License along with this library; if not, write to the Free Software<br>
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA</p>
* </blockquote>
*
* <p>
* Nexirius GmbH, hereby disclaims all copyright interest in<br>
* the library jnex' 'Nexirius Application Framework for Java' written<br>
* by Marcel Baumann.</p>
*/
//}HEADER
package com.nexirius.framework.application;

import com.nexirius.framework.dataeditor.PopupEditorAdaptor;
import com.nexirius.framework.gadgets.ErrorAdaptor;
import com.nexirius.framework.swing.JnexFileChooser;
import com.nexirius.framework.datamodel.ArrayModel;
import com.nexirius.framework.datamodel.DataModelEnumeration;
import com.nexirius.framework.dataviewer.ViewerFactory;

import javax.swing.*;
import java.awt.*;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
import java.lang.ref.SoftReference;
import java.lang.reflect.Method;
import java.lang.reflect.InvocationTargetException;
import java.text.MessageFormat;
import java.util.Hashtable;
import java.util.Enumeration;

public class DialogManager {
    static PopupEditorAdaptor popupEditorAdaptor;
    static AskAdaptor askAdaptor;
    static ErrorAdaptor errorAdaptor;
    static ProgressAdaptor progressAdaptor;
    static int errorWindowCount = 0;
    static JFileChooser chooser;
    static Hashtable dialogProperties = new Hashtable();
    private static JFrame applicationFrame;

    public static ArrayModel getDialogPropertiesModels() {
        ArrayModel array = new ArrayModel(new DialogPropertiesModel(), "DialogPropertyArray");
        Enumeration en = dialogProperties.keys();

        while (en.hasMoreElements()) {
            DialogPropertiesModel dialogPropertiesModel = (DialogPropertiesModel) dialogProperties.get(en.nextElement());

            dialogPropertiesModel.setParentDataModelContainer(null);
            array.append(dialogPropertiesModel);
        }

        return array;
    }

    public static void setDialogPropertiesModels(ArrayModel array) {
        DataModelEnumeration en = array.getEnumeration();

        while (en.hasMore()) {
            DialogPropertiesModel dialogPropertiesModel = (DialogPropertiesModel) en.next();
            dialogProperties.put(dialogPropertiesModel.getName(), dialogPropertiesModel);
        }
    }

    public static void setPopupEditorAdaptor(PopupEditorAdaptor ea) {
        popupEditorAdaptor = ea;
    }

    public static PopupEditorAdaptor getPopupEditorAdaptor() {
        return popupEditorAdaptor;
    }

    public static void setAskAdaptor(AskAdaptor aa) {
        askAdaptor = aa;
    }

    public static void setProgressAdaptor(ProgressAdaptor pa) {
        progressAdaptor = pa;
    }

    public static ProgressAdaptor getProgressAdaptor() {
        return progressAdaptor;
    }

    public static AskAdaptor getAskAdaptor() {
        return askAdaptor;
    }

    public static void setErrorAdaptor(ErrorAdaptor ea) {
        errorAdaptor = ea;
    }

    public static ErrorAdaptor getErrorAdaptor() {
        if (errorAdaptor == null) {
            errorAdaptor = new DefaultErrorAdaptor();
        }

        return errorAdaptor;
    }

    public static void error(Throwable ex) {
        String message = ex.getMessage();

        if (message == null) {
            message = ex.toString();
        }

        if (ex instanceof ErrorMessageException) {
            ErrorMessageException errorMessageException = (ErrorMessageException) ex;
            String cause = "";

            if (errorMessageException.getCause() != null) {
                cause = " (" + errorMessageException.getCause().toString() + ")";
            }
            error(ViewerFactory.getInstance().getText(message) + cause, errorMessageException.getAttributes());
        } else {
            error(message, (Object[]) null);
        }

        ex.printStackTrace();
    }

    public static void error(String message) {
        error(message, (Object[]) null);
    }

    public static void error(String message, Object param[]) {
        SwingUtilities.invokeLater(new ErrorRunnable(getErrorAdaptor(), message, param, true));
    }

    public static void error(String message, Object param1) {
        Object param[] = new Object[1];

        param[0] = param1;

        error(message, param);
    }

    public static void warning(String message) {
        warning(message, null);
    }

    public static void warning(String message, Object param[]) {
        SwingUtilities.invokeLater(new ErrorRunnable(getErrorAdaptor(), message, param, false));
    }

    public static JFrame getApplicationFrame() {
        return applicationFrame;
    }

    public static void setApplicationFrame(JFrame mainFrame) {
        DialogManager.applicationFrame = mainFrame;
    }

    static class ErrorRunnable implements Runnable {
        ErrorAdaptor errorAdaptor;
        String message;
        Object[] param;
        boolean isError;

        public ErrorRunnable(ErrorAdaptor errorAdaptor, String message, Object[] param, boolean isError) {
            this.errorAdaptor = errorAdaptor;
            this.message = message;
            this.param = param;
            this.isError = isError;
        }

        public void run() {
            if (isError) {
                errorAdaptor.error(message, param);
            } else {
                errorAdaptor.warning(message, param);
            }
        }
    }

    public static boolean ask(String question, String answerYes, String answerNo, boolean defaultIsYes) {
        return askAdaptor.ask(question, answerYes, answerNo, defaultIsYes);
    }

    /**
     * Modal window
     * @param question
     * @param answerYes
     * @param answerNo
     * @param defaultIsYes
     * @param hasCancel if true, throws RuntimeException on Cancel
     */
    public static boolean ask(String question, String answerYes, String answerNo, boolean defaultIsYes, boolean hasCancel, Object[] parameters) {
        return askAdaptor.ask(question, answerYes, answerNo, defaultIsYes, hasCancel, parameters);
    }

    /**
     * Throws RuntimeException on Cancel
     *
     * @param question
     * @param answerYes
     * @param answerNo
     * @param defaultIsYes
     * @param hasCancel
     */
    public static boolean ask(String question, String answerYes, String answerNo, boolean defaultIsYes, boolean hasCancel) {
        return askAdaptor.ask(question, answerYes, answerNo, defaultIsYes, hasCancel);
    }

    public static void setDefaultCursor(Component c) {
//    c.setEnabled(true);

        if (c == null) {

            c = getToplevelFrame();
        }

        if (c != null) {
            c.setCursor(Cursor.getDefaultCursor());
        }

    }

    /**
     * set the components cursor (hourglass)
     *
     * @param c null (for toplevelFrame) or the component which changes its cursor
     * @return the component which has changed its cursor
     */
    public static Component setWaitCursor(Component c) {
        if (c == null) {

            c = getToplevelFrame();
        }

        if (c != null) {
            c.setCursor(Cursor.getPredefinedCursor(Cursor.WAIT_CURSOR));
        }


        return c;
    }

    public static void showError() {
        ++errorWindowCount;
    }

    public static void hideError() {
        --errorWindowCount;

        if (errorWindowCount < 0) {
            new Exception("ErrorWindowCount < 0").printStackTrace();
            errorWindowCount = 0;
        }
    }

    public static boolean hasErrorWindow() {
        return errorWindowCount > 0;
    }

    public static JDialog createJDialog(String title, boolean modal, String dialogPropertiesName) {
        JDialog ret = createJDialog(title, modal);
        ret.setName(dialogPropertiesName);

        DialogPropertiesModel dialogPropertiesModel = getDialogProperties(dialogPropertiesName);

        if (dialogPropertiesModel == null) {
            Rectangle bounds = ret.getBounds();
            createDialogProperties(dialogPropertiesName, bounds);
        } else {
            dialogPropertiesModel.apply(ret);
        }

        return ret;
    }

    public static DialogPropertiesModel getDialogProperties(String dialogPropertiesName) {
        return (DialogPropertiesModel) dialogProperties.get(dialogPropertiesName);
    }

    public static void createDialogProperties(String dialogPropertiesName, Rectangle bounds) {
        DialogPropertiesModel dialogPropertiesModel;
        dialogPropertiesModel = new DialogPropertiesModel(dialogPropertiesName, bounds);
        dialogProperties.put(dialogPropertiesName, dialogPropertiesModel);
    }

    public static boolean saveDialogProperties(JDialog dialog) {
        String dialogPropertiesName = dialog.getName();

        if (dialogPropertiesName == null || dialogPropertiesName.startsWith("dialog")) {
            return false;
        }

        DialogPropertiesModel dialogPropertiesModel = new DialogPropertiesModel(dialogPropertiesName, dialog.getBounds());
        dialogProperties.put(dialogPropertiesName, dialogPropertiesModel);

        return true;
    }

    public static boolean applyDialogProperties(JDialog dialog) {
        String dialogPropertiesName = dialog.getName();

        if (dialogPropertiesName == null || dialogPropertiesName.startsWith("dialog")) {
            return false;
        }

        DialogPropertiesModel dialogPropertiesModel = getDialogProperties(dialogPropertiesName);

        if (dialogPropertiesModel != null) {
            return dialogPropertiesModel.apply(dialog);
        }

        return false;
    }

    /**
     * create a new JDialog window which is based on the current toplevelFrame
     */
    public static JDialog createJDialog(String title, boolean modal) {
        JDialog ret;
        Component parentFrame;
        if (modal) {
            parentFrame = getToplevelFrame();
        } else {
            parentFrame = applicationFrame;

            /**
             * avoid problem with modal dialogs which start a non modal dialog
             */
            if (getToplevelFrame() instanceof JDialog) {
                if (((JDialog)getToplevelFrame()).isModal()) {
                    parentFrame = getToplevelFrame();
                }
            }
        }

        if (parentFrame instanceof Frame) {
            ret = new JDialog((Frame) parentFrame, title, modal);
        } else if (parentFrame instanceof Dialog) {
            ret = new JDialog((Dialog) parentFrame, title, modal);
        } else {
            ret = new JDialog(new Frame(), title, modal);
        }

        return ret;
    }

    /**
     * show the dialog on top of all other windows and center it against
     * the current toplevel component. The dialog will be registered as
     * new toplevelFrame
     */
    public static void popup(JDialog dialog) {
        try {
            SwingUtilities.invokeAndWait(new PopupRunnable(dialog));
        } catch (Error ex) {
            new PopupRunnable(dialog).run();
        } catch (Throwable ex) {
            ex.printStackTrace();
        }
    }

    public static void popdown(JDialog dialog) {
        if (dialog != null) {
            dialog.setVisible(false);
            dialog.dispose();
        }
    }


    static class PopupRunnable implements Runnable {
        JDialog dialog;

        PopupRunnable(JDialog dialog) {
            this.dialog = dialog;
        }

        public void run() {
            if (!applyDialogProperties(dialog)) {
                center(dialog, false);
            } else
            if (dialog.getOwner() != null && dialog.getOwner().getName() != null && dialog.getOwner().getName().equals(dialog.getName()))
            {
                Point location = dialog.getOwner().getLocation();
                dialog.setLocation(location.x + 20, location.y + 20);
                saveDialogProperties(dialog);
            }
            dialog.addWindowListener(new DialogListener(dialog));

            dialog.setVisible(true);

//            if (!dialog.isModal()) {
//                setAlwaysOnTop(dialog, true);
//                setAlwaysOnTop(dialog, false);
//            }
        }
    }

//    private static Method setAlwaysOnTopMethod;
//
//    protected static void initAlwaysOnTopMethods() {
//        // These methods is only needed for Gtk, Reflection is used to allow compilation
//        // against JDK 1.4
//        if (setAlwaysOnTopMethod == null) {
//            try {
//                setAlwaysOnTopMethod = Window.class.getMethod("setAlwaysOnTop", new Class[]{boolean.class});
//            } catch (NoSuchMethodException e) {
//                e.printStackTrace();
//            }
//        }
//    }
//
//    public static void setAlwaysOnTop(Window window, boolean onTop) {
//        initAlwaysOnTopMethods();
//        if (setAlwaysOnTopMethod == null) {
//            return;
//        }
//        try {
//            setAlwaysOnTopMethod.invoke(window, new Object[]{new Boolean(onTop)});
//        } catch (IllegalAccessException e) {
//            e.printStackTrace();
//        } catch (InvocationTargetException e) {
//            e.printStackTrace();
//        }
//    }


    /**
     * put the component in the center of the current toplevel window
     * or in the center of the screen
     */
    public static void center(Component comp, boolean centerOfScreen) {
        Rectangle bounds = null;

        if (centerOfScreen || getToplevelFrame() == null) {
            Dimension scrdim = Toolkit.getDefaultToolkit().getScreenSize();

            bounds = new Rectangle(0, 0, scrdim.width, scrdim.height);
        } else {
            bounds = getToplevelFrame().getBounds();
        }

        Dimension dim = comp.getSize();
        Point center = new Point(bounds.x + bounds.width / 2, bounds.y + bounds.height / 2);
        Point p = new Point(center.x - dim.width / 2, center.y - dim.height / 2);

        p.x = Math.max(p.x, 0);
        p.y = Math.max(p.y, 0);

        comp.setLocation(p);
    }

    /**
     * @param toplevelFrame
     * @deprecated
     */
    public static void setToplevelFrame(Component toplevelFrame) {
        //DialogManager.toplevelFrame = toplevelFrame;
    }

    public static Component getToplevelFrame() {
        return KeyboardFocusManager.getCurrentKeyboardFocusManager().getFocusedWindow();
    }

    private static class DialogListener extends WindowAdapter {
        JDialog dialog;

        private void close() {
            saveDialogProperties(dialog);
            setDefaultCursor(null);
        }

        public DialogListener(JDialog d) {
            this.dialog = d;
        }

        public void windowClosed(WindowEvent e) {
            close();
        }
    }


    static class DefaultErrorAdaptor implements ErrorAdaptor {
        public void show(String kat, String message) {
            System.err.println("[" + kat + "]: " + message);
        }

        public void error(String message) {
            show("error", message);
        }

        public void error(String message, Object param[]) {
            MessageFormat f = new MessageFormat(message);

            show("error", f.format(param));
        }

        public void warning(String message) {
            show("warning", message);
        }

        public void warning(String message, Object param[]) {
            MessageFormat f = new MessageFormat(message);

            show("warning", f.format(param));
        }
    }

    /**
     * @param directoryName null is System.getProperty("user.dir")
     */
    public static JnexFileChooser getFileChooser(String directoryName) {
        return JnexFileChooser.getInstance(directoryName);
    }

    public static void main(String[] args) {
        JFrame mainFrame = new JFrame("Application");
        mainFrame.setBounds(100, 100, 100, 100);
        mainFrame.setVisible(true);
        DialogManager.setApplicationFrame(mainFrame);
        JDialog modal1 = DialogManager.createJDialog("Modal1", true);

        JButton button = new JButton("press");
        button.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                JDialog notModalPopup = DialogManager.createJDialog("NotModalPopup", false);
                notModalPopup.setBounds(100, 100, 100, 100);
                DialogManager.popup(notModalPopup);
            }
        });
        modal1.getContentPane().add(button);
        modal1.pack();
        DialogManager.popup(modal1);
        JDialog notModal = DialogManager.createJDialog("NotModal1", false);
        DialogManager.popup(notModal);
        JDialog modal2 = DialogManager.createJDialog("Modal2", true);
        DialogManager.popup(modal2);
    }

}
TOP

Related Classes of com.nexirius.framework.application.DialogManager$PopupRunnable

TOP
Copyright © 2018 www.massapi.com. All rights reserved.
All source code are property of their respective owners. Java is a trademark of Sun Microsystems, Inc and owned by ORACLE Inc. Contact coftware#gmail.com.