Java/Swing JFC/GUI Utilities

Материал из Java эксперт
Версия от 18:01, 31 мая 2010; (обсуждение)
(разн.) ← Предыдущая | Текущая версия (разн.) | Следующая → (разн.)
Перейти к: навигация, поиск

A utility class to tune the Metal look and feel.

 
/* 
 * JCommon : a free general purpose class library for the Java(tm) platform
 * 
 *
 * (C) Copyright 2000-2005, by Object Refinery Limited and Contributors.
 * 
 * Project Info:  http://www.jfree.org/jcommon/index.html
 *
 * This library 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 2.1 of the License, or 
 * (at your option) any later version.
 *
 * This library 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 Lesser General Public 
 * License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
 * License along with this library; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, 
 * USA.  
 *
 * [Java is a trademark or registered trademark of Sun Microsystems, Inc. 
 * in the United States and other countries.]
 *
 * ----------------
 * UIUtilities.java
 * ----------------
 * (C) Copyright 2002-2005, by Object Refinery Limited.
 *
 * Original Author:  Thomas Morgner (for Object Refinery Limited);
 * Contributor(s):   -;
 *
 * $Id: UIUtilities.java,v 1.7 2007/11/02 17:50:36 taqua Exp $
 *
 * Changes:
 * --------
 * 25-Jul-2002 : Version 1 (TM);
 */
import java.awt.Color;
import javax.swing.UIDefaults;
import javax.swing.UIManager;
import javax.swing.border.EmptyBorder;
import javax.swing.border.EtchedBorder;
import javax.swing.border.MatteBorder;
import javax.swing.plaf.BorderUIResource;
/**
 * A utility class to tune the Metal look and feel.
 * 
 * @author Thomas Morgner
 */
public class UIUtilities {

  /**
   * Set up the user interface.
   */
  public static void setupUI() {
    try {
      final String classname = UIManager.getSystemLookAndFeelClassName();
      UIManager.setLookAndFeel(classname);
    } catch (Exception e) {
      e.printStackTrace();
    }
    final UIDefaults defaults = UIManager.getDefaults();
    defaults.put("PopupMenu.border", new BorderUIResource.EtchedBorderUIResource(
        EtchedBorder.RAISED, defaults.getColor("controlShadow"), defaults
            .getColor("controlLtHighlight")));
    final MatteBorder matteborder = new MatteBorder(1, 1, 1, 1, Color.black);
    final EmptyBorder emptyborder = new MatteBorder(2, 2, 2, 2, defaults.getColor("control"));
    final BorderUIResource.rupoundBorderUIResource compBorder = new BorderUIResource.rupoundBorderUIResource(
        emptyborder, matteborder);
    final BorderUIResource.EmptyBorderUIResource emptyBorderUI = new BorderUIResource.EmptyBorderUIResource(
        0, 0, 0, 0);
    defaults.put("SplitPane.border", emptyBorderUI);
    defaults.put("Table.scrollPaneBorder", emptyBorderUI);
    defaults.put("ComboBox.border", compBorder);
    defaults.put("TextField.border", compBorder);
    defaults.put("TextArea.border", compBorder);
    defaults.put("CheckBox.border", compBorder);
    defaults.put("ScrollPane.border", emptyBorderUI);
  }
}





AWT Utilities

   
/**
 * The utillib library.
 * More information is available at http://www.jinchess.ru/.
 * Copyright (C) 2002, 2003 Alexander Maryanovsky.
 * All rights reserved.
 *
 * The utillib library 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 2 of the
 * License, or (at your option) any later version.
 *
 * The utillib library 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 Lesser
 * General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public License
 * along with utillib library; if not, write to the Free Software
 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
 */

import java.awt.*;
import java.lang.reflect.*;

/**
 * A collection of AWT related utilities.
 */
public class AWTUtilities{

  /**
   * Packs and centers the given window relative to the given component. The
   * specified component may be <code>null</code>, in which case the window will
   * be centered on the screen. The method also makes sure that the target
   * window is fully visible by calling <code>forceToScreen</code>.
   */
  public static void centerWindow(Window target, Component parent){
    target.pack();
    Dimension size = target.getSize();
    Rectangle parentBounds = parent == null || !parent.isShowing() ? 
      getUsableScreenBounds() :
      new Rectangle(parent.getLocationOnScreen(), parent.getSize());
    target.setLocation(parentBounds.x + (parentBounds.width - size.width)/2, parentBounds.y + (parentBounds.height - size.height)/2);
    
    forceToScreen(target);
  }
  
  
  
  /**
   * Reposition the specified window so that it necessarily fits on the screen,
   * while trying to minimize changes.
   */
   
  public static void forceToScreen(Window window){
    Dimension screenSize = window.getToolkit().getScreenSize();
    Rectangle bounds = window.getBounds();
    
    bounds.width = Math.min(bounds.width, screenSize.width);
    bounds.height = Math.min(bounds.height, screenSize.height);
    bounds.x = Math.min(Math.max(bounds.x, 0), screenSize.width - bounds.width);    
    bounds.y = Math.min(Math.max(bounds.y, 0), screenSize.height - bounds.height);
    window.setBounds(bounds);    
  }


  /**
   * Returns the parent Frame of the specified <code>Component</code> or
   * <code>null</code> if none exists.
   */
  public static Frame frameForComponent(Component component){
    while (component != null){
      if (component instanceof Frame)
        return (Frame)component;
      component = component.getParent();
    }
    return null;
  }


  /**
   * Returns a list of available font names. Under JDK1.1 it uses
   * <code>Toolkit.getFontList()</code> while under JDK1.2 (via reflection),
   * <code>GraphicsEnvironment.getAvailableFontFamilyNames()</code>
   */
  public static String [] getAvailableFontNames(){
    if (PlatformUtils.isJavaBetterThan("1.2")){
      try{
        // The equivalent of "return GraphicsEnvironment.getLocalGraphicsEnvironment().getAvailableFontFamilyNames();"
        Class geClass = Class.forName("java.awt.GraphicsEnvironment");
        Method getLocalGraphicsEnvironmentMethod = geClass.getMethod("getLocalGraphicsEnvironment", new Class[0]);
        Object localGE = getLocalGraphicsEnvironmentMethod.invoke(null, new Object[0]);
        Method getAvailableFontFamilyNamesMethod = geClass.getMethod("getAvailableFontFamilyNames", new Class[0]);
        String [] fontNames = (String [])getAvailableFontFamilyNamesMethod.invoke(localGE, new Object[0]);
        return fontNames;
      } catch (ClassNotFoundException e){e.printStackTrace();}
        catch (NoSuchMethodException e){e.printStackTrace();}
        catch (IllegalAccessException e){e.printStackTrace();}
        catch (InvocationTargetException e){e.printStackTrace();}
      return null;
    }
    else
      return Toolkit.getDefaultToolkit().getFontList();
  }
  
  
  
  /**
   * Returns the state of the specified frame, as specified by
   * <code>Frame.getExtendedState()</code> if running under JDK 1.4 or later,
   * otherwise returns 0. The call to <code>Frame.getExtendedState()</code> is
   * done via reflection to avoid runtime errors.
   */
   
  public static int getExtendedFrameState(Frame frame){
    if (PlatformUtils.isJavaBetterThan("1.4")){
      try{
        Class frameClass = Class.forName("java.awt.Frame");
        Method getExtendedStateMethod = frameClass.getMethod("getExtendedState", new Class[0]);
        Integer state = (Integer)getExtendedStateMethod.invoke(frame, new Object[0]);
        return state.intValue();
      } catch (ClassNotFoundException e){e.printStackTrace();}
        catch (NoSuchMethodException e){e.printStackTrace();}
        catch (IllegalAccessException e){e.printStackTrace();}
        catch (InvocationTargetException e){e.printStackTrace();}
    }
    
    return 0;
  }
  
  
  
  /**
   * Sets the state of the specified frame, as specified by
   * <code>Frame.setExtendedState</code> if running in JDK 1.4 or later,
   * otherwise does nothing. The call to <code>Frame.setExtendedState()</code>
   * is done via reflection to avoid runtime errors. 
   */
   
  public static void setExtendedFrameState(Frame frame, int state){
    if (PlatformUtils.isJavaBetterThan("1.4")){
      try{
        Class frameClass = Class.forName("java.awt.Frame");
        Method setExtendedStateMethod = frameClass.getMethod("setExtendedState", new Class[]{int.class});
        setExtendedStateMethod.invoke(frame, new Object[]{new Integer(state)});
      } catch (ClassNotFoundException e){e.printStackTrace();}
        catch (NoSuchMethodException e){e.printStackTrace();}
        catch (IllegalAccessException e){e.printStackTrace();}
        catch (InvocationTargetException e){e.printStackTrace();}
    }
  }
  
  
  
  /**
   * Attempts to determine the usable screen bounds of the default screen
   * device. If the require java.awt API is not available under the JVM we"re
   * running in, this will simply return the screen bounds obtained via
   * <code>Toolkit.getScreenSize()</code>.
   */
  
  public static Rectangle getUsableScreenBounds(){
    if (PlatformUtils.isJavaBetterThan("1.4")){
      try{
        Class graphicsEnvironmentClass = Class.forName("java.awt.GraphicsEnvironment");
        Class graphicsDeviceClass = Class.forName("java.awt.GraphicsDevice");
        Class graphicsConfigurationClass = Class.forName("java.awt.GraphicsConfiguration");
        
        Class [] emptyClassArr = new Class[0];
        Method getLocalGraphicsEnvironmentMethod = 
          graphicsEnvironmentClass.getMethod("getLocalGraphicsEnvironment", emptyClassArr);
        Method getDefaultScreenDeviceMethod = 
          graphicsEnvironmentClass.getMethod("getDefaultScreenDevice", emptyClassArr);
        Method getDefaultConfigurationMethod =
          graphicsDeviceClass.getMethod("getDefaultConfiguration", emptyClassArr);
        Method getBoundsMethod = 
          graphicsConfigurationClass.getMethod("getBounds", emptyClassArr);
        Method getScreenInsetsMethod = 
          Toolkit.class.getMethod("getScreenInsets", new Class[]{graphicsConfigurationClass});
        
        Object [] emptyObjArr = new Object[0];
        Object graphicsEnvironment = getLocalGraphicsEnvironmentMethod.invoke(null, emptyObjArr);
        Object defaultScreenDevice = getDefaultScreenDeviceMethod.invoke(graphicsEnvironment, emptyObjArr);
        Object defaultConfiguration = getDefaultConfigurationMethod.invoke(defaultScreenDevice, emptyObjArr);
        Rectangle bounds = (Rectangle)getBoundsMethod.invoke(defaultConfiguration, emptyObjArr);
        Insets insets = 
          (Insets)getScreenInsetsMethod.invoke(Toolkit.getDefaultToolkit(), new Object[]{defaultConfiguration});
        
        bounds.x += insets.left;
        bounds.y += insets.top;
        bounds.width -= insets.left + insets.right;
        bounds.height -= insets.top + insets.bottom;
        
        return bounds;
      } catch (ClassNotFoundException e){e.printStackTrace();}
        catch (SecurityException e){e.printStackTrace();}
        catch (NoSuchMethodException e){e.printStackTrace();}
        catch (IllegalArgumentException e){e.printStackTrace();}
        catch (IllegalAccessException e){e.printStackTrace();}
        catch (InvocationTargetException e){e.printStackTrace();}
    }
    return new Rectangle(new Point(0, 0), Toolkit.getDefaultToolkit().getScreenSize());
  }
  
  
  
  
  /**
   * Enables or disables all the components within the specified container.
   * 
   * This is a rather hacky method - it doesn"t work well if there are both
   * enabled and disabled components in the container.
   */
  public static void setContainerEnabled(Container container, boolean enabled){
    Component [] children = container.getComponents();
    for (int i = 0; i < children.length; i++){
      Component child = children[i];
      child.setEnabled(enabled);
      if (child instanceof Container)
        setContainerEnabled((Container)child, enabled);
    }
  }
  

}
/**
 * The utillib library.
 * More information is available at http://www.jinchess.ru/.
 * Copyright (C) 2004 Alexander Maryanovsky.
 * All rights reserved.
 *
 * The utillib library 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 2 of the
 * License, or (at your option) any later version.
 *
 * The utillib library 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 Lesser
 * General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public License
 * along with utillib library; if not, write to the Free Software
 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
 */
 

