Package net.helipilot50.stocktrade.displayproject

Source Code of net.helipilot50.stocktrade.displayproject.WindowManager

/*
Copyright (c) 2003-2009 ITerative Consulting Pty Ltd. All Rights Reserved.

Redistribution and use in source and binary forms, with or without modification, are permitted
provided that the following conditions are met:

o Redistributions of source code must retain the above copyright notice, this list of conditions and
the following disclaimer.
 
o Redistributions in binary form must reproduce the above copyright notice, this list of conditions
and the following disclaimer in the documentation and/or other materials provided with the distribution.
   
o This jcTOOL Helper Class software, whether in binary or source form may not be used within,
or to derive, any other product without the specific prior written permission of the copyright holder

 
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING,
BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.


*/
package net.helipilot50.stocktrade.displayproject;

import java.awt.Component;
import java.awt.Dimension;
import java.awt.Point;
import java.awt.Window;
import java.awt.event.WindowEvent;
import java.awt.event.WindowFocusListener;
import java.awt.event.WindowListener;
import java.util.EventListener;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Hashtable;
import java.util.Iterator;
import java.util.Map;
import java.util.NoSuchElementException;
import java.util.Set;
import java.util.Stack;

import javax.swing.Icon;
import javax.swing.JDialog;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.SwingUtilities;
import javax.swing.text.JTextComponent;

import net.helipilot50.stocktrade.displayproject.events.ClientEventManager;
import net.helipilot50.stocktrade.framework.EventHandle;
import net.helipilot50.stocktrade.framework.EventManager;
import net.helipilot50.stocktrade.framework.ForteKeyboardFocusManager;
import net.helipilot50.stocktrade.framework.FrameworkUtils;
import net.helipilot50.stocktrade.framework.ParameterHolder;
import net.helipilot50.stocktrade.framework.StringUtils;
import net.helipilot50.stocktrade.framework.TextData;

import org.apache.log4j.Logger;


/**
* The window manager provides manages which window is activated when another window is closed. It also manages the forte window closing events.
* @see java.awt.event.WindowListener
* @see java.awt.event.WindowFocusListener
*/
public class WindowManager implements WindowListener, WindowFocusListener {
    private static Map<String, Stack<Window>> ThreadWindowList = new Hashtable<String, Stack<Window>>(); // List of window threads
    private static Map<Window, String> WindowThreadList = new Hashtable<Window, String>();
    private static Window current = null;
    private static Map<Window, Thread> windowToThread = new HashMap<Window, Thread>();
    private static Logger _log = Logger.getLogger(WindowManager.class);
    /**
     * A list of the application modal windows. It is envisaged that there are only ever very few application
     * modal windows in an application at a time, so a set will do for storing these.
     */
    private static Set<Window> appModalWindows = new HashSet<Window>();

    public static Window getPrimaryWindow(){
            return current;
    }
    public static Point getPrimaryLocation(){
        Point p;
        if (current != null)
            p = current.getLocation();
        else
            p = new Point();
        return p;
    }
    public static Dimension getPrimarySize(){
        Dimension p = null;
        if (current != null) {
            p = current.getSize();
        }
        return p;
    }

    /**
     * Get a unique name for a thread so we can use it to index into a hash table. (Could possibly be
     * replaced with pThread.hashCode)
     */
    private static String getKey(Thread pThread) {
        if (pThread == null) {
            return null;
        }
        return pThread.toString()+pThread.hashCode();
    }

    public static void registerWindow(Window win) {
        WindowManager.registerWindow(win, getKey(Thread.currentThread()), false);
    }

    public static void registerWindow(Window win, boolean pIsAppModal) {
        WindowManager.registerWindow(win, getKey(Thread.currentThread()), pIsAppModal);
    }

    public static void registerWindow(Window win, String ThreadKey) {
        WindowManager.registerWindow(win, ThreadKey, false);
    }

