Java Tutorial/Swing/SwingUtilities
Версия от 17:44, 31 мая 2010; (обсуждение)
Содержание
- 1 14. Center that window on the given desktop.
- 2 14. Change the sizes of all the passed buttons to be the size of the largest one.
- 3 14. Convert a coordinate on a screen to a coordinate relative to a component"s bounds
- 4 14. Convert a coordinate relative to a component"s bounds to screen coordinates
- 5 14. Get All Components in a container
- 6 14. Get Point For Centering
- 7 14. Get Screen Bounds For
- 8 14. Get the JFrame by getting the root of a component
- 9 14. Getting the JFrame of a Component
- 10 14. Get Window from a component
- 11 14. Handle long-running tasks in a Swing application
- 12 14. Is Within Parent
- 13 14. Positions the specified frame at a random location on the screen while ensuring that the
- 14 14. Positions the specified frame at a relative position in the screen, where 50% is considered to be the center of the screen.
- 15 14. Positions the specified frame in the middle of the screen.
- 16 14. Returns the offset of the bracket matching the one at the specified offset of the document
- 17 14. Show the given frame as modal to the specified owner
14. Center that window on the given desktop.
/*
* $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.GraphicsDevice;
import java.awt.GraphicsEnvironment;
import java.awt.MouseInfo;
import java.awt.Point;
import java.awt.Rectangle;
import javax.swing.JInternalFrame;
/**
* 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 to
* center that window on the given desktop.
* </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 (JInternalFrame) 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 given desktop
*/
public static Point getPointForCentering(JInternalFrame window) {
try {
//assert window != null;
Point mousePoint = MouseInfo.getPointerInfo().getLocation();
GraphicsDevice[] devices = GraphicsEnvironment
.getLocalGraphicsEnvironment().getScreenDevices();
for (GraphicsDevice device : devices) {
Rectangle bounds = device.getDefaultConfiguration().getBounds();
//check to see if the mouse cursor is within these bounds
if (mousePoint.x >= bounds.x && mousePoint.y >= bounds.y
&& mousePoint.x <= (bounds.x + bounds.width)
&& mousePoint.y <= (bounds.y + bounds.height)) {
//this is it
int screenWidth = bounds.width;
int screenHeight = bounds.height;
int width = window.getWidth();
int height = window.getHeight();
return new Point(((screenWidth - width) / 2) + bounds.x,
((screenHeight - height) / 2) + bounds
.y);
}
}
} catch (Exception e) {
}
return new Point(0, 0);
}
}
14. Change the sizes of all the passed buttons to be the size of the largest one.
/*
* 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 {
/**
* Change the sizes of all the passed buttons to be the size of the largest
* one.
*
* @param btns
* Array of buttons to eb resized.
*
* @throws IllegalArgumentException
* If <TT>btns</TT> is <TT>null</TT>.
*/
public static void setJButtonSizesTheSame(JButton[] btns) {
if (btns == null) {
throw new IllegalArgumentException("null JButton[] passed");
}
// Get the largest width and height
final Dimension maxSize = new Dimension(0, 0);
for (int i = 0; i < btns.length; ++i) {
final JButton btn = btns[i];
final FontMetrics fm = btn.getFontMetrics(btn.getFont());
Rectangle2D bounds = fm.getStringBounds(btn.getText(), btn.getGraphics());
int boundsHeight = (int) bounds.getHeight();
int boundsWidth = (int) bounds.getWidth();
maxSize.width = boundsWidth > maxSize.width ? boundsWidth : maxSize.width;
maxSize.height = boundsHeight > maxSize.height ? boundsHeight : maxSize.height;
}
Insets insets = btns[0].getInsets();
maxSize.width += insets.left + insets.right;
maxSize.height += insets.top + insets.bottom;
for (int i = 0; i < btns.length; ++i) {
JButton btn = btns[i];
btn.setPreferredSize(maxSize);
}
}
}
14. Convert a coordinate on a screen to a coordinate relative to a component"s bounds
import java.awt.Point;
import javax.swing.JButton;
import javax.swing.SwingUtilities;
public class Main {
public static void main(String[] argv) {
JButton component = new JButton();
Point pt = new Point(component.getLocation());
SwingUtilities.convertPointFromScreen(pt, component);
}
}
14. Convert a coordinate relative to a component"s bounds to screen coordinates
import java.awt.Point;
import javax.swing.JButton;
import javax.swing.SwingUtilities;
public class Main {
public static void main(String[] argv) {
JButton component = new JButton();
Point pt = new Point(component.getLocation());
SwingUtilities.convertPointToScreen(pt, component);
}
}
14. Get All Components in a container
/*
* $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.ruponent;
import java.awt.Container;
import java.util.ArrayList;
import java.util.List;
/**
* 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 List<Component> getAllComponents(final Container c) {
Component[] comps = c.getComponents();
List<Component> compList = new ArrayList<Component>();
for (Component comp : comps) {
compList.add(comp);
if (comp instanceof Container) {
compList.addAll(getAllComponents((Container) comp));
}
}
return compList;
}
}
14. 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;
}
}
14. Get Screen Bounds For
/*
* 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 {
public static Rectangle getScreenBoundsFor(Rectangle rc) {
final GraphicsDevice[] gds = GraphicsEnvironment.getLocalGraphicsEnvironment()
.getScreenDevices();
final List<GraphicsConfiguration> configs = new ArrayList<GraphicsConfiguration>();
for (int i = 0; i < gds.length; i++) {
GraphicsConfiguration gc = gds[i].getDefaultConfiguration();
if (rc.intersects(gc.getBounds())) {
configs.add(gc);
}
}
GraphicsConfiguration selected = null;
if (configs.size() > 0) {
for (Iterator<GraphicsConfiguration> it = configs.iterator(); it.hasNext();) {
GraphicsConfiguration gcc = it.next();
if (selected == null)
selected = gcc;
else {
if (gcc.getBounds().contains(rc.x + 20, rc.y + 20)) {
selected = gcc;
break;
}
}
}
} else {
selected = GraphicsEnvironment.getLocalGraphicsEnvironment().getDefaultScreenDevice()
.getDefaultConfiguration();
}
int x = selected.getBounds().x;
int y = selected.getBounds().y;
int w = selected.getBounds().width;
int h = selected.getBounds().height;
return new Rectangle(x, y, w, h);
}
}
14. Get the JFrame by getting the root of a component
import java.awt.Color;
import java.awt.ruponent;
import java.awt.FlowLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.SwingUtilities;
public class Main extends JFrame {
public Main() {
this.setSize(400, 100);
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
this.setLayout(new FlowLayout(FlowLayout.CENTER));
JButton button = new JButton("Change Frame Color");
button.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
Component component = (Component) e.getSource();
JFrame frame = (JFrame) SwingUtilities.getRoot(component);
frame.getContentPane().setBackground(Color.RED);
}
});
this.getContentPane().add(button);
}
public static void main(String[] args) {
new Main().setVisible(true);
}
}
14. Getting the JFrame of a Component
import java.awt.ruponent;
import java.awt.event.ActionEvent;
import javax.swing.AbstractAction;
import javax.swing.Action;
import javax.swing.SwingUtilities;
public class Main {
public static void main(String[] argv) throws Exception {
// Create an action
Action action = new AbstractAction("Action Label") {
// This method is called when the action is triggered
public void actionPerformed(ActionEvent evt) {
Component c = (Component) evt.getSource();
// Get the frame
Component frame = SwingUtilities.getRoot(c);
// Hide the frame
frame.setVisible(false);
}
};
}
}
14. Get Window from a component
/*
* $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.ruponent;
import java.awt.Insets;
import java.awt.Point;
import java.awt.Window;
import javax.swing.JOptionPane;
/**
* 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 Window findWindow(Component c) {
if (c == null) {
return JOptionPane.getRootFrame();
} else if (c instanceof Window) {
return (Window) c;
} else {
return findWindow(c.getParent());
}
}
}
14. Handle long-running tasks in a Swing application
import java.awt.BorderLayout;
import java.awt.FlowLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.SwingUtilities;
public class Main {
private static JButton good = new JButton("Good");
private static JLabel resultLabel = new JLabel("Ready", JLabel.CENTER);
public static void main(String[] args) {
JFrame f = new JFrame();
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JPanel p = new JPanel();
p.setOpaque(true);
p.setLayout(new FlowLayout());
p.add(good);
f.add(p, BorderLayout.CENTER);
f.add(resultLabel, BorderLayout.SOUTH);
good.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent ev) {
resultLabel.setText("Working . . .");
good.setEnabled(false);
Thread worker = new Thread() {
public void run() {
try {
Thread.sleep(5000);
} catch (InterruptedException ex) {
}
SwingUtilities.invokeLater(new Runnable() {
public void run() {
resultLabel.setText("Ready");
good.setEnabled(true);
}
});
}
};
worker.start(); // So we don"t hold up the dispatch thread.
}
});
f.setSize(300, 100);
f.setVisible(true);
}
}
14. Is 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 {
public static boolean isWithinParent(Component wind) {
if (wind == null) {
throw new IllegalArgumentException("Null Component passed");
}
Rectangle windowBounds = wind.getBounds();
Component parent = wind.getParent();
Rectangle parentRect = null;
if (parent != null) {
parentRect = new Rectangle(parent.getSize());
} else {
// parentRect = new
// Rectangle(Toolkit.getDefaultToolkit().getScreenSize());
parentRect = getScreenBoundsFor(windowBounds);
}
// if (windowBounds.x > (parentRect.width - 20)
// || windowBounds.y > (parentRect.height - 20)
// || (windowBounds.x + windowBounds.width) < 20
// || (windowBounds.y + windowBounds.height) < 20)
// {
// return false;
// }
if (windowBounds.x < (parentRect.x - 20) || windowBounds.y < (parentRect.y - 20)) {
return false;
}
return true;
}
public static Rectangle getScreenBoundsFor(Rectangle rc) {
final GraphicsDevice[] gds = GraphicsEnvironment.getLocalGraphicsEnvironment()
.getScreenDevices();
final List<GraphicsConfiguration> configs = new ArrayList<GraphicsConfiguration>();
for (int i = 0; i < gds.length; i++) {
GraphicsConfiguration gc = gds[i].getDefaultConfiguration();
if (rc.intersects(gc.getBounds())) {
configs.add(gc);
}
}
GraphicsConfiguration selected = null;
if (configs.size() > 0) {
for (Iterator<GraphicsConfiguration> it = configs.iterator(); it.hasNext();) {
GraphicsConfiguration gcc = it.next();
if (selected == null)
selected = gcc;
else {
if (gcc.getBounds().contains(rc.x + 20, rc.y + 20)) {
selected = gcc;
break;
}
}
}
} else {
selected = GraphicsEnvironment.getLocalGraphicsEnvironment().getDefaultScreenDevice()
.getDefaultConfiguration();
}
int x = selected.getBounds().x;
int y = selected.getBounds().y;
int w = selected.getBounds().width;
int h = selected.getBounds().height;
return new Rectangle(x, y, w, h);
}
}
14. 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);
}
}
14. 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);
}
}
14. 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);
}
}
14. Returns the offset of the bracket matching the one at the specified offset of the document
/*
* TextUtilities.java - Utility functions used by the text area classes
* Copyright (C) 1999 Slava Pestov
*
* You may use and modify this package for any purpose. Redistribution is
* permitted, in both source and binary form, provided that this notice
* remains intact in all source distributions of this package.
*/
import javax.swing.text.BadLocationException;
import javax.swing.text.Document;
/**
* Class with several utility functions used by the text area component.
*
* @author Slava Pestov
* @version $Id$
*/
public class TextUtilities
{
/**
* Returns the offset of the bracket matching the one at the specified offset
* of the document, or -1 if the bracket is unmatched (or if the character is
* not a bracket).
*
* @param doc
* The document
* @param offset
* The offset
* @exception BadLocationException
* If an out-of-bounds access was attempted on the document
* text
*/
public static int findMatchingBracket( Document doc, int offset ) throws BadLocationException
{
if( doc.getLength() == 0 )
return -1;
char c = doc.getText( offset, 1 ).charAt( 0 );
char cprime; // c` - corresponding character
boolean direction; // true = back, false = forward
switch( c )
{
case "(" :
cprime = ")";
direction = false;
break;
case ")" :
cprime = "(";
direction = true;
break;
case "[" :
cprime = "]";
direction = false;
break;
case "]" :
cprime = "[";
direction = true;
break;
case "{" :
cprime = "}";
direction = false;
break;
case "}" :
cprime = "{";
direction = true;
break;
default :
return -1;
}
int count;
// How to merge these two cases is left as an exercise
// for the reader.
// Go back or forward
if( direction )
{
// Count is 1 initially because we have already
// `found" one closing bracket
count = 1;
// Get text[0,offset-1];
String text = doc.getText( 0, offset );
// Scan backwards
for( int i = offset - 1; i >= 0; i-- )
{
// If text[i] == c, we have found another
// closing bracket, therefore we will need
// two opening brackets to complete the
// match.
char x = text.charAt( i );
if( x == c )
count++ ;
// If text[i] == cprime, we have found a
// opening bracket, so we return i if
// --count == 0
else if( x == cprime )
{
if( --count == 0 )
return i;
}
}
}
else
{
// Count is 1 initially because we have already
// `found" one opening bracket
count = 1;
// So we don"t have to + 1 in every loop
offset++ ;
// Number of characters to check
int len = doc.getLength() - offset;
// Get text[offset+1,len];
String text = doc.getText( offset, len );
// Scan forwards
for( int i = 0; i < len; i++ )
{
// If text[i] == c, we have found another
// opening bracket, therefore we will need
// two closing brackets to complete the
// match.
char x = text.charAt( i );
if( x == c )
count++ ;
// If text[i] == cprime, we have found an
// closing bracket, so we return i if
// --count == 0
else if( x == cprime )
{
if( --count == 0 )
return i + offset;
}
}
}
// Nothing found
return -1;
}
}
14. Show the given frame as modal to the specified owner
import java.awt.Frame;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
import javax.swing.JFrame;
// @author Santhosh Kumar T - santhosh@in.fiorano.ru
public class ModalFrameUtil {
static class EventPump implements InvocationHandler {
Frame frame;
public EventPump(Frame frame) {
this.frame = frame;
}
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
return frame.isShowing();
}
// when the reflection calls in this method has to be
// replaced once Sun provides a public API to pump events.
public void start() throws Exception {
Class<?> clazz = Class.forName("java.awt.Conditional");
Object conditional = Proxy.newProxyInstance(clazz.getClassLoader(), new Class[] { clazz },
this);
Method pumpMethod = Class.forName("java.awt.EventDispatchThread").getDeclaredMethod(
"pumpEvents", new Class[] { clazz });
pumpMethod.setAccessible(true);
pumpMethod.invoke(Thread.currentThread(), new Object[] { conditional });
}
}
// show the given frame as modal to the specified owner.
// NOTE: this method returns only after the modal frame is closed.
public static void showAsModal(final Frame frame, final Frame owner) {
frame.addWindowListener(new WindowAdapter() {
public void windowOpened(WindowEvent e) {
owner.setEnabled(false);
}
public void windowClosing(WindowEvent e) {
owner.setEnabled(true);
frame.removeWindowListener(this);
}
public void windowClosed(WindowEvent e) {
owner.setEnabled(true);
frame.removeWindowListener(this);
}
});
owner.addWindowListener(new WindowAdapter() {
public void windowActivated(WindowEvent e) {
if (frame.isShowing()) {
frame.setExtendedState(JFrame.NORMAL);
frame.toFront();
} else {
owner.removeWindowListener(this);
}
}
});
frame.setVisible(true);
try {
new EventPump(frame).start();
} catch (Throwable throwable) {
throw new RuntimeException(throwable);
}
}
}