/**
 * A class which contains various platform specific utilities.
 */
 
 class PlatformUtils{
  
  
  
  /**
   * Returns whether the version of Java we"re running in is higher than or
   * equal to the specified version.
   */
   
  public static boolean isJavaBetterThan(String ver){
    return System.getProperty("java.version").rupareTo(ver) >= 0;
  }
  
  
  
  /**
   * Returns whether we"re running under the old (just in case there"s ever a
   * new one) Microsoft VM.
   */
   
  public static boolean isOldMicrosoftVM(){
    String vendor = System.getProperty("java.vendor");
    return (vendor != null) && vendor.toLowerCase().startsWith("microsoft") && 
           !isJavaBetterThan("1.2");    
  }
  
  
  
  /**
   * Returns whether we"re running under Windows.
   */
   
  public static boolean isWindows(){
    String os = System.getProperty("os.name"); 
    return (os != null) && os.toLowerCase().startsWith("windows");
  }
  
  
  
  /**
   * Returns whether we"re running under Windows 95/98/ME.
   */
   
  public static boolean isOldWindows(){
    String os = System.getProperty("os.name");
    
    return isWindows() && (System.getProperty("os.version").rupareTo("5.0") < 0) &&
                          !os.toLowerCase().startsWith("windows nt");
  }
  
  
  
  /**
   * Returns whether we"re running under Linux.
   */
   
  public static boolean isLinux(){
    String os = System.getProperty("os.name"); 
    return (os != null) && os.toLowerCase().startsWith("linux");
  }
  
  
  
  /**
   * Returns whether we"re running under Mac OS.
   */
   
  public static boolean isMacOS(){
    String os = System.getProperty("os.name");
    return (os != null) && os.toLowerCase().startsWith("mac");
  }
  
  
  
  /**
   * Returns whether we"re running under Mac OS X.
   */
   
  public static boolean isMacOSX(){
    String os = System.getProperty("os.name");
    return (os != null) && os.toLowerCase().startsWith("mac os x");
  }
  
  
  
  /**
   * Returns whether we"re running under Solaris.
   */
   
  public static boolean isSolaris(){
    String os = System.getProperty("os.name");
    
    return (os != null) && (os.toLowerCase().startsWith("solaris") ||
                            os.toLowerCase().startsWith("sunos"));
  }
  
  
  
  /**
   * Returns the name of the OS we"re running on, out of the specified list:
   * <ul>
   *   <li>windows
   *   <li>linux
   *   <li>macosx
   *   <li>solaris
   * </ul>
   * 
   * Returns <code>null</code> if we"re running on an OS which is not in the
   * above list.
   */
  
  public static String getOSName(){
    if (isWindows() || isOldWindows())
      return "windows";
    else if (isLinux())
      return "linux";
    else if (isMacOSX())
      return "macosx";
    else if (isSolaris())
      return "solaris";
    else
      return null;
  }
  
  
   
}





Calculates preferred max height for the given components without checking isVisible

   
import java.awt.ruponent;
/**
 * Copyright (C) 2004 NNL Technology AB
 * Visit www.infonode.net for information about InfoNode(R) 
 * products and how to contact NNL Technology AB.
 *
 * This program is free software; you can redistribute it and/or
 * modify it under the terms of the GNU General Public License
 * as published by the Free Software Foundation; either version 2
 * 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 Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, write to the Free Software
 * Foundation, Inc., 59 Temple Place - Suite 330, Boston, 
 * MA 02111-1307, USA.
 */

// $Id: ComponentUtil.java,v 1.25 2005/12/04 13:46:04 jesper Exp $

public class Util {
  /**
   * Calculates preferred max height for the given components without checking
   * isVisible.
   *
   * @param components Components to check
   * @return max height
   */
  public static int getPreferredMaxHeight(Component[] components) {
    int height = 0;
    for (int i = 0; i < components.length; i++) {
      int k = (int) components[i].getPreferredSize().getHeight();
      if (k > height)
        height = k;
    }
    return height;
  }
}





Calculates preferred max width for the given components without checking isVisible

   
import java.awt.ruponent;
/**
 * Copyright (C) 2004 NNL Technology AB
 * Visit www.infonode.net for information about InfoNode(R) 
 * products and how to contact NNL Technology AB.
 *
 * This program is free software; you can redistribute it and/or
 * modify it under the terms of the GNU General Public License
 * as published by the Free Software Foundation; either version 2
 * 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 Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, write to the Free Software
 * Foundation, Inc., 59 Temple Place - Suite 330, Boston, 
 * MA 02111-1307, USA.
 */

// $Id: ComponentUtil.java,v 1.25 2005/12/04 13:46:04 jesper Exp $

public class Util {
  /**
   * Calculates preferred max width for the given components without checking
   * isVisible.
   *
   * @param components Components to check
   * @return max width
   */
  public static int getPreferredMaxWidth(Component[] components) {
    int width = 0;
    for (int i = 0; i < components.length; i++) {
      int k = (int) components[i].getPreferredSize().getWidth();
      if (k > width)
        width = k;
    }
    return width;
  }
}





Center On Screen

   
/***
 * Image/J Plugins
 * Copyright (C) 2002-2004 Jarek Sacha
 *
 * This library 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 2.1 of the License, or (at your option) any later version.
 *
 * This library 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
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
 * License along with this library; if not, write to the Free Software
 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
 *
 * Latest release available at http://sourceforge.net/projects/ij-plugins/
 */
import java.awt.*;
/**
 * @author Jarek Sacha
 * @version $Revision: 1.2 $
 */
public class SwingUtils {
    public static void centerOnScreen(Window window, boolean packFrame) {
        //Validate frames that have preset sizes
        //Pack frames that have useful preferred size info, e.g. from their layout
        if (packFrame) {
            window.pack();
        } else {
            window.validate();
        }
        //Center the frame window
        Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
        Dimension frameSize = window.getSize();
        if (frameSize.height > screenSize.height) {
            frameSize.height = screenSize.height;
        }
        if (frameSize.width > screenSize.width) {
            frameSize.width = screenSize.width;
        }
        window.setLocation((screenSize.width - frameSize.width) / 2,
                (screenSize.height - frameSize.height) / 2);
    }
}





Center window

   
/*
 * Copyright (c) 1998-2002 Carnegie Mellon University.  All rights
 * reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 *
 * 1. Redistributions of source code must retain the above copyright
 *    notice, this list of conditions and the following disclaimer.
 *
 * 2. 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.
 *
 * THIS SOFTWARE IS PROVIDED BY CARNEGIE MELLON UNIVERSITY ``AS IS"" AND
 * ANY EXPRESSED 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 CARNEGIE MELLON UNIVERSITY
 * NOR ITS EMPLOYEES 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.
 *
 */

import java.awt.*;
public abstract class Win {
    public static void center (Window window, Component ref) {
        position (window, ref, 0.5, 0.5);
    }
    public static void position (Window frame, Component ref, 
                                 double xfrac, double yfrac) {
        Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
        Dimension size = frame.getSize();
        Dimension refSize = (ref != null) 
            ? ref.getSize() 
            : screenSize;
        Point origin = (ref != null)
            ? ref.getLocationOnScreen () 
            : new Point (0, 0);
        int x = origin.x + relativePoint (xfrac, refSize.width, size.width);
        int y = origin.y + relativePoint (yfrac, refSize.height, size.height);
        // make sure frame is entirely on screen
        x = Math.max (0, Math.min (screenSize.width - size.width, x));
        y = Math.max (0, Math.min (screenSize.height - size.height, y));
        
        frame.setLocation (x, y);
    }
    static int relativePoint (double frac, int parentLength, int childLength) {
        if (frac < 0)
            return (int) (frac * childLength);
        else if (frac > 1)
            return (int) (parentLength + (frac - 2) * childLength);
        else
            return (int) (frac * (parentLength - childLength));
    }

    public static Frame findFrame (Component comp) {
        for (; comp!=null; comp = comp.getParent ())
            if (comp instanceof Frame) {
                return (Frame)comp;
            }
        return null;
    }
    public static Frame findFrameOrMakeFrame (Component parent) {
        return (parent != null) ? findFrame (parent) : new Frame ();
    }
        
}





Center Within Parent

   
/*
 * Copyright (C) 2001-2004 Colin Bell
 * colbell@users.sourceforge.net
 *
 * This library 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 2.1 of the License, or (at your option) any later version.
 *
 * This library 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
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
 * License along with this library; if not, write to the Free Software
 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
 */

import java.awt.ruponent;
import java.awt.Container;
import java.awt.Dimension;
import java.awt.FontMetrics;
import java.awt.Frame;
import java.awt.GraphicsConfiguration;
import java.awt.GraphicsDevice;
import java.awt.GraphicsEnvironment;
import java.awt.Insets;
import java.awt.Point;
import java.awt.Rectangle;
import java.awt.Toolkit;
import java.awt.Window;
import java.awt.geom.Rectangle2D;
import java.beans.PropertyVetoException;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JInternalFrame;
import javax.swing.SwingUtilities;
/**
 * Common GUI utilities accessed via static methods.
 * 
 * @author 
 */