    public static void registerWindow(Window win, String ThreadKey, boolean pIsAppModal) {

        _log.debug("Register window: " + win.toString());
        synchronized (WindowManager.class) {
            try {
                _log.debug("Current thread: " + ThreadKey);
                /*
                 * map the window to the running thread
                 */
                windowToThread.put(win, Thread.currentThread());
                /*
                 * Find the thread in the list of window threads
                 */
                Stack<Window> s = ThreadWindowList.get(ThreadKey);
                if (s == null) {
                    /*
                     * if we dont find one, make one
                     */
                    s = new Stack<Window>();
                    _log.debug("..Creating thread entry");
                    ThreadWindowList.put(ThreadKey, s);
                }

                try {
                    /*
                     * Find the previous window on this thread
                     */
                    Window prevWin = ((Window)s.lastElement());
                    if (prevWin != null) {
                        /*
                         * if we find one, disable it
                         */
                      // We no longer need this kludge as we have GlassPaneWithEvents.  CraigM: 31/03/2008
                        // prevWin.setEnabled(false); //PM:8/10/07 kludge to stop the flicker
                        _log.debug("..Disabled parent window: " + prevWin.toString());

                        // Also, if the last window was application modal, this one must be too
                        // to prevent an incredibly confusing user dialog
                        if (appModalWindows.contains(prevWin)) {
                            pIsAppModal = true;
                        }
                    }
                } catch (NoSuchElementException ex){
                }
                /*
                 * push this window onto the stack
                 */
                s.push (win);
                /*
                 * put an entry into the Window thread list
                 */
                WindowThreadList.put(win, ThreadKey);
                _log.debug(".Pushed new window on stack: " + win.toString());
                if (pIsAppModal) {
                    appModalWindows.add(win);
                }

            } catch (RuntimeException e1) {
                _log.error(e1);
            }
        }
        CursorMgr.createWindow(win);
    }

    /**
     * Return the window prior to the passed window on the display stack of the
     * current thread. This method is not synchronized and cannot be made so
     * without deadlock, however this isn't a real issue as the code that is retrieving
     * the information is only dealing with one thread at a time typically.
     */
    public static Window getPreviousWindow(Window win) {
        String ThreadKey = WindowThreadList.get(win);
        if (ThreadKey != null){
            Stack<Window> s = ThreadWindowList.get(ThreadKey);
            if (s != null){
                for (int i = 0; i < s.size(); i++) {
                    if (s.get(i) == win) {
                        if (i > 0) {
                            return s.get(i-1);
                        }
                        else {
                            return null;
                        }
                    }
                }
            }
        }
        return null;
    }