public class GUIUtils {
  private static JFrame _mainFrame;
  /**
   * Centers <CODE>wind</CODE> within its parent. If it has no parent then
   * center within the screen. If centering would cause the title bar to go
   * above the parent (I.E. cannot see the titlebar and so cannot move the
   * window) then move the window down.
   * 
   * @param wind
   *          The Window to be centered.
   * 
   * @throws IllegalArgumentException
   *           If <TT>wind</TT> is <TT>null</TT>.
   */
  public static void centerWithinParent(Window wind) {
    if (wind == null) {
      throw new IllegalArgumentException("null Window passed");
    }
    final Container parent = wind.getParent();
    if (parent != null && parent.isVisible()) {
      center(wind, new Rectangle(parent.getLocationOnScreen(), parent.getSize()));
    } else {
      centerWithinScreen(wind);
    }
  }
  /**
   * Centers passed internal frame within its desktop area. If centering would
   * cause the title bar to go off the top of the screen then move the window
   * down.
   * 
   * @param frame
   *          The internal frame to be centered.
   * 
   * @throws IllegalArgumentException
   *           If <TT>frame</TT> is <TT>null</TT>.
   */
  public static void centerWithinDesktop(JInternalFrame frame) {
    if (frame == null) {
      throw new IllegalArgumentException("null JInternalFrame passed");
    }
    final Container parent = frame.getDesktopPane();
    if (parent != null && parent.isVisible()) {
      center(frame, new Rectangle(new Point(0, 0), parent.getSize()));
    }
  }
  /**
   * Centers <CODE>wind</CODE> within the screen. If centering would cause the
   * title bar to go off the top of the screen then move the window down.
   * 
   * @param wind
   *          The Window to be centered.
   * 
   * @throws IllegalArgumentException
   *           If <TT>wind</TT> is <TT>null</TT>.
   */
  public static void centerWithinScreen(Window wind) {
    if (wind == null) {
      throw new IllegalArgumentException("null Window passed");
    }
    final Toolkit toolKit = Toolkit.getDefaultToolkit();
    final Rectangle rcScreen = new Rectangle(toolKit.getScreenSize());
    final Dimension windSize = wind.getSize();
    final Dimension parentSize = new Dimension(rcScreen.width, rcScreen.height);
    if (windSize.height > parentSize.height) {
      windSize.height = parentSize.height;
    }
    if (windSize.width > parentSize.width) {
      windSize.width = parentSize.width;
    }
    center(wind, rcScreen);
  }
  /**
   * Centers <CODE>wind</CODE> within the passed rectangle.
   * 
   * @param wind
   *          The Window to be centered.
   * @param rect
   *          The rectangle (in screen coords) to center <CODE>wind</CODE>
   *          within.
   * 
   * @throws IllegalArgumentException
   *           If <TT>Window</TT> or <TT>Rectangle</TT> is <TT>null</TT>.
   */
  private static void center(Component wind, Rectangle rect) {
    if (wind == null || rect == null) {
      throw new IllegalArgumentException("null Window or Rectangle passed");
    }
    Dimension windSize = wind.getSize();
    int x = ((rect.width - windSize.width) / 2) + rect.x;
    int y = ((rect.height - windSize.height) / 2) + rect.y;
    if (y < rect.y) {
      y = rect.y;
    }
    wind.setLocation(x, y);
  }
}





Computes the center point of the current screen device.

 
/* 
 * JCommon : a free general purpose class library for the Java(tm) platform
 * 
 *
 * (C) Copyright 2000-2005, by Object Refinery Limited and Contributors.
 *
 * Project Info:  http://www.jfree.org/jcommon/index.html
 *
 * This library 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 2.1 of the License, or
 * (at your option) any later version.
 *
 * This library 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 Lesser General Public
 * License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
 * License along with this library; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301,
 * USA.
 *
 * [Java is a trademark or registered trademark of Sun Microsystems, Inc.
 * in the United States and other countries.]
 *
 * ----------------------
 * RefineryUtilities.java
 * ----------------------
 * (C) Copyright 2000-2005, by Object Refinery Limited.
 *
 * Original Author:  David Gilbert (for Object Refinery Limited);
 * Contributor(s):   Jon Iles;
 *
 * $Id: RefineryUtilities.java,v 1.11 2007/11/02 17:50:36 taqua Exp $
 *
 * Changes (from 26-Oct-2001)
 * --------------------------
 * 26-Oct-2001 : Changed package to com.jrefinery.ui.*;
 * 26-Nov-2001 : Changed name to SwingRefinery.java to make it obvious that this is not part of
 *               the Java APIs (DG);
 * 10-Dec-2001 : Changed name (again) to JRefineryUtilities.java (DG);
 * 28-Feb-2002 : Moved system properties classes into com.jrefinery.ui.about (DG);
 * 19-Apr-2002 : Renamed JRefineryUtilities-->RefineryUtilities.  Added drawRotatedString()
 *               method (DG);
 * 21-May-2002 : Changed frame positioning methods to accept Window parameters, as suggested by
 *               Laurence Vanhelsuwe (DG);
 * 27-May-2002 : Added getPointInRectangle method (DG);
 * 26-Jun-2002 : Removed unnecessary imports (DG);
 * 12-Jul-2002 : Added workaround for rotated text (JI);
 * 14-Oct-2002 : Fixed errors reported by Checkstyle (DG);
 * 08-May-2003 : Added a new drawRotatedString() method (DG);
 * 09-May-2003 : Added a drawRotatedShape() method (DG);
 * 10-Jun-2003 : Updated aligned and rotated string methods (DG);
 * 29-Oct-2003 : Added workaround for font alignment in PDF output (DG);
 * 07-Nov-2003 : Added rotateShape() method (DG);
 * 16-Mar-2004 : Moved rotateShape() method to ShapeUtils.java (DG);
 * 07-Apr-2004 : Modified text bounds calculation with TextUtilities.getTextBounds() (DG);
 * 21-May-2004 : Fixed bug 951870 - precision in drawAlignedString() method (DG);
 * 30-Sep-2004 : Deprecated and moved a number of methods to the TextUtilities class (DG);
 * 04-Oct-2004 : Renamed ShapeUtils --> ShapeUtilities (DG);
 * 11-Jan-2005 : Removed deprecated code in preparation for the 1.0.0 release (DG);
 *
 */
import java.awt.Dimension;
import java.awt.GraphicsEnvironment;
import java.awt.Point;
import java.awt.Rectangle;
import java.awt.Toolkit;
import java.lang.reflect.Method;
/**
 *
 *
 * @author David Gilbert
 */
public class Main{
  /**
   * Computes the center point of the current screen device. If this method is called on JDK 1.4, Xinerama-aware
   * results are returned. (See Sun-Bug-ID 4463949 for details).
   *
   * @return the center point of the current screen.
   */
  public static Point getCenterPoint ()
  {
    final GraphicsEnvironment localGraphicsEnvironment = GraphicsEnvironment.getLocalGraphicsEnvironment();
    try
    {
      final Method method = GraphicsEnvironment.class.getMethod("getCenterPoint", (Class[]) null);
      return (Point) method.invoke(localGraphicsEnvironment, (Object[]) null);
    }
    catch(Exception e)
    {
      // ignore ... will fail if this is not a JDK 1.4 ..
    }
    final Dimension s = Toolkit.getDefaultToolkit().getScreenSize();
    return new Point (s.width / 2, s.height / 2);
  }
  /**
   * Computes the maximum bounds of the current screen device. If this method is called on JDK 1.4, Xinerama-aware
   * results are returned. (See Sun-Bug-ID 4463949 for details).
   *
   * @return the maximum bounds of the current screen.
   */
    public static Rectangle getMaximumWindowBounds ()
    {
      final GraphicsEnvironment localGraphicsEnvironment = GraphicsEnvironment.getLocalGraphicsEnvironment();
      try
      {
        final Method method = GraphicsEnvironment.class.getMethod("getMaximumWindowBounds", (Class[]) null);
        return (Rectangle) method.invoke(localGraphicsEnvironment, (Object[]) null);
      }
      catch(Exception e)
      {
        // ignore ... will fail if this is not a JDK 1.4 ..
      }
      final Dimension s = Toolkit.getDefaultToolkit().getScreenSize();
      return new Rectangle (0, 0, s.width, s.height);
    }
}





Computes the maximum bounds of the current screen device. If this method is called on JDK 1.4, Xinerama-aware results are returned.

 
/* 
 * JCommon : a free general purpose class library for the Java(tm) platform
 * 
 *
 * (C) Copyright 2000-2005, by Object Refinery Limited and Contributors.
 *
 * Project Info:  http://www.jfree.org/jcommon/index.html
 *
 * This library 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 2.1 of the License, or
 * (at your option) any later version.
 *
 * This library 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 Lesser General Public
 * License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
 * License along with this library; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301,
 * USA.
 *
 * [Java is a trademark or registered trademark of Sun Microsystems, Inc.
 * in the United States and other countries.]
 *
 * ----------------------
 * RefineryUtilities.java
 * ----------------------
 * (C) Copyright 2000-2005, by Object Refinery Limited.
 *
 * Original Author:  David Gilbert (for Object Refinery Limited);
 * Contributor(s):   Jon Iles;
 *
 * $Id: RefineryUtilities.java,v 1.11 2007/11/02 17:50:36 taqua Exp $
 *
 * Changes (from 26-Oct-2001)
 * --------------------------
 * 26-Oct-2001 : Changed package to com.jrefinery.ui.*;
 * 26-Nov-2001 : Changed name to SwingRefinery.java to make it obvious that this is not part of
 *               the Java APIs (DG);
 * 10-Dec-2001 : Changed name (again) to JRefineryUtilities.java (DG);
 * 28-Feb-2002 : Moved system properties classes into com.jrefinery.ui.about (DG);
 * 19-Apr-2002 : Renamed JRefineryUtilities-->RefineryUtilities.  Added drawRotatedString()
 *               method (DG);
 * 21-May-2002 : Changed frame positioning methods to accept Window parameters, as suggested by
 *               Laurence Vanhelsuwe (DG);
 * 27-May-2002 : Added getPointInRectangle method (DG);
 * 26-Jun-2002 : Removed unnecessary imports (DG);
 * 12-Jul-2002 : Added workaround for rotated text (JI);
 * 14-Oct-2002 : Fixed errors reported by Checkstyle (DG);
 * 08-May-2003 : Added a new drawRotatedString() method (DG);
 * 09-May-2003 : Added a drawRotatedShape() method (DG);
 * 10-Jun-2003 : Updated aligned and rotated string methods (DG);
 * 29-Oct-2003 : Added workaround for font alignment in PDF output (DG);
 * 07-Nov-2003 : Added rotateShape() method (DG);
 * 16-Mar-2004 : Moved rotateShape() method to ShapeUtils.java (DG);
 * 07-Apr-2004 : Modified text bounds calculation with TextUtilities.getTextBounds() (DG);
 * 21-May-2004 : Fixed bug 951870 - precision in drawAlignedString() method (DG);
 * 30-Sep-2004 : Deprecated and moved a number of methods to the TextUtilities class (DG);
 * 04-Oct-2004 : Renamed ShapeUtils --> ShapeUtilities (DG);
 * 11-Jan-2005 : Removed deprecated code in preparation for the 1.0.0 release (DG);
 *
 */
import java.awt.Container;
import java.awt.Dialog;
import java.awt.Dimension;
import java.awt.GraphicsEnvironment;
import java.awt.Rectangle;
import java.awt.Toolkit;
import java.lang.reflect.Method;
/**
 *
 *
 * @author David Gilbert
 */
public class Main{
  /**
   * Positions the specified dialog at a position relative to its parent.
   *
   * @param dialog  the dialog to be positioned.
   * @param horizontalPercent  the relative location.
   * @param verticalPercent  the relative location.
   */
  public static void positionDialogRelativeToParent(final Dialog dialog,
                                                    final double horizontalPercent,
                                                    final double verticalPercent) {
      final Dimension d = dialog.getSize();
      final Container parent = dialog.getParent();
      final Dimension p = parent.getSize();
      final int baseX = parent.getX() - d.width;
      final int baseY = parent.getY() - d.height;
      final int w = d.width + p.width;
      final int h = d.height + p.height;
      int x = baseX + (int) (horizontalPercent * w);
      int y = baseY + (int) (verticalPercent * h);
      // make sure the dialog fits completely on the screen...
      final Rectangle s = getMaximumWindowBounds();
      x = Math.min(x, (s.width - d.width));
      x = Math.max(x, 0);
      y = Math.min(y, (s.height - d.height));
      y = Math.max(y, 0);
      dialog.setBounds(x + s.x, y + s.y, d.width, d.height);
  }
  /**
   * Computes the maximum bounds of the current screen device. If this method is called on JDK 1.4, Xinerama-aware
   * results are returned. (See Sun-Bug-ID 4463949 for details).
   *
   * @return the maximum bounds of the current screen.
   */
    public static Rectangle getMaximumWindowBounds ()
    {
      final GraphicsEnvironment localGraphicsEnvironment = GraphicsEnvironment.getLocalGraphicsEnvironment();
      try
      {
        final Method method = GraphicsEnvironment.class.getMethod("getMaximumWindowBounds", (Class[]) null);
        return (Rectangle) method.invoke(localGraphicsEnvironment, (Object[]) null);
      }
      catch(Exception e)
      {
        // ignore ... will fail if this is not a JDK 1.4 ..
      }
      final Dimension s = Toolkit.getDefaultToolkit().getScreenSize();
      return new Rectangle (0, 0, s.width, s.height);
    }
}





Get Point For Centering

  
/*
 * $Id: WindowUtils.java,v 1.16 2009/05/25 16:37:52 kschaefe Exp $
 *
 * Copyright 2004 Sun Microsystems, Inc., 4150 Network Circle,
 * Santa Clara, California 95054, U.S.A. All rights reserved.
 *
 * This library 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 2.1 of the License, or (at your option) any later version.
 *
 * This library 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
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
 * License along with this library; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA
 */
import java.awt.GraphicsConfiguration;
import java.awt.GraphicsEnvironment;
import java.awt.Insets;
import java.awt.Point;
import java.awt.Rectangle;
import java.awt.Toolkit;
import java.awt.Window;
/**
 * Encapsulates various utilities for windows (ie: <code>Frame</code> and
 * <code>Dialog</code> objects and descendants, in particular).
 *
 * @author Richard Bair
 */
public class Utils {
  public static Point getPointForCentering(Window window) {
    Rectangle usableBounds = getUsableDeviceBounds(window);
    int screenWidth = usableBounds.width;
    int screenHeight = usableBounds.height;
    int width = window.getWidth();
    int height = window.getHeight();
    
    return new Point(((screenWidth - width) / 2) + usableBounds.x,
            ((screenHeight - height) / 2) + usableBounds.y);
}
  /**
   * <p>
   * Returns the <code>Point</code> at which a window should be placed to
   * center that window on the screen.
   * </p>
   * <p>
   * Some thought was taken as to whether to implement a method such as this,
   * or to simply make a method that, given a window, will center it.  It was
   * decided that it is better to not alter an object within a method.
   * </p>
   *
   * @param window The window to calculate the center point for.  This object
   *               can not be null.
   *
   * @return the <code>Point</code> at which the window should be placed to
   *         center that window on the screen.
   */

  private static Rectangle getUsableDeviceBounds(Window window) {
      Window owner = window.getOwner();
      GraphicsConfiguration gc = null;
      
      if (owner == null) {
          gc = GraphicsEnvironment.getLocalGraphicsEnvironment()
                  .getDefaultScreenDevice().getDefaultConfiguration();
      } else {
          gc = owner.getGraphicsConfiguration();
      }
      
      Insets insets = Toolkit.getDefaultToolkit().getScreenInsets(gc);
      Rectangle bounds = gc.getBounds();
      bounds.x += insets.left;
      bounds.y += insets.top;
      bounds.width -= (insets.left + insets.right);
      bounds.height -= (insets.top + insets.bottom);
      
      return bounds;
  }
}





Get Point For Staggering

  
/*
 * $Id: WindowUtils.java,v 1.16 2009/05/25 16:37:52 kschaefe Exp $
 *
 * Copyright 2004 Sun Microsystems, Inc., 4150 Network Circle,
 * Santa Clara, California 95054, U.S.A. All rights reserved.
 *
 * This library 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 2.1 of the License, or (at your option) any later version.
 *
 * This library 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
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
 * License along with this library; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA
 */
import java.awt.Insets;
import java.awt.Point;
import java.awt.Window;
/**
 * Encapsulates various utilities for windows (ie: <code>Frame</code> and
 * <code>Dialog</code> objects and descendants, in particular).
 *
 * @author Richard Bair
 */
public class Utils {
  /**
   * <p/>
   * Returns the <code>Point</code> at which a window should be placed in
   * order to be staggered slightly from another &quot;origin&quot; window to
   * ensure that the title areas of both windows remain visible to the user.
   * </p>
   *
   * @param originWindow Window from which the staggered location will be calculated
   *
   * @return location staggered from the upper left location of the origin
   *         window
   */
  public static Point getPointForStaggering(Window originWindow) {
      Point origin = originWindow.getLocation();
      Insets insets = originWindow.getInsets();
      origin.x += insets.top;
      origin.y += insets.top;
      return origin;
  }
}





Is Focusable

   
import java.applet.Applet;
import java.awt.ruponent;
import java.awt.Container;
import java.awt.Point;
import java.awt.Window;
import java.util.ArrayList;
import javax.swing.RootPaneContainer;
import javax.swing.SwingUtilities;
/**
 * Copyright (C) 2004 NNL Technology AB
 * Visit www.infonode.net for information about InfoNode(R) 
 * products and how to contact NNL Technology AB.
 *
 * This program is free software; you can redistribute it and/or
 * modify it under the terms of the GNU General Public License
 * as published by the Free Software Foundation; either version 2
 * 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 Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, write to the Free Software
 * Foundation, Inc., 59 Temple Place - Suite 330, Boston, 
 * MA 02111-1307, USA.
 */

// $Id: ComponentUtil.java,v 1.25 2005/12/04 13:46:04 jesper Exp $

public class Util {
  public static boolean isFocusable(Component c) {
    return c.isFocusable() && c.isDisplayable() && c.isVisible() && c.isEnabled();
  }
}





Loading the given image

   
/**
 * The utillib library.
 * More information is available at http://www.jinchess.ru/.
 * Copyright (C) 2002 Alexander Maryanovsky.
 * All rights reserved.
 *
 * The utillib library 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 2 of the
 * License, or (at your option) any later version.
 *
 * The utillib library 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 Lesser
 * General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public License
 * along with utillib library; if not, write to the Free Software
 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
 */

import java.awt.Image;
import java.awt.Toolkit;
import java.awt.image.ImageObserver;

/**
 * Various image related utilities.
 */
public class ImageUtilities{

  /**
   * A constant indicating that the loading of the image completed.
   */
  public static final int COMPLETE = 1;

  /**
   * A constant indicating that the loading of the image errored.
   */
  public static final int ERRORED = 2;

  /**
   * A constant indicating that the loading of the image was aborted.
   */
  public static final int ABORTED = 3;

  
  /**
   * A constant indicating that the loading of the image was interrupted.
   */
  public static final int INTERRUPTED = 4;
  
  /**
   * Starts loading the given image, returns only when it"s done loading.
   * Note that it"s much more efficient to preload a lot of images at once using
   * the preload(Image []) method instead of this one.
   *
   * @return The result of the image loading, either {@link #COMPLETE},
   * {@link #ERRORED}, {@link #ABORTED} or {@link #INTERRUPTED}.
   *
   * @see #preload(java.awt.Image [], int [])
   */
  public static int preload(Image image){
    Toolkit toolkit = Toolkit.getDefaultToolkit();
    
    // Check if already loaded
    if ((toolkit.checkImage(image, -1, -1, null) & ImageObserver.ALLBITS) != 0)
      return COMPLETE;
    
    Object lock = new Object();
    synchronized(lock){
      while (true){
        ImageLoadObserver observer = new ImageLoadObserver(lock);
        toolkit.prepareImage(image, -1, -1, observer);
        int result = toolkit.checkImage(image, -1, -1, null);
        if ((result & ImageObserver.ALLBITS) != 0)
          return COMPLETE;
        if ((result & ImageObserver.ERROR) != 0)
          return ERRORED;
        if ((result & ImageObserver.ABORT) != 0)
          return ABORTED;
        
        try{
          lock.wait();
          return observer.getResult();
        } catch (InterruptedException e){
            return INTERRUPTED;
          }
      }
    }
  }