    public synchronized static void deregisterWindow(final Window win){
        UIutils.invokeOnGuiThread(new Runnable(){
            public void run() {
                _log.debug("Deregister window: " + win.toString());
                try {
                    CursorMgr.destroyWindow(win);
                    appModalWindows.remove(win);
                    windowToThread.remove(win);
                    String ThreadKey = ((String)WindowThreadList.get(win));
                    WindowThreadList.remove(win);

                    // Window is now deregistered.  Also dispose of it (previously done by callers)
                    // This makes sure that race conditions cannot occur (deregister happens before next window is activated)
                    win.setVisible(false);
                    win.dispose();

                    // Now bring the next window on the stack to the front.
                    _log.debug("Current thread: " + ThreadKey);
                    if (ThreadKey != null){
                        Stack<Window> s = ThreadWindowList.get(ThreadKey);
                        if (s != null){
                            try {
                                _log.debug(".Popping: " + s.lastElement().toString());
                                s.pop();
                                Window prevWin = s.lastElement();
                                if (prevWin != null) {
                                    _log.debug("..ToFront: " + prevWin.toString());
                                    // We no longer need this kludge as we have GlassPaneWithEvents.  CraigM: 31/03/2008
                                    // prevWin.setEnabled(true); //PM:8/10/07 klughe to stop the flicker
                                    prevWin.toFront();
                                    prevWin.requestFocus();
                                }
                                // remove the stack if it's empty to prevent keeping lots of
                                // expired entries on the stack, enabling it to grow without bounds
                                if (s.isEmpty()) {
                                    ThreadWindowList.remove(ThreadKey);
                                }
                            } catch (NoSuchElementException ex){
                            }       
                        }
                    }
                } catch (RuntimeException e1) {
                    _log.debug(e1);
                }
            }
        });
    }
    public void windowOpened(WindowEvent e) {
      if (_log.isDebugEnabled()) {
        _log.debug("["+this+"] Opening window: " + e.getWindow().toString());
      }
    }
    public void windowDeactivated(WindowEvent e) {
      if (_log.isDebugEnabled()) {
        _log.debug("["+this+"] Deactivated window: " + e.getWindow().toString());
      }
        ClientEventManager.postEvent( e.getComponent(), "AfterDeactivate" );
        current = null;
        if (_log.isDebugEnabled()) {
          _log.debug("["+this+"] CURRENT="+current);
        }
    }
    public void windowDeiconified(WindowEvent e) {
        _log.debug("["+this+"] Deiconified window: " + e.getWindow().toString());
        Hashtable<String, Object> qq_Params = new Hashtable<String, Object>();
        qq_Params.put( "x", new ParameterHolder(0) );
        qq_Params.put( "y", new ParameterHolder(0) );
        qq_Params.put( "modifier", new ParameterHolder(Constants.DS_NORMAL) );
        qq_Params.put( "DisplayNode", new ParameterHolder(null) );
        qq_Params.put( "row", new ParameterHolder(0) );
        qq_Params.put( "column", new ParameterHolder(0) );
        qq_Params.put( "OldState", new ParameterHolder(0) );
        qq_Params.put( "NewState", new ParameterHolder(Constants.DS_NORMAL) );
        ClientEventManager.postEvent( e.getComponent(), "DisplayStateChange", qq_Params);  
    }
    public void windowIconified(WindowEvent e) {
        _log.debug("["+this+"] Iconified window: " + e.getWindow().toString());
        Hashtable<String, Object> qq_Params = new Hashtable<String, Object>();
        qq_Params.put( "x", new ParameterHolder(0) );
        qq_Params.put( "y", new ParameterHolder(0) );
        qq_Params.put( "modifier", new ParameterHolder(Constants.DS_ICONIZED) );
        qq_Params.put( "DisplayNode", new ParameterHolder(null) );
        qq_Params.put( "row", new ParameterHolder(0) );
        qq_Params.put( "column", new ParameterHolder(0) );
        qq_Params.put( "OldState", new ParameterHolder(0) );
        qq_Params.put( "NewState", new ParameterHolder(Constants.DS_ICONIZED) );
        ClientEventManager.postEvent( e.getComponent(), "DisplayStateChange", qq_Params);  
    }
    /**
     * Triggered when the underlying window gains focus. We set the focus back to the correct
     * field on the window and then post the AfterFocusGain event
     */
    public void windowGainedFocus(WindowEvent e) {
        JFrame win = (JFrame)e.getWindow();
       
        //PM:6/10/07 - fixes the crazy window focus issue
        if (WindowManager.current != win) {

          // CraigM:03/11/2008 - If a modal window is minimised, and its parent window gains focus,
          //              the windowActivated will not always get called, so call it manually.
          this.windowActivated(e);
            return;
        }
        Component lastFocusOwner = (Component)win.getRootPane().getClientProperty("qq_lastFocusField");
        if (lastFocusOwner == null)
            lastFocusOwner = e.getWindow().getFocusTraversalPolicy().getFirstComponent(e.getWindow());
        _log.debug("Gained focus window: " + win.toString());
        _log.debug("\tfocus component: " + lastFocusOwner);
        if (lastFocusOwner != null){
          final int[] selectionStart = new int[1];
          final int[] selectionEnd = new int[1];
          boolean needToRestoreSelection = false;
          if (lastFocusOwner instanceof JTextComponent) {
        JTextComponent textComponent = (JTextComponent) lastFocusOwner;
        if (textComponent.getSelectedText() != null && textComponent.getSelectedText().length() != 0) {
          selectionStart[0] = textComponent.getSelectionStart();
          selectionEnd[0] = textComponent.getSelectionEnd();
          needToRestoreSelection = true;
        }
      }
            ForteKeyboardFocusManager.setSurpress();
            lastFocusOwner.requestFocusInWindow();
           
            // DK:09/10/2008:restore selection of text if before focus request there were any text selected.
            //We need it because TextComponent clears selection by focus gain event.
            if (needToRestoreSelection) {
        final JTextComponent textComponent = (JTextComponent) lastFocusOwner;
        SwingUtilities.invokeLater(new Runnable() {
          public void run() {
            textComponent.select(selectionStart[0], selectionEnd[0]);
          }
        });
      }
        }
        /*
         * If the window is being shown from a dialog box, it could be in response to a popup
         * error message. (For example, field validation.) In this case, if we set the focus
         * back to the control, the invalid control will attempt to verify again, which results
         * in failure and a popup, and so on in an infinite loop. Besides, JDialog boxes are
         * normally well behaved and leave the focus on the correct field on this window when
         * they close.
         */
        if (!(e.getOppositeWindow() instanceof JDialog)) {
            if (e.getWindow() instanceof JFrame){
//                ((JFrame)e.getWindow()).getContentPane().requestFocus();
            } else {
                ((JDialog)e.getWindow()).getContentPane().requestFocus();
            }
        }
        /*
         * Post an event to this thread. If the thread exists, we post a delayed event. This
         * caters for the case where a new thread creates a window, opens it and then enters
         * the event loop. The registration comes after the event is dispatched, so if the
         * window needs this event, it would miss it unless we delay it.
         */
        Thread th = getOwningThread(e.getWindow());
        if (th != null) {
            EventManager.postDelayedEvent(e.getComponent(), "AfterFocusGain", null, th);
        }
        else {
            ClientEventManager.postEvent( e.getComponent(), "AfterFocusGain" );
        }
    }