  /**
   * Starts loading the given images, returns only when all the images are done
   * loading. If you just need to preload one Image, use the preload(Image) method
   * instead.
   *
   * @return An array specifying the loading result of each image. Possible values
   * are {@link #COMPLETE}, {@link #ERRORED} and {@link #ABORTED}.
   *
   * @see #preload(Image)
   */
  public static int [] preload(Image [] images, int [] results){
    Object [] locks = new Object[images.length];
    ImageLoadObserver [] loadObservers = new ImageLoadObserver[images.length];
    if ((results == null) || (results.length < images.length))
      results = new int[images.length];
    Toolkit toolkit = Toolkit.getDefaultToolkit();
    for (int i = 0; i < images.length; i++){
      locks[i] = new Object();
      loadObservers[i] = new ImageLoadObserver(locks[i]);
      toolkit.prepareImage(images[i], -1, -1, loadObservers[i]);
    }
    for (int i = 0; i < images.length; i++){
      synchronized(locks[i]){
        int result = toolkit.checkImage(images[i], -1, -1, null);
        if ((result & ImageObserver.ALLBITS) != 0){
          results[i] = COMPLETE;
          continue;
        }
        if ((result & ImageObserver.ERROR) != 0){
          results[i] = ERRORED;
          continue;
        }
        if ((result & ImageObserver.ABORT) != 0){
          results[i] = ABORTED;
          continue;
        }
        
        try{
          locks[i].wait();
          results[i] = loadObservers[i].getResult();
        } catch (InterruptedException e){
            results[i] = INTERRUPTED;
          }
      }
    }
    
    return results;
  }
  
  
  
  /**
   * Returns whether the specified image is already fully loaded.
   */
  
  public static boolean isLoaded(Image image){
    return (Toolkit.getDefaultToolkit().checkImage(image, -1, -1, null) & ImageObserver.ALLBITS) != 0;
  }
  
  
  
  /**
   * This class is an implementation of ImageObserver which notifies a given
   * lock when loading of the Image is done. This can be used to wait until a
   * certain Image has finished loading.
   */
  public static class ImageLoadObserver implements ImageObserver{

    /**
     * The lock.
     */
    private final Object lock;

    /**
     * The loading result.
     */
    private int result = -1;


    /**
     * Creates a new ImageLoadObserver which will notify the given lock when
     * the Image is done loading.
     */
    public ImageLoadObserver(Object lock){
      this.lock = lock;
    }

    /**
     * If infoflags has the ALLBITS flag set, notifies the lock and returns
     * false, otherwise simply returns true.
     */
    public boolean imageUpdate(Image img, int infoflags, int x, int y, int width, int height){
      synchronized(lock){
        if ((infoflags & ALLBITS)!=0){
          result = ImageUtilities.ruPLETE;
          lock.notify();
          return false;
        }
        if ((infoflags & ERROR)!=0){
          result = ImageUtilities.ERRORED;
          lock.notify();
          return false;
        }
        if ((infoflags & ABORT)!=0){
          result = ImageUtilities.ABORTED;
          lock.notify();
          return false;
        }
      }
      return true;
    }


    /**
     * Returns the result of the image loading process or -1 if loading hasn"t finished yet.
     * Possible values are {@link ImageUtilities#COMPLETE}, {@link ImageUtilities#ERRORED}
     * and {@link ImageUtilities#ABORTED}
     */
    public int getResult(){
      return result;
    }
  }
 
}





Positions the specified dialog at a position relative to its parent.

 
/* 
 * JCommon : a free general purpose class library for the Java(tm) platform
 * 
 *
 * (C) Copyright 2000-2005, by Object Refinery Limited and Contributors.
 *
 * Project Info:  http://www.jfree.org/jcommon/index.html
 *
 * This library 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 2.1 of the License, or
 * (at your option) any later version.
 *
 * This library 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 Lesser General Public
 * License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
 * License along with this library; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301,
 * USA.
 *
 * [Java is a trademark or registered trademark of Sun Microsystems, Inc.
 * in the United States and other countries.]
 *
 * ----------------------
 * RefineryUtilities.java
 * ----------------------
 * (C) Copyright 2000-2005, by Object Refinery Limited.
 *
 * Original Author:  David Gilbert (for Object Refinery Limited);
 * Contributor(s):   Jon Iles;
 *
 * $Id: RefineryUtilities.java,v 1.11 2007/11/02 17:50:36 taqua Exp $
 *
 * Changes (from 26-Oct-2001)
 * --------------------------
 * 26-Oct-2001 : Changed package to com.jrefinery.ui.*;
 * 26-Nov-2001 : Changed name to SwingRefinery.java to make it obvious that this is not part of
 *               the Java APIs (DG);
 * 10-Dec-2001 : Changed name (again) to JRefineryUtilities.java (DG);
 * 28-Feb-2002 : Moved system properties classes into com.jrefinery.ui.about (DG);
 * 19-Apr-2002 : Renamed JRefineryUtilities-->RefineryUtilities.  Added drawRotatedString()
 *               method (DG);
 * 21-May-2002 : Changed frame positioning methods to accept Window parameters, as suggested by
 *               Laurence Vanhelsuwe (DG);
 * 27-May-2002 : Added getPointInRectangle method (DG);
 * 26-Jun-2002 : Removed unnecessary imports (DG);
 * 12-Jul-2002 : Added workaround for rotated text (JI);
 * 14-Oct-2002 : Fixed errors reported by Checkstyle (DG);
 * 08-May-2003 : Added a new drawRotatedString() method (DG);
 * 09-May-2003 : Added a drawRotatedShape() method (DG);
 * 10-Jun-2003 : Updated aligned and rotated string methods (DG);
 * 29-Oct-2003 : Added workaround for font alignment in PDF output (DG);
 * 07-Nov-2003 : Added rotateShape() method (DG);
 * 16-Mar-2004 : Moved rotateShape() method to ShapeUtils.java (DG);
 * 07-Apr-2004 : Modified text bounds calculation with TextUtilities.getTextBounds() (DG);
 * 21-May-2004 : Fixed bug 951870 - precision in drawAlignedString() method (DG);
 * 30-Sep-2004 : Deprecated and moved a number of methods to the TextUtilities class (DG);
 * 04-Oct-2004 : Renamed ShapeUtils --> ShapeUtilities (DG);
 * 11-Jan-2005 : Removed deprecated code in preparation for the 1.0.0 release (DG);
 *
 */
import java.awt.Container;
import java.awt.Dialog;
import java.awt.Dimension;
import java.awt.GraphicsEnvironment;
import java.awt.Rectangle;
import java.awt.Toolkit;
import java.lang.reflect.Method;
/**
 *
 *
 * @author David Gilbert
 */
public class Main{
  /**
   * Positions the specified dialog at a position relative to its parent.
   *
   * @param dialog  the dialog to be positioned.
   * @param horizontalPercent  the relative location.
   * @param verticalPercent  the relative location.
   */
  public static void positionDialogRelativeToParent(final Dialog dialog,
                                                    final double horizontalPercent,
                                                    final double verticalPercent) {
      final Dimension d = dialog.getSize();
      final Container parent = dialog.getParent();
      final Dimension p = parent.getSize();
      final int baseX = parent.getX() - d.width;
      final int baseY = parent.getY() - d.height;
      final int w = d.width + p.width;
      final int h = d.height + p.height;
      int x = baseX + (int) (horizontalPercent * w);
      int y = baseY + (int) (verticalPercent * h);
      // make sure the dialog fits completely on the screen...
      final Rectangle s = getMaximumWindowBounds();
      x = Math.min(x, (s.width - d.width));
      x = Math.max(x, 0);
      y = Math.min(y, (s.height - d.height));
      y = Math.max(y, 0);
      dialog.setBounds(x + s.x, y + s.y, d.width, d.height);
  }
  /**
   * Computes the maximum bounds of the current screen device. If this method is called on JDK 1.4, Xinerama-aware
   * results are returned. (See Sun-Bug-ID 4463949 for details).
   *
   * @return the maximum bounds of the current screen.
   */
    public static Rectangle getMaximumWindowBounds ()
    {
      final GraphicsEnvironment localGraphicsEnvironment = GraphicsEnvironment.getLocalGraphicsEnvironment();
      try
      {
        final Method method = GraphicsEnvironment.class.getMethod("getMaximumWindowBounds", (Class[]) null);
        return (Rectangle) method.invoke(localGraphicsEnvironment, (Object[]) null);
      }
      catch(Exception e)
      {
        // ignore ... will fail if this is not a JDK 1.4 ..
      }
      final Dimension s = Toolkit.getDefaultToolkit().getScreenSize();
      return new Rectangle (0, 0, s.width, s.height);
    }
}





Positions the specified frame at a random location on the screen while ensuring that the

 
entire frame is visible (provided that the frame is smaller than the screen).
/* 
 * JCommon : a free general purpose class library for the Java(tm) platform
 * 
 *
 * (C) Copyright 2000-2005, by Object Refinery Limited and Contributors.
 *
 * Project Info:  http://www.jfree.org/jcommon/index.html
 *
 * This library 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 2.1 of the License, or
 * (at your option) any later version.
 *
 * This library 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 Lesser General Public
 * License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
 * License along with this library; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301,
 * USA.
 *
 * [Java is a trademark or registered trademark of Sun Microsystems, Inc.
 * in the United States and other countries.]
 *
 * ----------------------
 * RefineryUtilities.java
 * ----------------------
 * (C) Copyright 2000-2005, by Object Refinery Limited.
 *
 * Original Author:  David Gilbert (for Object Refinery Limited);
 * Contributor(s):   Jon Iles;
 *
 * $Id: RefineryUtilities.java,v 1.11 2007/11/02 17:50:36 taqua Exp $
 *
 * Changes (from 26-Oct-2001)
 * --------------------------
 * 26-Oct-2001 : Changed package to com.jrefinery.ui.*;
 * 26-Nov-2001 : Changed name to SwingRefinery.java to make it obvious that this is not part of
 *               the Java APIs (DG);
 * 10-Dec-2001 : Changed name (again) to JRefineryUtilities.java (DG);
 * 28-Feb-2002 : Moved system properties classes into com.jrefinery.ui.about (DG);
 * 19-Apr-2002 : Renamed JRefineryUtilities-->RefineryUtilities.  Added drawRotatedString()
 *               method (DG);
 * 21-May-2002 : Changed frame positioning methods to accept Window parameters, as suggested by
 *               Laurence Vanhelsuwe (DG);
 * 27-May-2002 : Added getPointInRectangle method (DG);
 * 26-Jun-2002 : Removed unnecessary imports (DG);
 * 12-Jul-2002 : Added workaround for rotated text (JI);
 * 14-Oct-2002 : Fixed errors reported by Checkstyle (DG);
 * 08-May-2003 : Added a new drawRotatedString() method (DG);
 * 09-May-2003 : Added a drawRotatedShape() method (DG);
 * 10-Jun-2003 : Updated aligned and rotated string methods (DG);
 * 29-Oct-2003 : Added workaround for font alignment in PDF output (DG);
 * 07-Nov-2003 : Added rotateShape() method (DG);
 * 16-Mar-2004 : Moved rotateShape() method to ShapeUtils.java (DG);
 * 07-Apr-2004 : Modified text bounds calculation with TextUtilities.getTextBounds() (DG);
 * 21-May-2004 : Fixed bug 951870 - precision in drawAlignedString() method (DG);
 * 30-Sep-2004 : Deprecated and moved a number of methods to the TextUtilities class (DG);
 * 04-Oct-2004 : Renamed ShapeUtils --> ShapeUtilities (DG);
 * 11-Jan-2005 : Removed deprecated code in preparation for the 1.0.0 release (DG);
 *
 */