    public static Thread getOwningThread(Window win) {
        return windowToThread.get(win);
    }
    public void windowLostFocus(WindowEvent e) {
        JFrame win = (JFrame)e.getWindow();
        Component lastFocusOwner = win.getMostRecentFocusOwner();
        win.getRootPane().putClientProperty("qq_lastFocusField", lastFocusOwner);
        if (_log.isDebugEnabled()) {
          _log.debug("Lost focus window: " + e.getWindow().toString());
          _log.debug("\tLast focus owner was: " + lastFocusOwner);
        }
    }
    public void windowClosing(WindowEvent e) {
        Window win = e.getWindow();
        Window properWin = WindowManager.blockedBy(win);
        if (win == properWin) {
            // Only process window closing events if we're the deepest level modal window.
          if (_log.isDebugEnabled()) {
            _log.debug("["+this+"] Closing window: " + win.toString());
          }
            int closePolicy = 0;
            try {
                Class<?> cls = win.getClass();
                //PM:13/12/07 fixed close policy
                //closePolicy = cls.getField("qq_SystemClosePolicy").getInt(win);
                closePolicy = ((Integer)cls.getMethod("getSystemClosePolicy").invoke(win));
            } catch (Exception ex) {
                closePolicy = Constants.SC_ENABLEDSHUTDOWN;
            }
            switch (closePolicy){
            case Constants.SC_DISABLED:
                break;
            case Constants.SC_ENABLEDNOFINALIZE:
                break;
            case Constants.SC_ENABLEDFINALIZE:
//            FocusHelper.windowClosing(win);
                UIutils.requestFinalize((JFrame)win);
                break;
            case Constants.SC_ENABLEDSHUTDOWN:
        default:
            Thread th = getOwningThread(e.getWindow());
            FocusHelper.windowClosing(win, new EventHandle[] {new EventHandle(th, "Shutdown")});
            break;
        }
            /*
             * 25/01/06 Commented out below call.
             * If user has made changes and then cancels the close operation, we
             * want the window to continue as usual.
             * The deregisterWindow() method will be called from elsewhere eg. BaseWindow.DisplayObject
             * so it should be ok not to perform here. 
             */
//          deregisterWindow(win);
        }
    }