import java.awt.Dimension;
import java.awt.GraphicsEnvironment;
import java.awt.Rectangle;
import java.awt.Toolkit;
import java.awt.Window;
import java.lang.reflect.Method;
/**
 * 
 * 
 * @author David Gilbert
 */
public class Main {
  /**
   * Positions the specified frame at a random location on the screen while ensuring that the
   * entire frame is visible (provided that the frame is smaller than the screen).
   *
   * @param frame  the frame.
   */
  public static void positionFrameRandomly(final Window frame) {
      positionFrameOnScreen(frame, Math.random(), Math.random());
  }
  /**
   * Positions the specified frame at a relative position in the screen, where
   * 50% is considered to be the center of the screen.
   * 
   * @param frame
   *          the frame.
   * @param horizontalPercent
   *          the relative horizontal position of the frame (0.0 to 1.0, where
   *          0.5 is the center of the screen).
   * @param verticalPercent
   *          the relative vertical position of the frame (0.0 to 1.0, where 0.5
   *          is the center of the screen).
   */
  public static void positionFrameOnScreen(final Window frame, final double horizontalPercent,
      final double verticalPercent) {
    final Rectangle s = getMaximumWindowBounds();
    final Dimension f = frame.getSize();
    final int w = Math.max(s.width - f.width, 0);
    final int h = Math.max(s.height - f.height, 0);
    final int x = (int) (horizontalPercent * w) + s.x;
    final int y = (int) (verticalPercent * h) + s.y;
    frame.setBounds(x, y, f.width, f.height);
  }
  /**
   * Computes the maximum bounds of the current screen device. If this method is
   * called on JDK 1.4, Xinerama-aware results are returned. (See Sun-Bug-ID
   * 4463949 for details).
   * 
   * @return the maximum bounds of the current screen.
   */
  public static Rectangle getMaximumWindowBounds() {
    final GraphicsEnvironment localGraphicsEnvironment = GraphicsEnvironment
        .getLocalGraphicsEnvironment();
    try {
      final Method method = GraphicsEnvironment.class.getMethod("getMaximumWindowBounds",
          (Class[]) null);
      return (Rectangle) method.invoke(localGraphicsEnvironment, (Object[]) null);
    } catch (Exception e) {
      // ignore ... will fail if this is not a JDK 1.4 ..
    }
    final Dimension s = Toolkit.getDefaultToolkit().getScreenSize();
    return new Rectangle(0, 0, s.width, s.height);
  }
}





Positions the specified frame at a relative position in the screen, where 50% is considered to be the center of the screen.

 
/* 
 * JCommon : a free general purpose class library for the Java(tm) platform
 * 
 *
 * (C) Copyright 2000-2005, by Object Refinery Limited and Contributors.
 *
 * Project Info:  http://www.jfree.org/jcommon/index.html
 *
 * This library 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 2.1 of the License, or
 * (at your option) any later version.
 *
 * This library 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 Lesser General Public
 * License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
 * License along with this library; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301,
 * USA.
 *
 * [Java is a trademark or registered trademark of Sun Microsystems, Inc.
 * in the United States and other countries.]
 *
 * ----------------------
 * RefineryUtilities.java
 * ----------------------
 * (C) Copyright 2000-2005, by Object Refinery Limited.
 *
 * Original Author:  David Gilbert (for Object Refinery Limited);
 * Contributor(s):   Jon Iles;
 *
 * $Id: RefineryUtilities.java,v 1.11 2007/11/02 17:50:36 taqua Exp $
 *
 * Changes (from 26-Oct-2001)
 * --------------------------
 * 26-Oct-2001 : Changed package to com.jrefinery.ui.*;
 * 26-Nov-2001 : Changed name to SwingRefinery.java to make it obvious that this is not part of
 *               the Java APIs (DG);
 * 10-Dec-2001 : Changed name (again) to JRefineryUtilities.java (DG);
 * 28-Feb-2002 : Moved system properties classes into com.jrefinery.ui.about (DG);
 * 19-Apr-2002 : Renamed JRefineryUtilities-->RefineryUtilities.  Added drawRotatedString()
 *               method (DG);
 * 21-May-2002 : Changed frame positioning methods to accept Window parameters, as suggested by
 *               Laurence Vanhelsuwe (DG);
 * 27-May-2002 : Added getPointInRectangle method (DG);
 * 26-Jun-2002 : Removed unnecessary imports (DG);
 * 12-Jul-2002 : Added workaround for rotated text (JI);
 * 14-Oct-2002 : Fixed errors reported by Checkstyle (DG);
 * 08-May-2003 : Added a new drawRotatedString() method (DG);
 * 09-May-2003 : Added a drawRotatedShape() method (DG);
 * 10-Jun-2003 : Updated aligned and rotated string methods (DG);
 * 29-Oct-2003 : Added workaround for font alignment in PDF output (DG);
 * 07-Nov-2003 : Added rotateShape() method (DG);
 * 16-Mar-2004 : Moved rotateShape() method to ShapeUtils.java (DG);
 * 07-Apr-2004 : Modified text bounds calculation with TextUtilities.getTextBounds() (DG);
 * 21-May-2004 : Fixed bug 951870 - precision in drawAlignedString() method (DG);
 * 30-Sep-2004 : Deprecated and moved a number of methods to the TextUtilities class (DG);
 * 04-Oct-2004 : Renamed ShapeUtils --> ShapeUtilities (DG);
 * 11-Jan-2005 : Removed deprecated code in preparation for the 1.0.0 release (DG);
 *
 */
import java.awt.Dimension;
import java.awt.GraphicsEnvironment;
import java.awt.Rectangle;
import java.awt.Toolkit;
import java.awt.Window;
import java.lang.reflect.Method;
/**
 * 
 * 
 * @author David Gilbert
 */
public class Main {
  /**
   * Positions the specified frame at a relative position in the screen, where
   * 50% is considered to be the center of the screen.
   * 
   * @param frame
   *          the frame.
   * @param horizontalPercent
   *          the relative horizontal position of the frame (0.0 to 1.0, where
   *          0.5 is the center of the screen).
   * @param verticalPercent
   *          the relative vertical position of the frame (0.0 to 1.0, where 0.5
   *          is the center of the screen).
   */
  public static void positionFrameOnScreen(final Window frame, final double horizontalPercent,
      final double verticalPercent) {
    final Rectangle s = getMaximumWindowBounds();
    final Dimension f = frame.getSize();
    final int w = Math.max(s.width - f.width, 0);
    final int h = Math.max(s.height - f.height, 0);
    final int x = (int) (horizontalPercent * w) + s.x;
    final int y = (int) (verticalPercent * h) + s.y;
    frame.setBounds(x, y, f.width, f.height);
  }
  /**
   * Computes the maximum bounds of the current screen device. If this method is
   * called on JDK 1.4, Xinerama-aware results are returned. (See Sun-Bug-ID
   * 4463949 for details).
   * 
   * @return the maximum bounds of the current screen.
   */
  public static Rectangle getMaximumWindowBounds() {
    final GraphicsEnvironment localGraphicsEnvironment = GraphicsEnvironment
        .getLocalGraphicsEnvironment();
    try {
      final Method method = GraphicsEnvironment.class.getMethod("getMaximumWindowBounds",
          (Class[]) null);
      return (Rectangle) method.invoke(localGraphicsEnvironment, (Object[]) null);
    } catch (Exception e) {
      // ignore ... will fail if this is not a JDK 1.4 ..
    }
    final Dimension s = Toolkit.getDefaultToolkit().getScreenSize();
    return new Rectangle(0, 0, s.width, s.height);
  }
}





Positions the specified frame in the middle of the screen.

 
/* 
 * JCommon : a free general purpose class library for the Java(tm) platform
 * 
 *
 * (C) Copyright 2000-2005, by Object Refinery Limited and Contributors.
 *
 * Project Info:  http://www.jfree.org/jcommon/index.html
 *
 * This library 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 2.1 of the License, or
 * (at your option) any later version.
 *
 * This library 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 Lesser General Public
 * License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
 * License along with this library; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301,
 * USA.
 *
 * [Java is a trademark or registered trademark of Sun Microsystems, Inc.
 * in the United States and other countries.]
 *
 * ----------------------
 * RefineryUtilities.java
 * ----------------------
 * (C) Copyright 2000-2005, by Object Refinery Limited.
 *
 * Original Author:  David Gilbert (for Object Refinery Limited);
 * Contributor(s):   Jon Iles;
 *
 * $Id: RefineryUtilities.java,v 1.11 2007/11/02 17:50:36 taqua Exp $
 *
 * Changes (from 26-Oct-2001)
 * --------------------------
 * 26-Oct-2001 : Changed package to com.jrefinery.ui.*;
 * 26-Nov-2001 : Changed name to SwingRefinery.java to make it obvious that this is not part of
 *               the Java APIs (DG);
 * 10-Dec-2001 : Changed name (again) to JRefineryUtilities.java (DG);
 * 28-Feb-2002 : Moved system properties classes into com.jrefinery.ui.about (DG);
 * 19-Apr-2002 : Renamed JRefineryUtilities-->RefineryUtilities.  Added drawRotatedString()
 *               method (DG);
 * 21-May-2002 : Changed frame positioning methods to accept Window parameters, as suggested by
 *               Laurence Vanhelsuwe (DG);
 * 27-May-2002 : Added getPointInRectangle method (DG);
 * 26-Jun-2002 : Removed unnecessary imports (DG);
 * 12-Jul-2002 : Added workaround for rotated text (JI);
 * 14-Oct-2002 : Fixed errors reported by Checkstyle (DG);
 * 08-May-2003 : Added a new drawRotatedString() method (DG);
 * 09-May-2003 : Added a drawRotatedShape() method (DG);
 * 10-Jun-2003 : Updated aligned and rotated string methods (DG);
 * 29-Oct-2003 : Added workaround for font alignment in PDF output (DG);
 * 07-Nov-2003 : Added rotateShape() method (DG);
 * 16-Mar-2004 : Moved rotateShape() method to ShapeUtils.java (DG);
 * 07-Apr-2004 : Modified text bounds calculation with TextUtilities.getTextBounds() (DG);
 * 21-May-2004 : Fixed bug 951870 - precision in drawAlignedString() method (DG);
 * 30-Sep-2004 : Deprecated and moved a number of methods to the TextUtilities class (DG);
 * 04-Oct-2004 : Renamed ShapeUtils --> ShapeUtilities (DG);
 * 11-Jan-2005 : Removed deprecated code in preparation for the 1.0.0 release (DG);
 *
 */