    /**
     * Given a window to activate, if there is an application modal window and the passed window
     * isn't it, activate the application modal window.
     * @param win
     * @return
     */
    private static synchronized Window overrideWindowToActivateWithAppModalOne(Window win) {
        if (appModalWindows.isEmpty()) {
            return win;
        }
        else if (appModalWindows.contains(win)) {
            // This is an app modal window, activate it.
            return win;
        }
        else {
            // There are application modal windows, this windows isn't one, get one out of the
            // set at random
            Iterator<Window> it = appModalWindows.iterator();
            if (it.hasNext()) {
                return it.next();
            }
            else {
                return win;
            }
        }
    }

    public static Window getWindowToActivate() {
        return getWindowToActivate(false);
    }

    /**
     * Return the window to be activated on the current thread, that is the most recently
     * opened modal window.
     * @param pIgnoreAppModalWindows set to true to allow this method to return only windows
     * on the current thread, or false to be able to return an application modal window on
     * a different thread.
     */
    public static Window getWindowToActivate(boolean pIgnoreAppModalWindows) {
        return getWindowToActivate(Thread.currentThread(), pIgnoreAppModalWindows);
    }

    /**
     * Return the window to be activated for the given thread, that is the most recently
     * opened modal window on this thread.
     * @param pThread The thread which we're interested in
     * @param pIgnoreAppModalWindows set to true to allow this method to return only windows
     * on the current thread, or false to be able to return an application modal window on
     * a different thread.
     * @return The window to open, or null if there is no window or the thread is unknown
     */
    public static Window getWindowToActivate(Thread pThread, boolean pIgnoreAppModalWindows) {
        /*
         * Find the thread in the list of window threads
         */
        Window result;
        Stack<Window> s = ThreadWindowList.get(getKey(pThread));
        if (s == null || s.isEmpty()) {
            result = null;
        }
        else {
            result = s.peek();
        }
        if (pIgnoreAppModalWindows) {
            return result;
        }
        else {
            return overrideWindowToActivateWithAppModalOne(result);
        }
    }

    /**
     * Get the active window for the thread that controls the passed window. This will be the most
     * recently opened modal child of the passed window (or null if this window is unknown to the manager)
     * @param pWin
     * @return
     */
    public static Window getWindowToActivate(Window pWin, boolean pIgnoreAppModalWindows) {
        Thread th = getOwningThread(pWin);
        if (th == null) {
            // We're trying to activate a window which has never been properly registered. This may be
            // because of something gone wrong with nested windows for example. Just allow the window to
            // be activated.
          if (_log.isInfoEnabled()) {
            _log.info("getWindowToActivate(" + pWin.toString() + ") couldn't find the owning thread.\nTrace: " + FrameworkUtils.traceBack());
          }
            return overrideWindowToActivateWithAppModalOne(pWin);
        }
        else {
            return getWindowToActivate(th, pIgnoreAppModalWindows);
        }
    }
    public static Window getWindowToActivate(Window pWin) {
        return getWindowToActivate(pWin, false);
    }

    public void windowClosed(WindowEvent e) {
      if (_log.isDebugEnabled()) {
        _log.debug("["+this+"] Closed window: " + e.getWindow().toString());
      }
    }
    public void windowActivated(WindowEvent e) {
      boolean doDebug = _log.isDebugEnabled();
        Window originalTarget = e.getWindow();
        if (doDebug) {
          _log.debug("["+this+"] Activate window: " + e.getWindow().toString());
        }
        Window properTarget = getWindowToActivate(originalTarget);
        if (properTarget == null || properTarget == originalTarget) {
            // This is the correct window to activate, fire the event
          if (doDebug) {
            _log.debug("["+this+"] Proper activate.");
          }
            ClientEventManager.postEvent( e.getComponent(), "AfterActivate" );
            current = ((Window)e.getComponent());
        }
        else {
          if (doDebug) {
            _log.debug("["+this+"] Improper Activate : PROPER TARGET = " + properTarget.toString());
          }
            // focus to the deepest level child.
            properTarget.toFront();
            properTarget.requestFocus();
            current = properTarget;
        }
        if (doDebug) {
          _log.debug("["+this+"] CURRENT="+current);
        }
    }
    public static Window blockedBy(Window source){
        return current;
    }
    public static void addWindowListener(Window win){
        EventListener[] listeners = win.getListeners(WindowListener.class);
        if (listeners != null){
            for (int i = 0; i < listeners.length; i++){
                if (listeners[i].getClass().equals(WindowManager.class))
                    return;
            }
        }
        WindowManager wm = new WindowManager();
        win.addWindowListener(wm);
        win.addWindowFocusListener(wm);
    }
    class WindowEntry{
        private Window window;
        private Thread thead;
        public WindowEntry(Window window, Thread thead) {
            super();
            this.window = window;
            this.thead = thead;
        }
        public Thread getThead() {
            return thead;
        }
        public Window getWindow() {
            return window;
        }

    }

    /**
     * Set the passed window to be application modal or not, depending on the value of the
     * second parameter. Note that this method does not actually set focus into the passed
     * window even if pAppModal is true, this must be done elsewhere.
     * @param pWin - The window to make application modal
     * @param pAppModal - Whether the passed window should be made application modal or not.
     * @return true if the window was previously application modal, or false otherwise.
     */
    private static synchronized boolean setAppModal(Window pWin, boolean pAppModal) {
        if (pWin == null) {
            return false;
        }
        boolean result = appModalWindows.contains(pWin);
        if (pAppModal) {
            if (!result) {
                appModalWindows.add(pWin);
            }
        }
        else if (result) {
            appModalWindows.remove(pWin);
        }
        return result;     
    }
    /*---------------------------------------------------------
     *       Question Dialog
     ---------------------------------------------------------*/
    public static int questionDialog(TextData messageText, int buttonSet, int defaultButton, int wrapWidth){
      return questionDialog(messageText.toString(), buttonSet, defaultButton, wrapWidth);
    }
    public static int questionDialog(String messageText, int buttonSet, int defaultButton, int wrapWidth){
      return showQuestionDialog(StringUtils.wrapText(messageText, "", wrapWidth, 4), buttonSet, defaultButton);

    }
    /**
     * The following utility routines handle different pop-up messages, always giving them a parent of
     * the current primary window.  They should be used in preference to direct use of JOptionPane,
     * particularly if the default button needs to be other than OK/Yes.
     *
     * The first few routines have a simpler, reduced parameter set and should be used in preference
     * to the later routines which have been included for backward compatability with raw converted code.
     *
     * We make the owning windows application modal if not already done, so that this dialog will always
     * float ontop of the application properly
     */
    public static int showQuestionDialog(String msg, int optionType, int initialOption) {
        Window win = findParentWindow();
        boolean wasAppModal = setAppModal(win, true);
        int result = DialogOptionPane.showOptionDialog(win, msg, "Question", optionType, JOptionPane.QUESTION_MESSAGE, initialOption);
        if (!wasAppModal) {
            setAppModal(win, false);
        }
        return result;
    }