import java.awt.Dimension;
import java.awt.GraphicsEnvironment;
import java.awt.Rectangle;
import java.awt.Toolkit;
import java.awt.Window;
import java.lang.reflect.Method;
/**
 * 
 * 
 * @author David Gilbert
 */
public class Main {
  /**
   * Positions the specified frame in the middle of the screen.
   *
   * @param frame  the frame to be centered on the screen.
   */
  public static void centerFrameOnScreen(final Window frame) {
      positionFrameOnScreen(frame, 0.5, 0.5);
  }
  /**
   * Positions the specified frame at a relative position in the screen, where
   * 50% is considered to be the center of the screen.
   * 
   * @param frame
   *          the frame.
   * @param horizontalPercent
   *          the relative horizontal position of the frame (0.0 to 1.0, where
   *          0.5 is the center of the screen).
   * @param verticalPercent
   *          the relative vertical position of the frame (0.0 to 1.0, where 0.5
   *          is the center of the screen).
   */
  public static void positionFrameOnScreen(final Window frame, final double horizontalPercent,
      final double verticalPercent) {
    final Rectangle s = getMaximumWindowBounds();
    final Dimension f = frame.getSize();
    final int w = Math.max(s.width - f.width, 0);
    final int h = Math.max(s.height - f.height, 0);
    final int x = (int) (horizontalPercent * w) + s.x;
    final int y = (int) (verticalPercent * h) + s.y;
    frame.setBounds(x, y, f.width, f.height);
  }
  /**
   * Computes the maximum bounds of the current screen device. If this method is
   * called on JDK 1.4, Xinerama-aware results are returned. (See Sun-Bug-ID
   * 4463949 for details).
   * 
   * @return the maximum bounds of the current screen.
   */
  public static Rectangle getMaximumWindowBounds() {
    final GraphicsEnvironment localGraphicsEnvironment = GraphicsEnvironment
        .getLocalGraphicsEnvironment();
    try {
      final Method method = GraphicsEnvironment.class.getMethod("getMaximumWindowBounds",
          (Class[]) null);
      return (Rectangle) method.invoke(localGraphicsEnvironment, (Object[]) null);
    } catch (Exception e) {
      // ignore ... will fail if this is not a JDK 1.4 ..
    }
    final Dimension s = Toolkit.getDefaultToolkit().getScreenSize();
    return new Rectangle(0, 0, s.width, s.height);
  }
}





Press a key pragmatically

   

import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
public class KeyUtils {
  public static void pressKey(Component component ) {
    if (component.getKeyListeners().length > 0) {
      KeyEvent event = new KeyEvent(component, KeyEvent.KEY_PRESSED, 0, 1, 32, (char)32);
      for (int i = 0; i < component.getKeyListeners().length; i++) {
        KeyListener keyListener = component.getKeyListeners()[i];
        keyListener.keyPressed(event);
      }
    }
    if (JComponent.class.isInstance(component)) {
      KeyStroke keyStroke = KeyStroke.getKeyStroke(32, 1);
      final ActionListener actionForKeyStroke = ((JComponent)component).getActionForKeyStroke(keyStroke);
      if (actionForKeyStroke != null) {
        actionForKeyStroke.actionPerformed(new ActionEvent(component, KeyEvent.KEY_PRESSED, ""));
      }
    }
  }
}





Renders a component into an image

 
/*
 *
 * Created on March 16, 2007, 4:34 PM
 *
 * Copyright 2006-2007 Nigel Hughes
 *
 * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
 * in compliance with the License. You may obtain a copy of the License at http://www.apache.org/
 * licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR
 * CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language
 * governing permissions and limitations under the License.
 */
import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.GraphicsConfiguration;
import java.awt.GraphicsEnvironment;
import java.awt.RenderingHints;
import java.awt.Transparency;
import java.awt.font.FontRenderContext;
import java.awt.font.LineBreakMeasurer;
import java.awt.font.TextAttribute;
import java.awt.font.TextLayout;
import java.awt.image.BufferedImage;
import java.text.AttributedCharacterIterator;
import java.text.AttributedString;
import java.util.Hashtable;
import java.util.LinkedList;
import javax.swing.JComponent;
/**
 * @author nigel
 */
public class Utils {
  /** 
   * Renders a component into an image, which is useful for playing with the component"s 
   * resultant image in special effects or transitions
   *
   * @param component The component to render
   * @return A buffered image with the rendered component. 
   */
  public static BufferedImage renderComponentToImage(JComponent component){
      //Create the image
      BufferedImage image = createCompatibleImage(component.getWidth(),component.getHeight());
      
      //Render the component onto the image
      Graphics graphics = image.createGraphics();
//      component.update(graphics);
      component.paint(graphics);
      graphics.dispose();
      return image;
  }
  /**
   * Creates an image compatible with the current display
   * 
   * @return A BufferedImage with the appropriate color model
   */
  public static BufferedImage createCompatibleImage(int width, int height) {
    GraphicsConfiguration configuration = GraphicsEnvironment.getLocalGraphicsEnvironment()
        .getDefaultScreenDevice().getDefaultConfiguration();
    return configuration.createCompatibleImage(width, height, Transparency.TRANSLUCENT);
  }
}





Set All Opaque

   
import java.awt.ruponent;
import java.awt.Container;
import javax.swing.JComponent;
/**
 * Copyright (C) 2004 NNL Technology AB
 * Visit www.infonode.net for information about InfoNode(R) 
 * products and how to contact NNL Technology AB.
 *
 * This program is free software; you can redistribute it and/or
 * modify it under the terms of the GNU General Public License
 * as published by the Free Software Foundation; either version 2
 * 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 Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, write to the Free Software
 * Foundation, Inc., 59 Temple Place - Suite 330, Boston, 
 * MA 02111-1307, USA.
 */

// $Id: ComponentUtil.java,v 1.25 2005/12/04 13:46:04 jesper Exp $

public class Util {
  public static void setAllOpaque(Container c, boolean opaque) {
    if (c instanceof JComponent) {
      ((JComponent) c).setOpaque(opaque);
      for (int i = 0; i < c.getComponentCount(); i++) {
        Component comp = c.getComponent(i);
        if (comp instanceof Container)
          setAllOpaque((Container) comp, opaque);
      }
    }
  }
}





Set Frame Location Relative To

   

import javax.swing.*;
import java.awt.*;
/**
 * @author Adrian BER (beradrian@yahoo.ru)
 */
public class UIUtilities {

    public static void setFrameLocationRelativeTo(JFrame f, Component c) {
        if (c == null) {
            // Setting the position of the dialog on the center of the screen
            // in 1.4 should be replaced by
//             f.setLocationRelativeTo(null);
            Dimension d = Toolkit.getDefaultToolkit().getScreenSize();
            f.setLocation((int)d.getWidth()/2 - (int)f.getPreferredSize().getWidth()/2,
                    (int)d.getHeight()/2 - (int)f.getPreferredSize().getHeight()/2);
        }
    }
}





Set Wait Cursor

   
//
//  GuiUtil
//
//  Copyright (C) by Andrea Carboni.
//   This file may be distributed under the terms of the LGPL license.

import java.awt.Color;
import java.awt.ruponent;
import java.awt.Cursor;
import java.awt.Frame;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.RenderingHints;

public class GuiUtil
{
  private static Cursor defCursor  = Cursor.getDefaultCursor();
  private static Cursor waitCursor = Cursor.getPredefinedCursor(Cursor.WAIT_CURSOR);
  //---------------------------------------------------------------------------
  public static void setWaitCursor(Component c, boolean yesno)
  {
    c.setCursor(yesno ? waitCursor : defCursor);
    getFrame(c).setCursor(yesno ? waitCursor : defCursor);
  }
  //---------------------------------------------------------------------------
  public static void setWaitCursor(boolean yesno)
  {
    Frame.getFrames()[0].setCursor(yesno ? waitCursor : defCursor);
  }
  //---------------------------------------------------------------------------
  public static Frame getFrame(Component c)
  {
    Object obj = c;
    while (!(obj instanceof Frame))
      obj = ((Component)obj).getParent();
    return (Frame)obj;
  }
  //---------------------------------------------------------------------------
  public static Color cloneColor(Color c)
  {
    return new Color(c.getRed(), c.getGreen(), c.getBlue());
  }
  //---------------------------------------------------------------------------
  public static final void setTextAntiAliasing(Graphics g, boolean yesno)
  {
    Object obj = yesno ? RenderingHints.VALUE_TEXT_ANTIALIAS_ON
                 : RenderingHints.VALUE_TEXT_ANTIALIAS_OFF;
    ((Graphics2D) g).setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING, obj);
  }
  //---------------------------------------------------------------------------
  public static final void setAntiAliasing(Graphics g, boolean yesno)
  {
    Object obj = yesno ? RenderingHints.VALUE_ANTIALIAS_ON
                 : RenderingHints.VALUE_ANTIALIAS_OFF;
    ((Graphics2D) g).setRenderingHint(RenderingHints.KEY_ANTIALIASING, obj);
  }
}





Shadow Popup Border

   
/*
 * Copyright (c) 2001-2009 JGoodies Karsten Lentzsch. 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 Neither the name of JGoodies Karsten Lentzsch nor the names of
 *    its contributors may be used to endorse or promote products derived
 *    from this software without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "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.
 */

import java.awt.ruponent;
import java.awt.Graphics;
import java.awt.Image;
import java.awt.Insets;
import javax.swing.ImageIcon;
import javax.swing.JComponent;
import javax.swing.border.AbstractBorder;
/**
 * A border with a drop shadow intended to be used as the outer border
 * of popups. Can paint the screen background if used with heavy-weight
 * popup windows.
 *
 * @author Karsten Lentzsch
 * @author Andrej Golovnin
 * @version $Revision: 1.6 $
 *
 * @see ShadowPopup
 * @see ShadowPopupFactory
 */
final class ShadowPopupBorder extends AbstractBorder {
    /**
     * The drop shadow needs 5 pixels at the bottom and the right hand side.
     */
    private static final int SHADOW_SIZE = 5;
  /**
   * The singleton instance used to draw all borders.
   */
  private static ShadowPopupBorder instance = new ShadowPopupBorder();
  /**
   * The drop shadow is created from a PNG image with 8 bit alpha channel.
   */
  private static Image shadow
    = new ImageIcon(ShadowPopupBorder.class.getResource("shadow.png")).getImage();

    // Instance Creation *****************************************************
  /**
   * Returns the singleton instance used to draw all borders.
   */
  public static ShadowPopupBorder getInstance() {
    return instance;
  }