    public static int showErrorDialog(String msg, int optionType, int initialOption) {
        Window win = findParentWindow();
        boolean wasAppModal = setAppModal(win, true);
        int result = DialogOptionPane.showOptionDialog(win, msg, "Error", optionType, JOptionPane.ERROR_MESSAGE, initialOption);
        if (!wasAppModal) {
            setAppModal(win, false);
        }
        return result;
    }

    public static int showErrorDialog(String msg) {
        return showErrorDialog(msg, JOptionPane.DEFAULT_OPTION, 0);
    }

    public static int showInformationDialog(String msg, int optionType, int initialOption) {
        Window win = findParentWindow();
        boolean wasAppModal = setAppModal(win, true);
        int result = DialogOptionPane.showOptionDialog(win, msg, "Information", optionType, JOptionPane.INFORMATION_MESSAGE, initialOption);
        if (!wasAppModal) {
            setAppModal(win, false);
        }
        return result;
    }

    public static int showInformationDialog(String msg) {
        return showInformationDialog(msg, JOptionPane.DEFAULT_OPTION, 0);
    }

    public static int showWarningDialog(String msg, int optionType, int initialOption) {
        Window win = findParentWindow();
        boolean wasAppModal = setAppModal(win, true);
        int result = DialogOptionPane.showOptionDialog(win, msg, "Warning", optionType, JOptionPane.WARNING_MESSAGE, initialOption);
        if (!wasAppModal) {
            setAppModal(win, false);
        }
        return result;
    }

    public static int showWarningDialog(String msg) {
        Window win = findParentWindow();
        boolean wasAppModal = setAppModal(win, true);
        int result = DialogOptionPane.showOptionDialog(win, msg, "Warning", JOptionPane.DEFAULT_OPTION, JOptionPane.WARNING_MESSAGE, 0);
        if (!wasAppModal) {
            setAppModal(win, false);
        }
        return result;
    }
    /*-------------------------------------------------------
  Message Dialog
  ---------------------------------------------------------*/
    public static int showMessageDialog(Component parentComponent, String msg, String title, int optionType) {
        if (optionType == JOptionPane.WARNING_MESSAGE) {
            return showWarningDialog(msg);
        }
        else if (optionType == JOptionPane.ERROR_MESSAGE) {
            return showErrorDialog(msg);
        }
        else if (optionType == JOptionPane.INFORMATION_MESSAGE) {
            return showInformationDialog(msg);
        }
        else {
            return showOptionDialog(parentComponent, msg, title, JOptionPane.DEFAULT_OPTION, optionType, null, null, null);
        }
    }
   
    /**
     * The messageDialog method displays a message dialog on a main window, which makes the window application-modal, meaning that it prevents input to all other windows while it is active.
     * A message dialog window contains a message and a button for dismissing the dialog.
     * @param parentComponent The parent JFrame
     * @param messageText The messageText parameter specifies the text to use as the message in the dialog.
     * @param messageType The messageType parameter specifies the type of window system dialog to contain the message. Window systems use their own window styles and icons to distinguish different types of messages, such as warnings and errors. The default is MT_INFO.
     * @param wrapWidth The wrapWidth parameter specifies maximum number of characters per line to use in the dialog�s message text before word wrapping begins. You can also use explicit newline characters to break dialog lines.
     */
    //PM:14/05/2008: added forte method signature
    public static void messageDialog(Component parentComponent, TextData messageText, int messageType, int wrapWidth){
      messageDialog(parentComponent, messageText.toString(), messageType, wrapWidth);
    }
    //PM:14/05/2008: added forte method signature
    public static void messageDialog(Component parentComponent, String messageText, int messageType, int wrapWidth){
      String caption = "Information";
      int optionType = JOptionPane.DEFAULT_OPTION;
      switch (messageType){
      case Constants.MT_INFO:
        caption = "Information";
        optionType = JOptionPane.INFORMATION_MESSAGE;
        break;
      case Constants.MT_WARNING:
        caption = "Warning";
        optionType = JOptionPane.WARNING_MESSAGE;
        break;
      case Constants.MT_ERROR:
        caption = "Error";
        optionType = JOptionPane.ERROR_MESSAGE;
        break;
      }
     
      showMessageDialog(parentComponent, StringUtils.wrapText(messageText, "", wrapWidth, 4), caption, optionType);
    }
   