  /**
   * Paints the border for the specified component with the specified
     * position and size.
   */
  public void paintBorder(Component c, Graphics g, int x, int y, int width, int height) {
    // draw drop shadow
    g.drawImage(shadow, x +  5, y + height - 5, x + 10, y + height, 0, 6, 5, 11, null, c);
    g.drawImage(shadow, x + 10, y + height - 5, x + width - 5, y + height, 5, 6, 6, 11, null, c);
    g.drawImage(shadow, x + width - 5, y + 5, x + width, y + 10, 6, 0, 11, 5, null, c);
    g.drawImage(shadow, x + width - 5, y + 10, x + width, y + height - 5, 6, 5, 11, 6, null, c);
    g.drawImage(shadow, x + width - 5, y + height - 5, x + width, y + height, 6, 6, 11, 11, null, c);
  }

  /**
   * Returns the insets of the border.
   */
  public Insets getBorderInsets(Component c) {
    return new Insets(0, 0, SHADOW_SIZE, SHADOW_SIZE);
  }

    /**
     * Reinitializes the insets parameter with this Border"s current Insets.
     * @param c the component for which this border insets value applies
     * @param insets the object to be reinitialized
     * @return the <code>insets</code> object
     */
    public Insets getBorderInsets(Component c, Insets insets) {
        insets.left = insets.top = 0;
        insets.right = insets.bottom = SHADOW_SIZE;
        return insets;
    }
}





Unit conversions

  
/*
 * Licensed to the Apache Software Foundation (ASF) under one or more
 * contributor license agreements.  See the NOTICE file distributed with
 * this work for additional information regarding copyright ownership.
 * The ASF licenses this file to You under the Apache License, Version 2.0
 * (the "License"); you may not use this file except in compliance with
 * the License.  You may obtain a copy of the License at
 * 
 *      http://www.apache.org/licenses/LICENSE-2.0
 * 
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
/* $Id: FixedLength.java 279656 2005-09-08 22:06:48Z pietsch $ */

/**
 * Utility class for unit conversions.
 */
public final class UnitConv {
    /** conversion factory from millimeters to inches. */
    public static final float IN2MM = 25.4f;
    
    /** conversion factory from centimeters to inches. */
    public static final float IN2CM = 2.54f;
    
    /** conversion factory from inches to points. */
    public static final int IN2PT = 72;
    
    /**
     * Converts millimeters (mm) to points (pt)
     * @param mm the value in mm
     * @return the value in pt
     */
    public static double mm2pt(double mm) {
        return mm * IN2PT / IN2MM;
    }
    /**
     * Converts millimeters (mm) to millipoints (mpt)
     * @param mm the value in mm
     * @return the value in mpt
     */
    public static double mm2mpt(double mm) {
        return mm * 1000 * IN2PT / IN2MM;
    }
    /**
     * Converts points (pt) to millimeters (mm)
     * @param pt the value in pt
     * @return the value in mm
     */
    public static double pt2mm(double pt) {
        return pt * IN2MM / IN2PT;
    }
    
    /**
     * Converts millimeters (mm) to inches (in)
     * @param mm the value in mm
     * @return the value in inches
     */
    public static double mm2in(double mm) {
        return mm / IN2MM;
    }
    
    /**
     * Converts inches (in) to millimeters (mm)
     * @param in the value in inches
     * @return the value in mm
     */
    public static double in2mm(double in) {
        return in * IN2MM;
    }
    
    /**
     * Converts inches (in) to millipoints (mpt)
     * @param in the value in inches
     * @return the value in mpt
     */
    public static double in2mpt(double in) {
        return in * IN2PT * 1000;
    }
    
    /**
     * Converts inches (in) to points (pt)
     * @param in the value in inches
     * @return the value in pt
     */
    public static double in2pt(double in) {
        return in * IN2PT;
    }
    
    /**
     * Converts millipoints (mpt) to inches (in) 
     * @param mpt the value in mpt
     * @return the value in inches
     */
    public static double mpt2in(double mpt) {
        return mpt / IN2PT / 1000;
    }
    
    /**
     * Converts millimeters (mm) to pixels (px)
     * @param mm the value in mm
     * @param resolution the resolution in dpi (dots per inch)
     * @return the value in pixels
     */
    public static double mm2px(double mm, int resolution) {
        return mm2in(mm) * resolution;
    }
    /**
     * Converts millipoints (mpt) to pixels (px)
     * @param mpt the value in mpt
     * @param resolution the resolution in dpi (dots per inch)
     * @return the value in pixels
     */
    public static double mpt2px(double mpt, int resolution) {
        return mpt2in(mpt) * resolution;
    }
}





Unit measure

   
/*
 * Ruler.java
 * 
 * Created on Oct 1, 2007, 8:33:09 AM
 * 
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

import java.util.HashMap;
/**
 *
 * @author gtoffoli
 */
public class Unit {
    public static final double PIXEL = 1.0;
    public static final double INCHES = 72.0;
    public static final double CENTIMETERS = 28.3464;
    public static final double MILLIMETERS = 2.83464;
    /** Holds value of property unitName. */
    private String unitName;
    private String keyName;
    /** Holds value of property conversionValue. */
    private double conversionValue;
    /** Creates a new instance of Unit */
    public Unit(String unitName, double conversionValue) {
        this(unitName, conversionValue, unitName);
    }
    
    public Unit(String unitName, double conversionValue, String keyName) {
        this.unitName = unitName;
        this.conversionValue = conversionValue;
        this.setKeyName(keyName);
    }
    /** Getter for property unitName.
     * @return Value of property unitName.
     *
     */
    public String getUnitName() {
        return this.unitName;
    }
    /** Setter for property unitName.
     * @param unitName New value of property unitName.
     *
     */
    public void setUnitName(String unitName) {
        this.unitName = unitName;
    }
    /** Getter for property conversionValue.
     * @return Value of property conversionValue.
     *
     */
    public double getConversionValue() {
        return this.conversionValue;
    }
    /** Setter for property conversionValue.
     * @param conversionValue New value of property conversionValue.
     *
     */
    public void setConversionValue(double conversionValue) {
        this.conversionValue = conversionValue;
    }
    private static Unit[] units = null;
    
    private static HashMap<String,Unit> unitsMap = null;
    
    public static Unit[] getStandardUnits()
    {
        if (units == null)
        {
            unitsMap = new HashMap<String,Unit>();
            units = new Unit[4];
            units[0] = new Unit("pixels",Unit.PIXEL, "pixels");  
            unitsMap.put("pixels", units[0]);
            units[1] = new Unit("inches",Unit.INCHES, "inches");
            unitsMap.put("inches", units[1]);
            units[2] = new Unit("cm",    Unit.CENTIMETERS, "cm");
            unitsMap.put("cm", units[2]);
            units[3] = new Unit("mm",    Unit.MILLIMETERS, "mm");
            unitsMap.put("mm", units[3]);
        }
        return units;
    }
    public static int getUnitIndex(String unitName)
    {
        Unit[] units = getStandardUnits();
        for (int i=0; i<units.length; ++i)
        {
            if (units[i].getUnitName().equalsIgnoreCase(unitName)) return i;
        }
        return -1;
    }
    public String toString()
    {
        return getUnitName();
    }
    /**
     * convert from pixel to the unit represented by this class
     *
     * @param pixel
     * @return
     */
    public double convert(int pixels)
    {
        return ((double)pixels)/conversionValue;
    }
    /**
     * convert from pixel to the unit represented by this class
     *
     * @param pixel
     * @return
     */
    public long toPixel(double val)
    {
        return (long)(val*conversionValue);
    }
    static public double convertPixelsToInches(long pixels)
  {
    return ((double)pixels)/INCHES;
  }
  static public long convertInchesToPixels(double inches)
  {
    return (long)(inches*INCHES);
  }
  static public double convertPixelsToCentimeters(long pixels)
  {
    return ((double)pixels)/CENTIMETERS;
  }
  static public long convertCentimetersToPixels(double centimeters)
  {
    return (long)(centimeters*CENTIMETERS);
  }
  static public double convertPixelsToMillimeters(long pixels)
  {
    return ((double)pixels)/MILLIMETERS;
  }
  static public long convertMillimetersToPixels(double millimeters)
  {
    return (long)(millimeters*CENTIMETERS);
  }
  static public long convertToPixels(double value, double convert)
  {
    return (long)(value*convert);
  }
        
        static public Unit getUnit(String unitName)
  {
            if (unitsMap == null) getStandardUnits();
            return unitsMap.get(unitName);
        }
    public String getKeyName() {
        return keyName;
    }
    public void setKeyName(String keyName) {
        this.keyName = keyName;
    }
}





Utilities for GUI work.

 
/*
 * Copyright (c) Ian F. Darwin, http://www.darwinsys.ru/, 1996-2002.
 * All rights reserved. Software written by Ian F. Darwin and others.
 * $Id: LICENSE,v 1.8 2004/02/09 03:33:38 ian Exp $
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 * 1. Redistributions of source code must retain the above copyright
 *    notice, this list of conditions and the following disclaimer.
 * 2. 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.
 *
 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``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 AUTHOR 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.
 * 
 * Java, the Duke mascot, and all variants of Sun"s Java "steaming coffee
 * cup" logo are trademarks of Sun Microsystems. Sun"s, and James Gosling"s,
 * pioneering role in inventing and promulgating (and standardizing) the Java 
 * language and environment is gratefully acknowledged.
 * 
 * The pioneering role of Dennis Ritchie and Bjarne Stroustrup, of AT&T, for
 * inventing predecessor languages C and C++ is also gratefully acknowledged.
 */
import java.awt.Dimension;
import java.awt.Toolkit;
import java.awt.Window;
/**
 * Utilities for GUI work.
 * 
 * @version $Id: UtilGUI.java,v 1.6 2003/07/12 23:28:01 ian Exp $
 */
public class UtilGUI {
  /** Centre a Window, Frame, JFrame, Dialog, etc. */
  public static void centre(Window w) {
    // After packing a Frame or Dialog, centre it on the screen.
    Dimension us = w.getSize(), them = Toolkit.getDefaultToolkit()
        .getScreenSize();
    int newX = (them.width - us.width) / 2;
    int newY = (them.height - us.height) / 2;
    w.setLocation(newX, newY);
  }
  /**
   * Center a Window, Frame, JFrame, Dialog, etc., but do it the American
   * Spelling Way :-)
   */
  public static void center(Window w) {
    UtilGUI.centre(w);
  }
  /** Maximize a window, the hard way. */
  public static void maximize(Window w) {
    Dimension us = w.getSize(), them = Toolkit.getDefaultToolkit()
        .getScreenSize();
    w.setBounds(0, 0, them.width, them.height);
  }
}