    public static int showMessageDialog(Component parentComponent, String msg) {
        return showMessageDialog(parentComponent, msg, "", JOptionPane.INFORMATION_MESSAGE);
    }

    public static int showOptionDialog(String msg, int dialogType, int wrapWidth) {
        Window win = findParentWindow();
        boolean wasAppModal = setAppModal(win, true);
        int result = DialogOptionPane.showOptionDialog(win, msg, dialogType, wrapWidth);
        if (!wasAppModal) {
            setAppModal(win, false);
        }
        return result;
    }

    public static int showOptionDialog(Component parentComponent, String msg, String title, int optionType, int msgType, Icon icon, Object[] options, Object initialValue) {
        if (parentComponent==null) {
            parentComponent=findParentWindow();
        }
        final int initialOption = findInitialOption(options, initialValue);
        Window win = (parentComponent instanceof Window) ? ((Window)parentComponent) : null;
        boolean wasAppModal = setAppModal(win, true);
        int result = DialogOptionPane.showOptionDialog(parentComponent, msg, title, optionType, msgType, initialOption);
        if (!wasAppModal) {
            setAppModal(win, false);
        }
        return result;
    }


    public static int showOptionDialog(String msg, String title, int optionType, int msgType, Icon icon, Object[] options, Object initialValue) {
        final int initialOption = findInitialOption(options, initialValue);
        Window win = findParentWindow();
        boolean wasAppModal = setAppModal(win, true);
        int result = DialogOptionPane.showOptionDialog(win, msg, title, optionType, msgType, initialOption);
        if (!wasAppModal) {
            setAppModal(win, false);
        }
        return result;
    }

    // Find index of initial value in array of options
    private static int findInitialOption(Object[] options, Object initialValue) {
        int initialOption = JOptionPane.OK_OPTION;          // Also equivalent to Yes
        if (options!=null && initialValue!=null) {
            for (int i=0; i<options.length; i++) {
                if (initialValue.equals(options[i])) {
                    if (i<3) {
                        initialOption = i;
                    }
                    break;
                }
            }
        }
        return initialOption;
    }

//     Changed the order - use the current thread first rather that call to getPrimaryWindow
//     The current window can be the CacheLoadDisplayWin in this case any dialog that has it's parent
//     set to CacheLoadDisplayWin will be dismissed when CacheLoadDisplayWin is set to invisible

    private static Window findParentWindow() {
        Window parent = null;

        // If no primary window open, get window for current thread
        Stack<Window> s = ThreadWindowList.get(getKey(Thread.currentThread()));
        if (s!=null && !s.isEmpty()) {
            parent = (Window)s.peek();
        }
        else {
            parent = getPrimaryWindow();
        }

        if (parent==null) {
            System.err.println("WindowManager.findParentWindow ===>> Unable to find a parent window for dialog box");
        }
        return parent;
    }

//    private static Component findParentWindow() {
//      Component parent = getPrimaryWindow();
//      // If no primary window open, get window for current thread
//      if (parent==null) {
//        System.err.println("WindowManager.findParentWindow ===>> Primary null - looking for another in thread "+getKey(Thread.currentThread()));
//            Stack s = ((Stack)ThreadWindowList.get(getKey(Thread.currentThread())));
//            if (s!=null && s.size()>0) {
//              parent = (Component)s.get(s.size()-1);
//            }
//            else {
//              System.err.println("WindowManager.findParentWindow ===>> Unable to find a parent window for dialog box");
//            }
//      }
//      return parent;
//    }

}
TOP

Related Classes of net.helipilot50.stocktrade.displayproject.WindowManager

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.