code
stringlengths 3
1.18M
| language
stringclasses 1
value |
|---|---|
/*
* Copyright (c) 1999, 2007, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code 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
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package java.awt;
import java.awt.peer.*;
import java.awt.image.*;
import java.awt.event.*;
import java.lang.reflect.InvocationTargetException;
import sun.awt.ComponentFactory;
import sun.awt.SunToolkit;
import sun.security.util.SecurityConstants;
/** {@collect.stats}
* This class is used to generate native system input events
* for the purposes of test automation, self-running demos, and
* other applications where control of the mouse and keyboard
* is needed. The primary purpose of Robot is to facilitate
* automated testing of Java platform implementations.
* <p>
* Using the class to generate input events differs from posting
* events to the AWT event queue or AWT components in that the
* events are generated in the platform's native input
* queue. For example, <code>Robot.mouseMove</code> will actually move
* the mouse cursor instead of just generating mouse move events.
* <p>
* Note that some platforms require special privileges or extensions
* to access low-level input control. If the current platform configuration
* does not allow input control, an <code>AWTException</code> will be thrown
* when trying to construct Robot objects. For example, X-Window systems
* will throw the exception if the XTEST 2.2 standard extension is not supported
* (or not enabled) by the X server.
* <p>
* Applications that use Robot for purposes other than self-testing should
* handle these error conditions gracefully.
*
* @author Robi Khan
* @since 1.3
*/
public class Robot {
private static final int MAX_DELAY = 60000;
private RobotPeer peer;
private boolean isAutoWaitForIdle = false;
private int autoDelay = 0;
private static final int LEGAL_BUTTON_MASK =
InputEvent.BUTTON1_MASK|
InputEvent.BUTTON2_MASK|
InputEvent.BUTTON3_MASK;
// location of robot's GC, used in mouseMove(), getPixelColor() and captureScreenImage()
private Point gdLoc;
private DirectColorModel screenCapCM = null;
/** {@collect.stats}
* Constructs a Robot object in the coordinate system of the primary screen.
* <p>
*
* @throws AWTException if the platform configuration does not allow
* low-level input control. This exception is always thrown when
* GraphicsEnvironment.isHeadless() returns true
* @throws SecurityException if <code>createRobot</code> permission is not granted
* @see java.awt.GraphicsEnvironment#isHeadless
* @see SecurityManager#checkPermission
* @see AWTPermission
*/
public Robot() throws AWTException {
if (GraphicsEnvironment.isHeadless()) {
throw new AWTException("headless environment");
}
init(GraphicsEnvironment.getLocalGraphicsEnvironment()
.getDefaultScreenDevice());
}
/** {@collect.stats}
* Creates a Robot for the given screen device. Coordinates passed
* to Robot method calls like mouseMove and createScreenCapture will
* be interpreted as being in the same coordinate system as the
* specified screen. Note that depending on the platform configuration,
* multiple screens may either:
* <ul>
* <li>share the same coordinate system to form a combined virtual screen</li>
* <li>use different coordinate systems to act as independent screens</li>
* </ul>
* This constructor is meant for the latter case.
* <p>
* If screen devices are reconfigured such that the coordinate system is
* affected, the behavior of existing Robot objects is undefined.
*
* @param screen A screen GraphicsDevice indicating the coordinate
* system the Robot will operate in.
* @throws AWTException if the platform configuration does not allow
* low-level input control. This exception is always thrown when
* GraphicsEnvironment.isHeadless() returns true.
* @throws IllegalArgumentException if <code>screen</code> is not a screen
* GraphicsDevice.
* @throws SecurityException if <code>createRobot</code> permission is not granted
* @see java.awt.GraphicsEnvironment#isHeadless
* @see GraphicsDevice
* @see SecurityManager#checkPermission
* @see AWTPermission
*/
public Robot(GraphicsDevice screen) throws AWTException {
checkIsScreenDevice(screen);
init(screen);
}
private void init(GraphicsDevice screen) throws AWTException {
checkRobotAllowed();
gdLoc = screen.getDefaultConfiguration().getBounds().getLocation();
Toolkit toolkit = Toolkit.getDefaultToolkit();
if (toolkit instanceof ComponentFactory) {
peer = ((ComponentFactory)toolkit).createRobot(this, screen);
disposer = new RobotDisposer(peer);
sun.java2d.Disposer.addRecord(anchor, disposer);
}
}
/* determine if the security policy allows Robot's to be created */
private void checkRobotAllowed() {
SecurityManager security = System.getSecurityManager();
if (security != null) {
security.checkPermission(SecurityConstants.CREATE_ROBOT_PERMISSION);
}
}
/* check if the given device is a screen device */
private void checkIsScreenDevice(GraphicsDevice device) {
if (device == null || device.getType() != GraphicsDevice.TYPE_RASTER_SCREEN) {
throw new IllegalArgumentException("not a valid screen device");
}
}
private transient Object anchor = new Object();
static class RobotDisposer implements sun.java2d.DisposerRecord {
private final RobotPeer peer;
public RobotDisposer(RobotPeer peer) {
this.peer = peer;
}
public void dispose() {
if (peer != null) {
peer.dispose();
}
}
}
private transient RobotDisposer disposer;
/** {@collect.stats}
* Moves mouse pointer to given screen coordinates.
* @param x X position
* @param y Y position
*/
public synchronized void mouseMove(int x, int y) {
peer.mouseMove(gdLoc.x + x, gdLoc.y + y);
afterEvent();
}
/** {@collect.stats}
* Presses one or more mouse buttons. The mouse buttons should
* be released using the <code>mouseRelease</code> method.
*
* @param buttons the Button mask; a combination of one or more
* of these flags:
* <ul>
* <li><code>InputEvent.BUTTON1_MASK</code>
* <li><code>InputEvent.BUTTON2_MASK</code>
* <li><code>InputEvent.BUTTON3_MASK</code>
* </ul>
* @throws IllegalArgumentException if the button mask is not a
* valid combination
* @see #mouseRelease(int)
*/
public synchronized void mousePress(int buttons) {
checkButtonsArgument(buttons);
peer.mousePress(buttons);
afterEvent();
}
/** {@collect.stats}
* Releases one or more mouse buttons.
*
* @param buttons the Button mask; a combination of one or more
* of these flags:
* <ul>
* <li><code>InputEvent.BUTTON1_MASK</code>
* <li><code>InputEvent.BUTTON2_MASK</code>
* <li><code>InputEvent.BUTTON3_MASK</code>
* </ul>
* @see #mousePress(int)
* @throws IllegalArgumentException if the button mask is not a valid
* combination
*/
public synchronized void mouseRelease(int buttons) {
checkButtonsArgument(buttons);
peer.mouseRelease(buttons);
afterEvent();
}
private void checkButtonsArgument(int buttons) {
if ( (buttons|LEGAL_BUTTON_MASK) != LEGAL_BUTTON_MASK ) {
throw new IllegalArgumentException("Invalid combination of button flags");
}
}
/** {@collect.stats}
* Rotates the scroll wheel on wheel-equipped mice.
*
* @param wheelAmt number of "notches" to move the mouse wheel
* Negative values indicate movement up/away from the user,
* positive values indicate movement down/towards the user.
*
* @since 1.4
*/
public synchronized void mouseWheel(int wheelAmt) {
peer.mouseWheel(wheelAmt);
afterEvent();
}
/** {@collect.stats}
* Presses a given key. The key should be released using the
* <code>keyRelease</code> method.
* <p>
* Key codes that have more than one physical key associated with them
* (e.g. <code>KeyEvent.VK_SHIFT</code> could mean either the
* left or right shift key) will map to the left key.
*
* @param keycode Key to press (e.g. <code>KeyEvent.VK_A</code>)
* @throws IllegalArgumentException if <code>keycode</code> is not
* a valid key
* @see #keyRelease(int)
* @see java.awt.event.KeyEvent
*/
public synchronized void keyPress(int keycode) {
checkKeycodeArgument(keycode);
peer.keyPress(keycode);
afterEvent();
}
/** {@collect.stats}
* Releases a given key.
* <p>
* Key codes that have more than one physical key associated with them
* (e.g. <code>KeyEvent.VK_SHIFT</code> could mean either the
* left or right shift key) will map to the left key.
*
* @param keycode Key to release (e.g. <code>KeyEvent.VK_A</code>)
* @throws IllegalArgumentException if <code>keycode</code> is not a
* valid key
* @see #keyPress(int)
* @see java.awt.event.KeyEvent
*/
public synchronized void keyRelease(int keycode) {
checkKeycodeArgument(keycode);
peer.keyRelease(keycode);
afterEvent();
}
private void checkKeycodeArgument(int keycode) {
// rather than build a big table or switch statement here, we'll
// just check that the key isn't VK_UNDEFINED and assume that the
// peer implementations will throw an exception for other bogus
// values e.g. -1, 999999
if (keycode == KeyEvent.VK_UNDEFINED) {
throw new IllegalArgumentException("Invalid key code");
}
}
/** {@collect.stats}
* Returns the color of a pixel at the given screen coordinates.
* @param x X position of pixel
* @param y Y position of pixel
* @return Color of the pixel
*/
public synchronized Color getPixelColor(int x, int y) {
Color color = new Color(peer.getRGBPixel(gdLoc.x + x, gdLoc.y + y));
return color;
}
/** {@collect.stats}
* Creates an image containing pixels read from the screen. This image does
* not include the mouse cursor.
* @param screenRect Rect to capture in screen coordinates
* @return The captured image
* @throws IllegalArgumentException if <code>screenRect</code> width and height are not greater than zero
* @throws SecurityException if <code>readDisplayPixels</code> permission is not granted
* @see SecurityManager#checkPermission
* @see AWTPermission
*/
public synchronized BufferedImage createScreenCapture(Rectangle screenRect) {
checkScreenCaptureAllowed();
// according to the spec, screenRect is relative to robot's GD
Rectangle translatedRect = new Rectangle(screenRect);
translatedRect.translate(gdLoc.x, gdLoc.y);
checkValidRect(translatedRect);
BufferedImage image;
DataBufferInt buffer;
WritableRaster raster;
if (screenCapCM == null) {
/*
* Fix for 4285201
* Create a DirectColorModel equivalent to the default RGB ColorModel,
* except with no Alpha component.
*/
screenCapCM = new DirectColorModel(24,
/* red mask */ 0x00FF0000,
/* green mask */ 0x0000FF00,
/* blue mask */ 0x000000FF);
}
int pixels[];
int[] bandmasks = new int[3];
pixels = peer.getRGBPixels(translatedRect);
buffer = new DataBufferInt(pixels, pixels.length);
bandmasks[0] = screenCapCM.getRedMask();
bandmasks[1] = screenCapCM.getGreenMask();
bandmasks[2] = screenCapCM.getBlueMask();
raster = Raster.createPackedRaster(buffer, translatedRect.width, translatedRect.height, translatedRect.width, bandmasks, null);
image = new BufferedImage(screenCapCM, raster, false, null);
return image;
}
private static void checkValidRect(Rectangle rect) {
if (rect.width <= 0 || rect.height <= 0) {
throw new IllegalArgumentException("Rectangle width and height must be > 0");
}
}
private static void checkScreenCaptureAllowed() {
SecurityManager security = System.getSecurityManager();
if (security != null) {
security.checkPermission(
SecurityConstants.READ_DISPLAY_PIXELS_PERMISSION);
}
}
/*
* Called after an event is generated
*/
private void afterEvent() {
autoWaitForIdle();
autoDelay();
}
/** {@collect.stats}
* Returns whether this Robot automatically invokes <code>waitForIdle</code>
* after generating an event.
* @return Whether <code>waitForIdle</code> is automatically called
*/
public synchronized boolean isAutoWaitForIdle() {
return isAutoWaitForIdle;
}
/** {@collect.stats}
* Sets whether this Robot automatically invokes <code>waitForIdle</code>
* after generating an event.
* @param isOn Whether <code>waitForIdle</code> is automatically invoked
*/
public synchronized void setAutoWaitForIdle(boolean isOn) {
isAutoWaitForIdle = isOn;
}
/*
* Calls waitForIdle after every event if so desired.
*/
private void autoWaitForIdle() {
if (isAutoWaitForIdle) {
waitForIdle();
}
}
/** {@collect.stats}
* Returns the number of milliseconds this Robot sleeps after generating an event.
*/
public synchronized int getAutoDelay() {
return autoDelay;
}
/** {@collect.stats}
* Sets the number of milliseconds this Robot sleeps after generating an event.
* @throws IllegalArgumentException If <code>ms</code> is not between 0 and 60,000 milliseconds inclusive
*/
public synchronized void setAutoDelay(int ms) {
checkDelayArgument(ms);
autoDelay = ms;
}
/*
* Automatically sleeps for the specified interval after event generated.
*/
private void autoDelay() {
delay(autoDelay);
}
/** {@collect.stats}
* Sleeps for the specified time.
* To catch any <code>InterruptedException</code>s that occur,
* <code>Thread.sleep()</code> may be used instead.
* @param ms time to sleep in milliseconds
* @throws IllegalArgumentException if <code>ms</code> is not between 0 and 60,000 milliseconds inclusive
* @see java.lang.Thread#sleep
*/
public synchronized void delay(int ms) {
checkDelayArgument(ms);
try {
Thread.sleep(ms);
} catch(InterruptedException ite) {
ite.printStackTrace();
}
}
private void checkDelayArgument(int ms) {
if (ms < 0 || ms > MAX_DELAY) {
throw new IllegalArgumentException("Delay must be to 0 to 60,000ms");
}
}
/** {@collect.stats}
* Waits until all events currently on the event queue have been processed.
* @throws IllegalThreadStateException if called on the AWT event dispatching thread
*/
public synchronized void waitForIdle() {
checkNotDispatchThread();
// post a dummy event to the queue so we know when
// all the events before it have been processed
try {
SunToolkit.flushPendingEvents();
EventQueue.invokeAndWait( new Runnable() {
public void run() {
// dummy implementation
}
} );
} catch(InterruptedException ite) {
System.err.println("Robot.waitForIdle, non-fatal exception caught:");
ite.printStackTrace();
} catch(InvocationTargetException ine) {
System.err.println("Robot.waitForIdle, non-fatal exception caught:");
ine.printStackTrace();
}
}
private void checkNotDispatchThread() {
if (EventQueue.isDispatchThread()) {
throw new IllegalThreadStateException("Cannot call method from the event dispatcher thread");
}
}
/** {@collect.stats}
* Returns a string representation of this Robot.
*
* @return the string representation.
*/
public synchronized String toString() {
String params = "autoDelay = "+getAutoDelay()+", "+"autoWaitForIdle = "+isAutoWaitForIdle();
return getClass().getName() + "[ " + params + " ]";
}
}
|
Java
|
/*
* Copyright (c) 1995, 2007, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code 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
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package java.awt;
import java.awt.peer.TextFieldPeer;
import java.awt.event.*;
import java.util.EventListener;
import java.io.ObjectOutputStream;
import java.io.ObjectInputStream;
import java.io.IOException;
import javax.accessibility.*;
/** {@collect.stats}
* A <code>TextField</code> object is a text component
* that allows for the editing of a single line of text.
* <p>
* For example, the following image depicts a frame with four
* text fields of varying widths. Two of these text fields
* display the predefined text <code>"Hello"</code>.
* <p>
* <img src="doc-files/TextField-1.gif" alt="The preceding text describes this image."
* ALIGN=center HSPACE=10 VSPACE=7>
* <p>
* Here is the code that produces these four text fields:
* <p>
* <hr><blockquote><pre>
* TextField tf1, tf2, tf3, tf4;
* // a blank text field
* tf1 = new TextField();
* // blank field of 20 columns
* tf2 = new TextField("", 20);
* // predefined text displayed
* tf3 = new TextField("Hello!");
* // predefined text in 30 columns
* tf4 = new TextField("Hello", 30);
* </pre></blockquote><hr>
* <p>
* Every time the user types a key in the text field, one or
* more key events are sent to the text field. A <code>KeyEvent</code>
* may be one of three types: keyPressed, keyReleased, or keyTyped.
* The properties of a key event indicate which of these types
* it is, as well as additional information about the event,
* such as what modifiers are applied to the key event and the
* time at which the event occurred.
* <p>
* The key event is passed to every <code>KeyListener</code>
* or <code>KeyAdapter</code> object which registered to receive such
* events using the component's <code>addKeyListener</code> method.
* (<code>KeyAdapter</code> objects implement the
* <code>KeyListener</code> interface.)
* <p>
* It is also possible to fire an <code>ActionEvent</code>.
* If action events are enabled for the text field, they may
* be fired by pressing the <code>Return</code> key.
* <p>
* The <code>TextField</code> class's <code>processEvent</code>
* method examines the action event and passes it along to
* <code>processActionEvent</code>. The latter method redirects the
* event to any <code>ActionListener</code> objects that have
* registered to receive action events generated by this
* text field.
*
* @author Sami Shaio
* @see java.awt.event.KeyEvent
* @see java.awt.event.KeyAdapter
* @see java.awt.event.KeyListener
* @see java.awt.event.ActionEvent
* @see java.awt.Component#addKeyListener
* @see java.awt.TextField#processEvent
* @see java.awt.TextField#processActionEvent
* @see java.awt.TextField#addActionListener
* @since JDK1.0
*/
public class TextField extends TextComponent {
/** {@collect.stats}
* The number of columns in the text field.
* A column is an approximate average character
* width that is platform-dependent.
* Guaranteed to be non-negative.
*
* @serial
* @see #setColumns(int)
* @see #getColumns()
*/
int columns;
/** {@collect.stats}
* The echo character, which is used when
* the user wishes to disguise the characters
* typed into the text field.
* The disguises are removed if echoChar = <code>0</code>.
*
* @serial
* @see #getEchoChar()
* @see #setEchoChar(char)
* @see #echoCharIsSet()
*/
char echoChar;
transient ActionListener actionListener;
private static final String base = "textfield";
private static int nameCounter = 0;
/*
* JDK 1.1 serialVersionUID
*/
private static final long serialVersionUID = -2966288784432217853L;
/** {@collect.stats}
* Initialize JNI field and method ids
*/
private static native void initIDs();
static {
/* ensure that the necessary native libraries are loaded */
Toolkit.loadLibraries();
if (!GraphicsEnvironment.isHeadless()) {
initIDs();
}
}
/** {@collect.stats}
* Constructs a new text field.
* @exception HeadlessException if GraphicsEnvironment.isHeadless()
* returns true.
* @see java.awt.GraphicsEnvironment#isHeadless
*/
public TextField() throws HeadlessException {
this("", 0);
}
/** {@collect.stats}
* Constructs a new text field initialized with the specified text.
* @param text the text to be displayed. If
* <code>text</code> is <code>null</code>, the empty
* string <code>""</code> will be displayed.
* @exception HeadlessException if GraphicsEnvironment.isHeadless()
* returns true.
* @see java.awt.GraphicsEnvironment#isHeadless
*/
public TextField(String text) throws HeadlessException {
this(text, (text != null) ? text.length() : 0);
}
/** {@collect.stats}
* Constructs a new empty text field with the specified number
* of columns. A column is an approximate average character
* width that is platform-dependent.
* @param columns the number of columns. If
* <code>columns</code> is less than <code>0</code>,
* <code>columns</code> is set to <code>0</code>.
* @exception HeadlessException if GraphicsEnvironment.isHeadless()
* returns true.
* @see java.awt.GraphicsEnvironment#isHeadless
*/
public TextField(int columns) throws HeadlessException {
this("", columns);
}
/** {@collect.stats}
* Constructs a new text field initialized with the specified text
* to be displayed, and wide enough to hold the specified
* number of columns. A column is an approximate average character
* width that is platform-dependent.
* @param text the text to be displayed. If
* <code>text</code> is <code>null</code>, the empty
* string <code>""</code> will be displayed.
* @param columns the number of columns. If
* <code>columns</code> is less than <code>0</code>,
* <code>columns</code> is set to <code>0</code>.
* @exception HeadlessException if GraphicsEnvironment.isHeadless()
* returns true.
* @see java.awt.GraphicsEnvironment#isHeadless
*/
public TextField(String text, int columns) throws HeadlessException {
super(text);
this.columns = (columns >= 0) ? columns : 0;
}
/** {@collect.stats}
* Construct a name for this component. Called by getName() when the
* name is null.
*/
String constructComponentName() {
synchronized (TextField.class) {
return base + nameCounter++;
}
}
/** {@collect.stats}
* Creates the TextField's peer. The peer allows us to modify the
* appearance of the TextField without changing its functionality.
*/
public void addNotify() {
synchronized (getTreeLock()) {
if (peer == null)
peer = getToolkit().createTextField(this);
super.addNotify();
}
}
/** {@collect.stats}
* Gets the character that is to be used for echoing.
* <p>
* An echo character is useful for text fields where
* user input should not be echoed to the screen, as in
* the case of a text field for entering a password.
* If <code>echoChar</code> = <code>0</code>, user
* input is echoed to the screen unchanged.
* <p>
* A Java platform implementation may support only a limited,
* non-empty set of echo characters. This function returns the
* echo character originally requested via setEchoChar(). The echo
* character actually used by the TextField implementation might be
* different.
* @return the echo character for this text field.
* @see java.awt.TextField#echoCharIsSet
* @see java.awt.TextField#setEchoChar
*/
public char getEchoChar() {
return echoChar;
}
/** {@collect.stats}
* Sets the echo character for this text field.
* <p>
* An echo character is useful for text fields where
* user input should not be echoed to the screen, as in
* the case of a text field for entering a password.
* Setting <code>echoChar</code> = <code>0</code> allows
* user input to be echoed to the screen again.
* <p>
* A Java platform implementation may support only a limited,
* non-empty set of echo characters. Attempts to set an
* unsupported echo character will cause the default echo
* character to be used instead. Subsequent calls to getEchoChar()
* will return the echo character originally requested. This might
* or might not be identical to the echo character actually
* used by the TextField implementation.
* @param c the echo character for this text field.
* @see java.awt.TextField#echoCharIsSet
* @see java.awt.TextField#getEchoChar
* @since JDK1.1
*/
public void setEchoChar(char c) {
setEchoCharacter(c);
}
/** {@collect.stats}
* @deprecated As of JDK version 1.1,
* replaced by <code>setEchoChar(char)</code>.
*/
@Deprecated
public synchronized void setEchoCharacter(char c) {
if (echoChar != c) {
echoChar = c;
TextFieldPeer peer = (TextFieldPeer)this.peer;
if (peer != null) {
peer.setEchoCharacter(c);
}
}
}
/** {@collect.stats}
* Sets the text that is presented by this
* text component to be the specified text.
* @param t the new text.
* @see java.awt.TextComponent#getText
*/
public void setText(String t) {
super.setText(t);
// This could change the preferred size of the Component.
if (valid) {
invalidate();
}
}
/** {@collect.stats}
* Indicates whether or not this text field has a
* character set for echoing.
* <p>
* An echo character is useful for text fields where
* user input should not be echoed to the screen, as in
* the case of a text field for entering a password.
* @return <code>true</code> if this text field has
* a character set for echoing;
* <code>false</code> otherwise.
* @see java.awt.TextField#setEchoChar
* @see java.awt.TextField#getEchoChar
*/
public boolean echoCharIsSet() {
return echoChar != 0;
}
/** {@collect.stats}
* Gets the number of columns in this text field. A column is an
* approximate average character width that is platform-dependent.
* @return the number of columns.
* @see java.awt.TextField#setColumns
* @since JDK1.1
*/
public int getColumns() {
return columns;
}
/** {@collect.stats}
* Sets the number of columns in this text field. A column is an
* approximate average character width that is platform-dependent.
* @param columns the number of columns.
* @see java.awt.TextField#getColumns
* @exception IllegalArgumentException if the value
* supplied for <code>columns</code>
* is less than <code>0</code>.
* @since JDK1.1
*/
public void setColumns(int columns) {
int oldVal;
synchronized (this) {
oldVal = this.columns;
if (columns < 0) {
throw new IllegalArgumentException("columns less than zero.");
}
if (columns != oldVal) {
this.columns = columns;
}
}
if (columns != oldVal) {
invalidate();
}
}
/** {@collect.stats}
* Gets the preferred size of this text field
* with the specified number of columns.
* @param columns the number of columns
* in this text field.
* @return the preferred dimensions for
* displaying this text field.
* @since JDK1.1
*/
public Dimension getPreferredSize(int columns) {
return preferredSize(columns);
}
/** {@collect.stats}
* @deprecated As of JDK version 1.1,
* replaced by <code>getPreferredSize(int)</code>.
*/
@Deprecated
public Dimension preferredSize(int columns) {
synchronized (getTreeLock()) {
TextFieldPeer peer = (TextFieldPeer)this.peer;
return (peer != null) ?
peer.preferredSize(columns) :
super.preferredSize();
}
}
/** {@collect.stats}
* Gets the preferred size of this text field.
* @return the preferred dimensions for
* displaying this text field.
* @since JDK1.1
*/
public Dimension getPreferredSize() {
return preferredSize();
}
/** {@collect.stats}
* @deprecated As of JDK version 1.1,
* replaced by <code>getPreferredSize()</code>.
*/
@Deprecated
public Dimension preferredSize() {
synchronized (getTreeLock()) {
return (columns > 0) ?
preferredSize(columns) :
super.preferredSize();
}
}
/** {@collect.stats}
* Gets the minumum dimensions for a text field with
* the specified number of columns.
* @param columns the number of columns in
* this text field.
* @since JDK1.1
*/
public Dimension getMinimumSize(int columns) {
return minimumSize(columns);
}
/** {@collect.stats}
* @deprecated As of JDK version 1.1,
* replaced by <code>getMinimumSize(int)</code>.
*/
@Deprecated
public Dimension minimumSize(int columns) {
synchronized (getTreeLock()) {
TextFieldPeer peer = (TextFieldPeer)this.peer;
return (peer != null) ?
peer.minimumSize(columns) :
super.minimumSize();
}
}
/** {@collect.stats}
* Gets the minumum dimensions for this text field.
* @return the minimum dimensions for
* displaying this text field.
* @since JDK1.1
*/
public Dimension getMinimumSize() {
return minimumSize();
}
/** {@collect.stats}
* @deprecated As of JDK version 1.1,
* replaced by <code>getMinimumSize()</code>.
*/
@Deprecated
public Dimension minimumSize() {
synchronized (getTreeLock()) {
return (columns > 0) ?
minimumSize(columns) :
super.minimumSize();
}
}
/** {@collect.stats}
* Adds the specified action listener to receive
* action events from this text field.
* If l is null, no exception is thrown and no action is performed.
* <p>Refer to <a href="doc-files/AWTThreadIssues.html#ListenersThreads"
* >AWT Threading Issues</a> for details on AWT's threading model.
*
* @param l the action listener.
* @see #removeActionListener
* @see #getActionListeners
* @see java.awt.event.ActionListener
* @since JDK1.1
*/
public synchronized void addActionListener(ActionListener l) {
if (l == null) {
return;
}
actionListener = AWTEventMulticaster.add(actionListener, l);
newEventsOnly = true;
}
/** {@collect.stats}
* Removes the specified action listener so that it no longer
* receives action events from this text field.
* If l is null, no exception is thrown and no action is performed.
* <p>Refer to <a href="doc-files/AWTThreadIssues.html#ListenersThreads"
* >AWT Threading Issues</a> for details on AWT's threading model.
*
* @param l the action listener.
* @see #addActionListener
* @see #getActionListeners
* @see java.awt.event.ActionListener
* @since JDK1.1
*/
public synchronized void removeActionListener(ActionListener l) {
if (l == null) {
return;
}
actionListener = AWTEventMulticaster.remove(actionListener, l);
}
/** {@collect.stats}
* Returns an array of all the action listeners
* registered on this textfield.
*
* @return all of this textfield's <code>ActionListener</code>s
* or an empty array if no action
* listeners are currently registered
*
* @see #addActionListener
* @see #removeActionListener
* @see java.awt.event#ActionListener
* @since 1.4
*/
public synchronized ActionListener[] getActionListeners() {
return (ActionListener[])(getListeners(ActionListener.class));
}
/** {@collect.stats}
* Returns an array of all the objects currently registered
* as <code><em>Foo</em>Listener</code>s
* upon this <code>TextField</code>.
* <code><em>Foo</em>Listener</code>s are registered using the
* <code>add<em>Foo</em>Listener</code> method.
*
* <p>
* You can specify the <code>listenerType</code> argument
* with a class literal, such as
* <code><em>Foo</em>Listener.class</code>.
* For example, you can query a
* <code>TextField</code> <code>t</code>
* for its action listeners with the following code:
*
* <pre>ActionListener[] als = (ActionListener[])(t.getListeners(ActionListener.class));</pre>
*
* If no such listeners exist, this method returns an empty array.
*
* @param listenerType the type of listeners requested; this parameter
* should specify an interface that descends from
* <code>java.util.EventListener</code>
* @return an array of all objects registered as
* <code><em>Foo</em>Listener</code>s on this textfield,
* or an empty array if no such
* listeners have been added
* @exception ClassCastException if <code>listenerType</code>
* doesn't specify a class or interface that implements
* <code>java.util.EventListener</code>
*
* @see #getActionListeners
* @since 1.3
*/
public <T extends EventListener> T[] getListeners(Class<T> listenerType) {
EventListener l = null;
if (listenerType == ActionListener.class) {
l = actionListener;
} else {
return super.getListeners(listenerType);
}
return AWTEventMulticaster.getListeners(l, listenerType);
}
// REMIND: remove when filtering is done at lower level
boolean eventEnabled(AWTEvent e) {
if (e.id == ActionEvent.ACTION_PERFORMED) {
if ((eventMask & AWTEvent.ACTION_EVENT_MASK) != 0 ||
actionListener != null) {
return true;
}
return false;
}
return super.eventEnabled(e);
}
/** {@collect.stats}
* Processes events on this text field. If the event
* is an instance of <code>ActionEvent</code>,
* it invokes the <code>processActionEvent</code>
* method. Otherwise, it invokes <code>processEvent</code>
* on the superclass.
* <p>Note that if the event parameter is <code>null</code>
* the behavior is unspecified and may result in an
* exception.
*
* @param e the event
* @see java.awt.event.ActionEvent
* @see java.awt.TextField#processActionEvent
* @since JDK1.1
*/
protected void processEvent(AWTEvent e) {
if (e instanceof ActionEvent) {
processActionEvent((ActionEvent)e);
return;
}
super.processEvent(e);
}
/** {@collect.stats}
* Processes action events occurring on this text field by
* dispatching them to any registered
* <code>ActionListener</code> objects.
* <p>
* This method is not called unless action events are
* enabled for this component. Action events are enabled
* when one of the following occurs:
* <p><ul>
* <li>An <code>ActionListener</code> object is registered
* via <code>addActionListener</code>.
* <li>Action events are enabled via <code>enableEvents</code>.
* </ul>
* <p>Note that if the event parameter is <code>null</code>
* the behavior is unspecified and may result in an
* exception.
*
* @param e the action event
* @see java.awt.event.ActionListener
* @see java.awt.TextField#addActionListener
* @see java.awt.Component#enableEvents
* @since JDK1.1
*/
protected void processActionEvent(ActionEvent e) {
ActionListener listener = actionListener;
if (listener != null) {
listener.actionPerformed(e);
}
}
/** {@collect.stats}
* Returns a string representing the state of this <code>TextField</code>.
* This method is intended to be used only for debugging purposes, and the
* content and format of the returned string may vary between
* implementations. The returned string may be empty but may not be
* <code>null</code>.
*
* @return the parameter string of this text field
*/
protected String paramString() {
String str = super.paramString();
if (echoChar != 0) {
str += ",echo=" + echoChar;
}
return str;
}
/*
* Serialization support.
*/
/** {@collect.stats}
* The textField Serialized Data Version.
*
* @serial
*/
private int textFieldSerializedDataVersion = 1;
/** {@collect.stats}
* Writes default serializable fields to stream. Writes
* a list of serializable ActionListener(s) as optional data.
* The non-serializable ActionListener(s) are detected and
* no attempt is made to serialize them.
*
* @serialData Null terminated sequence of zero or more pairs.
* A pair consists of a String and Object.
* The String indicates the type of object and
* is one of the following :
* ActionListenerK indicating and ActionListener object.
*
* @see AWTEventMulticaster#save(ObjectOutputStream, String, EventListener)
* @see java.awt.Component#actionListenerK
*/
private void writeObject(ObjectOutputStream s)
throws IOException
{
s.defaultWriteObject();
AWTEventMulticaster.save(s, actionListenerK, actionListener);
s.writeObject(null);
}
/** {@collect.stats}
* Read the ObjectInputStream and if it isn't null,
* add a listener to receive action events fired by the
* TextField. Unrecognized keys or values will be
* ignored.
*
* @exception HeadlessException if
* <code>GraphicsEnvironment.isHeadless()</code> returns
* <code>true</code>
* @see #removeActionListener(ActionListener)
* @see #addActionListener(ActionListener)
* @see java.awt.GraphicsEnvironment#isHeadless
*/
private void readObject(ObjectInputStream s)
throws ClassNotFoundException, IOException, HeadlessException
{
// HeadlessException will be thrown by TextComponent's readObject
s.defaultReadObject();
// Make sure the state we just read in for columns has legal values
if (columns < 0) {
columns = 0;
}
// Read in listeners, if any
Object keyOrNull;
while(null != (keyOrNull = s.readObject())) {
String key = ((String)keyOrNull).intern();
if (actionListenerK == key) {
addActionListener((ActionListener)(s.readObject()));
} else {
// skip value for unrecognized key
s.readObject();
}
}
}
/////////////////
// Accessibility support
////////////////
/** {@collect.stats}
* Gets the AccessibleContext associated with this TextField.
* For text fields, the AccessibleContext takes the form of an
* AccessibleAWTTextField.
* A new AccessibleAWTTextField instance is created if necessary.
*
* @return an AccessibleAWTTextField that serves as the
* AccessibleContext of this TextField
* @since 1.3
*/
public AccessibleContext getAccessibleContext() {
if (accessibleContext == null) {
accessibleContext = new AccessibleAWTTextField();
}
return accessibleContext;
}
/** {@collect.stats}
* This class implements accessibility support for the
* <code>TextField</code> class. It provides an implementation of the
* Java Accessibility API appropriate to text field user-interface elements.
* @since 1.3
*/
protected class AccessibleAWTTextField extends AccessibleAWTTextComponent
{
/*
* JDK 1.3 serialVersionUID
*/
private static final long serialVersionUID = 6219164359235943158L;
/** {@collect.stats}
* Gets the state set of this object.
*
* @return an instance of AccessibleStateSet describing the states
* of the object
* @see AccessibleState
*/
public AccessibleStateSet getAccessibleStateSet() {
AccessibleStateSet states = super.getAccessibleStateSet();
states.add(AccessibleState.SINGLE_LINE);
return states;
}
}
}
|
Java
|
/*
* Copyright (c) 2006, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code 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
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package java.awt;
import java.awt.MultipleGradientPaint.CycleMethod;
import java.awt.MultipleGradientPaint.ColorSpaceType;
import java.awt.geom.AffineTransform;
import java.awt.geom.Rectangle2D;
import java.awt.image.ColorModel;
/** {@collect.stats}
* Provides the actual implementation for the RadialGradientPaint.
* This is where the pixel processing is done. A RadialGradienPaint
* only supports circular gradients, but it should be possible to scale
* the circle to look approximately elliptical, by means of a
* gradient transform passed into the RadialGradientPaint constructor.
*
* @author Nicholas Talian, Vincent Hardy, Jim Graham, Jerry Evans
*/
final class RadialGradientPaintContext extends MultipleGradientPaintContext {
/** {@collect.stats} True when (focus == center). */
private boolean isSimpleFocus = false;
/** {@collect.stats} True when (cycleMethod == NO_CYCLE). */
private boolean isNonCyclic = false;
/** {@collect.stats} Radius of the outermost circle defining the 100% gradient stop. */
private float radius;
/** {@collect.stats} Variables representing center and focus points. */
private float centerX, centerY, focusX, focusY;
/** {@collect.stats} Radius of the gradient circle squared. */
private float radiusSq;
/** {@collect.stats} Constant part of X, Y user space coordinates. */
private float constA, constB;
/** {@collect.stats} Constant second order delta for simple loop. */
private float gDeltaDelta;
/** {@collect.stats}
* This value represents the solution when focusX == X. It is called
* trivial because it is easier to calculate than the general case.
*/
private float trivial;
/** {@collect.stats} Amount for offset when clamping focus. */
private static final float SCALEBACK = .99f;
/** {@collect.stats}
* Constructor for RadialGradientPaintContext.
*
* @param paint the {@code RadialGradientPaint} from which this context
* is created
* @param cm the {@code ColorModel} that receives
* the {@code Paint} data (this is used only as a hint)
* @param deviceBounds the device space bounding box of the
* graphics primitive being rendered
* @param userBounds the user space bounding box of the
* graphics primitive being rendered
* @param t the {@code AffineTransform} from user
* space into device space (gradientTransform should be
* concatenated with this)
* @param hints the hints that the context object uses to choose
* between rendering alternatives
* @param cx the center X coordinate in user space of the circle defining
* the gradient. The last color of the gradient is mapped to
* the perimeter of this circle.
* @param cy the center Y coordinate in user space of the circle defining
* the gradient. The last color of the gradient is mapped to
* the perimeter of this circle.
* @param r the radius of the circle defining the extents of the
* color gradient
* @param fx the X coordinate in user space to which the first color
* is mapped
* @param fy the Y coordinate in user space to which the first color
* is mapped
* @param fractions the fractions specifying the gradient distribution
* @param colors the gradient colors
* @param cycleMethod either NO_CYCLE, REFLECT, or REPEAT
* @param colorSpace which colorspace to use for interpolation,
* either SRGB or LINEAR_RGB
*/
RadialGradientPaintContext(RadialGradientPaint paint,
ColorModel cm,
Rectangle deviceBounds,
Rectangle2D userBounds,
AffineTransform t,
RenderingHints hints,
float cx, float cy,
float r,
float fx, float fy,
float[] fractions,
Color[] colors,
CycleMethod cycleMethod,
ColorSpaceType colorSpace)
{
super(paint, cm, deviceBounds, userBounds, t, hints,
fractions, colors, cycleMethod, colorSpace);
// copy some parameters
centerX = cx;
centerY = cy;
focusX = fx;
focusY = fy;
radius = r;
this.isSimpleFocus = (focusX == centerX) && (focusY == centerY);
this.isNonCyclic = (cycleMethod == CycleMethod.NO_CYCLE);
// for use in the quadractic equation
radiusSq = radius * radius;
float dX = focusX - centerX;
float dY = focusY - centerY;
double distSq = (dX * dX) + (dY * dY);
// test if distance from focus to center is greater than the radius
if (distSq > radiusSq * SCALEBACK) {
// clamp focus to radius
float scalefactor = (float)Math.sqrt(radiusSq * SCALEBACK / distSq);
dX = dX * scalefactor;
dY = dY * scalefactor;
focusX = centerX + dX;
focusY = centerY + dY;
}
// calculate the solution to be used in the case where X == focusX
// in cyclicCircularGradientFillRaster()
trivial = (float)Math.sqrt(radiusSq - (dX * dX));
// constant parts of X, Y user space coordinates
constA = a02 - centerX;
constB = a12 - centerY;
// constant second order delta for simple loop
gDeltaDelta = 2 * ( a00 * a00 + a10 * a10) / radiusSq;
}
/** {@collect.stats}
* Return a Raster containing the colors generated for the graphics
* operation.
*
* @param x,y,w,h the area in device space for which colors are
* generated.
*/
protected void fillRaster(int pixels[], int off, int adjust,
int x, int y, int w, int h)
{
if (isSimpleFocus && isNonCyclic && isSimpleLookup) {
simpleNonCyclicFillRaster(pixels, off, adjust, x, y, w, h);
} else {
cyclicCircularGradientFillRaster(pixels, off, adjust, x, y, w, h);
}
}
/** {@collect.stats}
* This code works in the simplest of cases, where the focus == center
* point, the gradient is noncyclic, and the gradient lookup method is
* fast (single array index, no conversion necessary).
*/
private void simpleNonCyclicFillRaster(int pixels[], int off, int adjust,
int x, int y, int w, int h)
{
/* We calculate sqrt(X^2 + Y^2) relative to the radius
* size to get the fraction for the color to use.
*
* Each step along the scanline adds (a00, a10) to (X, Y).
* If we precalculate:
* gRel = X^2+Y^2
* for the start of the row, then for each step we need to
* calculate:
* gRel' = (X+a00)^2 + (Y+a10)^2
* = X^2 + 2*X*a00 + a00^2 + Y^2 + 2*Y*a10 + a10^2
* = (X^2+Y^2) + 2*(X*a00+Y*a10) + (a00^2+a10^2)
* = gRel + 2*(X*a00+Y*a10) + (a00^2+a10^2)
* = gRel + 2*DP + SD
* (where DP = dot product between X,Y and a00,a10
* and SD = dot product square of the delta vector)
* For the step after that we get:
* gRel'' = (X+2*a00)^2 + (Y+2*a10)^2
* = X^2 + 4*X*a00 + 4*a00^2 + Y^2 + 4*Y*a10 + 4*a10^2
* = (X^2+Y^2) + 4*(X*a00+Y*a10) + 4*(a00^2+a10^2)
* = gRel + 4*DP + 4*SD
* = gRel' + 2*DP + 3*SD
* The increment changed by:
* (gRel'' - gRel') - (gRel' - gRel)
* = (2*DP + 3*SD) - (2*DP + SD)
* = 2*SD
* Note that this value depends only on the (inverse of the)
* transformation matrix and so is a constant for the loop.
* To make this all relative to the unit circle, we need to
* divide all values as follows:
* [XY] /= radius
* gRel /= radiusSq
* DP /= radiusSq
* SD /= radiusSq
*/
// coordinates of UL corner in "user space" relative to center
float rowX = (a00*x) + (a01*y) + constA;
float rowY = (a10*x) + (a11*y) + constB;
// second order delta calculated in constructor
float gDeltaDelta = this.gDeltaDelta;
// adjust is (scan-w) of pixels array, we need (scan)
adjust += w;
// rgb of the 1.0 color used when the distance exceeds gradient radius
int rgbclip = gradient[fastGradientArraySize];
for (int j = 0; j < h; j++) {
// these values depend on the coordinates of the start of the row
float gRel = (rowX * rowX + rowY * rowY) / radiusSq;
float gDelta = (2 * ( a00 * rowX + a10 * rowY) / radiusSq +
gDeltaDelta/2);
/* Use optimized loops for any cases where gRel >= 1.
* We do not need to calculate sqrt(gRel) for these
* values since sqrt(N>=1) == (M>=1).
* Note that gRel follows a parabola which can only be < 1
* for a small region around the center on each scanline. In
* particular:
* gDeltaDelta is always positive
* gDelta is <0 until it crosses the midpoint, then >0
* To the left and right of that region, it will always be
* >=1 out to infinity, so we can process the line in 3
* regions:
* out to the left - quick fill until gRel < 1, updating gRel
* in the heart - slow fraction=sqrt fill while gRel < 1
* out to the right - quick fill rest of scanline, ignore gRel
*/
int i = 0;
// Quick fill for "out to the left"
while (i < w && gRel >= 1.0f) {
pixels[off + i] = rgbclip;
gRel += gDelta;
gDelta += gDeltaDelta;
i++;
}
// Slow fill for "in the heart"
while (i < w && gRel < 1.0f) {
int gIndex;
if (gRel <= 0) {
gIndex = 0;
} else {
float fIndex = gRel * SQRT_LUT_SIZE;
int iIndex = (int) (fIndex);
float s0 = sqrtLut[iIndex];
float s1 = sqrtLut[iIndex+1] - s0;
fIndex = s0 + (fIndex - iIndex) * s1;
gIndex = (int) (fIndex * fastGradientArraySize);
}
// store the color at this point
pixels[off + i] = gradient[gIndex];
// incremental calculation
gRel += gDelta;
gDelta += gDeltaDelta;
i++;
}
// Quick fill to end of line for "out to the right"
while (i < w) {
pixels[off + i] = rgbclip;
i++;
}
off += adjust;
rowX += a01;
rowY += a11;
}
}
// SQRT_LUT_SIZE must be a power of 2 for the test above to work.
private static final int SQRT_LUT_SIZE = (1 << 11);
private static float sqrtLut[] = new float[SQRT_LUT_SIZE+1];
static {
for (int i = 0; i < sqrtLut.length; i++) {
sqrtLut[i] = (float) Math.sqrt(i / ((float) SQRT_LUT_SIZE));
}
}
/** {@collect.stats}
* Fill the raster, cycling the gradient colors when a point falls outside
* of the perimeter of the 100% stop circle.
*
* This calculation first computes the intersection point of the line
* from the focus through the current point in the raster, and the
* perimeter of the gradient circle.
*
* Then it determines the percentage distance of the current point along
* that line (focus is 0%, perimeter is 100%).
*
* Equation of a circle centered at (a,b) with radius r:
* (x-a)^2 + (y-b)^2 = r^2
* Equation of a line with slope m and y-intercept b:
* y = mx + b
* Replacing y in the circle equation and solving using the quadratic
* formula produces the following set of equations. Constant factors have
* been extracted out of the inner loop.
*/
private void cyclicCircularGradientFillRaster(int pixels[], int off,
int adjust,
int x, int y,
int w, int h)
{
// constant part of the C factor of the quadratic equation
final double constC =
-radiusSq + (centerX * centerX) + (centerY * centerY);
// coefficients of the quadratic equation (Ax^2 + Bx + C = 0)
double A, B, C;
// slope and y-intercept of the focus-perimeter line
double slope, yintcpt;
// intersection with circle X,Y coordinate
double solutionX, solutionY;
// constant parts of X, Y coordinates
final float constX = (a00*x) + (a01*y) + a02;
final float constY = (a10*x) + (a11*y) + a12;
// constants in inner loop quadratic formula
final float precalc2 = 2 * centerY;
final float precalc3 = -2 * centerX;
// value between 0 and 1 specifying position in the gradient
float g;
// determinant of quadratic formula (should always be > 0)
float det;
// sq distance from the current point to focus
float currentToFocusSq;
// sq distance from the intersect point to focus
float intersectToFocusSq;
// temp variables for change in X,Y squared
float deltaXSq, deltaYSq;
// used to index pixels array
int indexer = off;
// incremental index change for pixels array
int pixInc = w+adjust;
// for every row
for (int j = 0; j < h; j++) {
// user space point; these are constant from column to column
float X = (a01*j) + constX;
float Y = (a11*j) + constY;
// for every column (inner loop begins here)
for (int i = 0; i < w; i++) {
if (X == focusX) {
// special case to avoid divide by zero
solutionX = focusX;
solutionY = centerY;
solutionY += (Y > focusY) ? trivial : -trivial;
} else {
// slope and y-intercept of the focus-perimeter line
slope = (Y - focusY) / (X - focusX);
yintcpt = Y - (slope * X);
// use the quadratic formula to calculate the
// intersection point
A = (slope * slope) + 1;
B = precalc3 + (-2 * slope * (centerY - yintcpt));
C = constC + (yintcpt* (yintcpt - precalc2));
det = (float)Math.sqrt((B * B) - (4 * A * C));
solutionX = -B;
// choose the positive or negative root depending
// on where the X coord lies with respect to the focus
solutionX += (X < focusX)? -det : det;
solutionX = solutionX / (2 * A); // divisor
solutionY = (slope * solutionX) + yintcpt;
}
// Calculate the square of the distance from the current point
// to the focus and the square of the distance from the
// intersection point to the focus. Want the squares so we can
// do 1 square root after division instead of 2 before.
deltaXSq = X - focusX;
deltaXSq = deltaXSq * deltaXSq;
deltaYSq = Y - focusY;
deltaYSq = deltaYSq * deltaYSq;
currentToFocusSq = deltaXSq + deltaYSq;
deltaXSq = (float)solutionX - focusX;
deltaXSq = deltaXSq * deltaXSq;
deltaYSq = (float)solutionY - focusY;
deltaYSq = deltaYSq * deltaYSq;
intersectToFocusSq = deltaXSq + deltaYSq;
// get the percentage (0-1) of the current point along the
// focus-circumference line
g = (float)Math.sqrt(currentToFocusSq / intersectToFocusSq);
// store the color at this point
pixels[indexer + i] = indexIntoGradientsArrays(g);
// incremental change in X, Y
X += a00;
Y += a10;
} //end inner loop
indexer += pixInc;
} //end outer loop
}
}
|
Java
|
/*
* Copyright (c) 2001, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code 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
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package java.awt;
import java.awt.event.KeyEvent;
/** {@collect.stats}
* A KeyEventPostProcessor cooperates with the current KeyboardFocusManager
* in the final resolution of all unconsumed KeyEvents. KeyEventPostProcessors
* registered with the current KeyboardFocusManager will receive KeyEvents
* after the KeyEvents have been dispatched to and handled by their targets.
* KeyEvents that would have been otherwise discarded because no Component in
* the application currently owns the focus will also be forwarded to
* registered KeyEventPostProcessors. This will allow applications to implement
* features that require global KeyEvent post-handling, such as menu shortcuts.
* <p>
* Note that the KeyboardFocusManager itself implements KeyEventPostProcessor.
* By default, the current KeyboardFocusManager will be the final
* KeyEventPostProcessor in the chain. The current KeyboardFocusManager cannot
* be completely deregistered as a KeyEventPostProcessor. However, if a
* KeyEventPostProcessor reports that no further post-processing of the
* KeyEvent should take place, the AWT will consider the event fully handled
* and will take no additional action with regard to the event. (While it is
* possible for client code to register the current KeyboardFocusManager as
* a KeyEventPostProcessor one or more times, this is usually unnecessary and
* not recommended.)
*
* @author David Mendenhall
*
* @see KeyboardFocusManager#addKeyEventPostProcessor
* @see KeyboardFocusManager#removeKeyEventPostProcessor
* @since 1.4
*/
public interface KeyEventPostProcessor {
/** {@collect.stats}
* This method is called by the current KeyboardFocusManager, requesting
* that this KeyEventPostProcessor perform any necessary post-processing
* which should be part of the KeyEvent's final resolution. At the time
* this method is invoked, typically the KeyEvent has already been
* dispatched to and handled by its target. However, if no Component in
* the application currently owns the focus, then the KeyEvent has not
* been dispatched to any Component. Typically, KeyEvent post-processing
* will be used to implement features which require global KeyEvent
* post-handling, such as menu shortcuts. Note that if a
* KeyEventPostProcessor wishes to dispatch the KeyEvent, it must use
* <code>redispatchEvent</code> to prevent the AWT from recursively
* requesting that this KeyEventPostProcessor perform post-processing
* of the event again.
* <p>
* If an implementation of this method returns <code>false</code>, then the
* KeyEvent is passed to the next KeyEventPostProcessor in the chain,
* ending with the current KeyboardFocusManager. If an implementation
* returns <code>true</code>, the KeyEvent is assumed to have been fully
* handled (although this need not be the case), and the AWT will take no
* further action with regard to the KeyEvent. If an implementation
* consumes the KeyEvent but returns <code>false</code>, the consumed
* event will still be passed to the next KeyEventPostProcessor in the
* chain. It is important for developers to check whether the KeyEvent has
* been consumed before performing any post-processing of the KeyEvent. By
* default, the current KeyboardFocusManager will perform no post-
* processing in response to a consumed KeyEvent.
*
* @param e the KeyEvent to post-process
* @return <code>true</code> if the AWT should take no further action with
* regard to the KeyEvent; <code>false</code> otherwise
* @see KeyboardFocusManager#redispatchEvent
*/
boolean postProcessKeyEvent(KeyEvent e);
}
|
Java
|
/*
* Copyright (c) 1995, 2007, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code 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
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package java.awt;
import java.awt.image.ColorModel;
import java.awt.geom.AffineTransform;
import java.awt.geom.Rectangle2D;
import java.awt.color.ColorSpace;
/** {@collect.stats}
* The <code>Color</code> class is used to encapsulate colors in the default
* sRGB color space or colors in arbitrary color spaces identified by a
* {@link ColorSpace}. Every color has an implicit alpha value of 1.0 or
* an explicit one provided in the constructor. The alpha value
* defines the transparency of a color and can be represented by
* a float value in the range 0.0 - 1.0 or 0 - 255.
* An alpha value of 1.0 or 255 means that the color is completely
* opaque and an alpha value of 0 or 0.0 means that the color is
* completely transparent.
* When constructing a <code>Color</code> with an explicit alpha or
* getting the color/alpha components of a <code>Color</code>, the color
* components are never premultiplied by the alpha component.
* <p>
* The default color space for the Java 2D(tm) API is sRGB, a proposed
* standard RGB color space. For further information on sRGB,
* see <A href="http://www.w3.org/pub/WWW/Graphics/Color/sRGB.html">
* http://www.w3.org/pub/WWW/Graphics/Color/sRGB.html
* </A>.
* <p>
* @author Sami Shaio
* @author Arthur van Hoff
* @see ColorSpace
* @see AlphaComposite
*/
public class Color implements Paint, java.io.Serializable {
/** {@collect.stats}
* The color white. In the default sRGB space.
*/
public final static Color white = new Color(255, 255, 255);
/** {@collect.stats}
* The color white. In the default sRGB space.
* @since 1.4
*/
public final static Color WHITE = white;
/** {@collect.stats}
* The color light gray. In the default sRGB space.
*/
public final static Color lightGray = new Color(192, 192, 192);
/** {@collect.stats}
* The color light gray. In the default sRGB space.
* @since 1.4
*/
public final static Color LIGHT_GRAY = lightGray;
/** {@collect.stats}
* The color gray. In the default sRGB space.
*/
public final static Color gray = new Color(128, 128, 128);
/** {@collect.stats}
* The color gray. In the default sRGB space.
* @since 1.4
*/
public final static Color GRAY = gray;
/** {@collect.stats}
* The color dark gray. In the default sRGB space.
*/
public final static Color darkGray = new Color(64, 64, 64);
/** {@collect.stats}
* The color dark gray. In the default sRGB space.
* @since 1.4
*/
public final static Color DARK_GRAY = darkGray;
/** {@collect.stats}
* The color black. In the default sRGB space.
*/
public final static Color black = new Color(0, 0, 0);
/** {@collect.stats}
* The color black. In the default sRGB space.
* @since 1.4
*/
public final static Color BLACK = black;
/** {@collect.stats}
* The color red. In the default sRGB space.
*/
public final static Color red = new Color(255, 0, 0);
/** {@collect.stats}
* The color red. In the default sRGB space.
* @since 1.4
*/
public final static Color RED = red;
/** {@collect.stats}
* The color pink. In the default sRGB space.
*/
public final static Color pink = new Color(255, 175, 175);
/** {@collect.stats}
* The color pink. In the default sRGB space.
* @since 1.4
*/
public final static Color PINK = pink;
/** {@collect.stats}
* The color orange. In the default sRGB space.
*/
public final static Color orange = new Color(255, 200, 0);
/** {@collect.stats}
* The color orange. In the default sRGB space.
* @since 1.4
*/
public final static Color ORANGE = orange;
/** {@collect.stats}
* The color yellow. In the default sRGB space.
*/
public final static Color yellow = new Color(255, 255, 0);
/** {@collect.stats}
* The color yellow. In the default sRGB space.
* @since 1.4
*/
public final static Color YELLOW = yellow;
/** {@collect.stats}
* The color green. In the default sRGB space.
*/
public final static Color green = new Color(0, 255, 0);
/** {@collect.stats}
* The color green. In the default sRGB space.
* @since 1.4
*/
public final static Color GREEN = green;
/** {@collect.stats}
* The color magenta. In the default sRGB space.
*/
public final static Color magenta = new Color(255, 0, 255);
/** {@collect.stats}
* The color magenta. In the default sRGB space.
* @since 1.4
*/
public final static Color MAGENTA = magenta;
/** {@collect.stats}
* The color cyan. In the default sRGB space.
*/
public final static Color cyan = new Color(0, 255, 255);
/** {@collect.stats}
* The color cyan. In the default sRGB space.
* @since 1.4
*/
public final static Color CYAN = cyan;
/** {@collect.stats}
* The color blue. In the default sRGB space.
*/
public final static Color blue = new Color(0, 0, 255);
/** {@collect.stats}
* The color blue. In the default sRGB space.
* @since 1.4
*/
public final static Color BLUE = blue;
/** {@collect.stats}
* The color value.
* @serial
* @see #getRGB
*/
int value;
/** {@collect.stats}
* The color value in the default sRGB <code>ColorSpace</code> as
* <code>float</code> components (no alpha).
* If <code>null</code> after object construction, this must be an
* sRGB color constructed with 8-bit precision, so compute from the
* <code>int</code> color value.
* @serial
* @see #getRGBColorComponents
* @see #getRGBComponents
*/
private float frgbvalue[] = null;
/** {@collect.stats}
* The color value in the native <code>ColorSpace</code> as
* <code>float</code> components (no alpha).
* If <code>null</code> after object construction, this must be an
* sRGB color constructed with 8-bit precision, so compute from the
* <code>int</code> color value.
* @serial
* @see #getRGBColorComponents
* @see #getRGBComponents
*/
private float fvalue[] = null;
/** {@collect.stats}
* The alpha value as a <code>float</code> component.
* If <code>frgbvalue</code> is <code>null</code>, this is not valid
* data, so compute from the <code>int</code> color value.
* @serial
* @see #getRGBComponents
* @see #getComponents
*/
private float falpha = 0.0f;
/** {@collect.stats}
* The <code>ColorSpace</code>. If <code>null</code>, then it's
* default is sRGB.
* @serial
* @see #getColor
* @see #getColorSpace
* @see #getColorComponents
*/
private ColorSpace cs = null;
/** {@collect.stats}
* The <code>PaintContext</code> for this solid color.
* @see #createContext
*/
private transient ColorPaintContext context;
/*
* JDK 1.1 serialVersionUID
*/
private static final long serialVersionUID = 118526816881161077L;
/** {@collect.stats}
* Initialize JNI field and method IDs
*/
private static native void initIDs();
static {
/** {@collect.stats} 4112352 - Calling getDefaultToolkit()
** here can cause this class to be accessed before it is fully
** initialized. DON'T DO IT!!!
**
** Toolkit.getDefaultToolkit();
**/
/* ensure that the necessary native libraries are loaded */
Toolkit.loadLibraries();
if (!GraphicsEnvironment.isHeadless()) {
initIDs();
}
}
/** {@collect.stats}
* Checks the color integer components supplied for validity.
* Throws an {@link IllegalArgumentException} if the value is out of
* range.
* @param r the Red component
* @param g the Green component
* @param b the Blue component
**/
private static void testColorValueRange(int r, int g, int b, int a) {
boolean rangeError = false;
String badComponentString = "";
if ( a < 0 || a > 255) {
rangeError = true;
badComponentString = badComponentString + " Alpha";
}
if ( r < 0 || r > 255) {
rangeError = true;
badComponentString = badComponentString + " Red";
}
if ( g < 0 || g > 255) {
rangeError = true;
badComponentString = badComponentString + " Green";
}
if ( b < 0 || b > 255) {
rangeError = true;
badComponentString = badComponentString + " Blue";
}
if ( rangeError == true ) {
throw new IllegalArgumentException("Color parameter outside of expected range:"
+ badComponentString);
}
}
/** {@collect.stats}
* Checks the color <code>float</code> components supplied for
* validity.
* Throws an <code>IllegalArgumentException</code> if the value is out
* of range.
* @param r the Red component
* @param g the Green component
* @param b the Blue component
**/
private static void testColorValueRange(float r, float g, float b, float a) {
boolean rangeError = false;
String badComponentString = "";
if ( a < 0.0 || a > 1.0) {
rangeError = true;
badComponentString = badComponentString + " Alpha";
}
if ( r < 0.0 || r > 1.0) {
rangeError = true;
badComponentString = badComponentString + " Red";
}
if ( g < 0.0 || g > 1.0) {
rangeError = true;
badComponentString = badComponentString + " Green";
}
if ( b < 0.0 || b > 1.0) {
rangeError = true;
badComponentString = badComponentString + " Blue";
}
if ( rangeError == true ) {
throw new IllegalArgumentException("Color parameter outside of expected range:"
+ badComponentString);
}
}
/** {@collect.stats}
* Creates an opaque sRGB color with the specified red, green,
* and blue values in the range (0 - 255).
* The actual color used in rendering depends
* on finding the best match given the color space
* available for a given output device.
* Alpha is defaulted to 255.
*
* @throws IllegalArgumentException if <code>r</code>, <code>g</code>
* or <code>b</code> are outside of the range
* 0 to 255, inclusive
* @param r the red component
* @param g the green component
* @param b the blue component
* @see #getRed
* @see #getGreen
* @see #getBlue
* @see #getRGB
*/
public Color(int r, int g, int b) {
this(r, g, b, 255);
}
/** {@collect.stats}
* Creates an sRGB color with the specified red, green, blue, and alpha
* values in the range (0 - 255).
*
* @throws IllegalArgumentException if <code>r</code>, <code>g</code>,
* <code>b</code> or <code>a</code> are outside of the range
* 0 to 255, inclusive
* @param r the red component
* @param g the green component
* @param b the blue component
* @param a the alpha component
* @see #getRed
* @see #getGreen
* @see #getBlue
* @see #getAlpha
* @see #getRGB
*/
public Color(int r, int g, int b, int a) {
value = ((a & 0xFF) << 24) |
((r & 0xFF) << 16) |
((g & 0xFF) << 8) |
((b & 0xFF) << 0);
testColorValueRange(r,g,b,a);
}
/** {@collect.stats}
* Creates an opaque sRGB color with the specified combined RGB value
* consisting of the red component in bits 16-23, the green component
* in bits 8-15, and the blue component in bits 0-7. The actual color
* used in rendering depends on finding the best match given the
* color space available for a particular output device. Alpha is
* defaulted to 255.
*
* @param rgb the combined RGB components
* @see java.awt.image.ColorModel#getRGBdefault
* @see #getRed
* @see #getGreen
* @see #getBlue
* @see #getRGB
*/
public Color(int rgb) {
value = 0xff000000 | rgb;
}
/** {@collect.stats}
* Creates an sRGB color with the specified combined RGBA value consisting
* of the alpha component in bits 24-31, the red component in bits 16-23,
* the green component in bits 8-15, and the blue component in bits 0-7.
* If the <code>hasalpha</code> argument is <code>false</code>, alpha
* is defaulted to 255.
*
* @param rgba the combined RGBA components
* @param hasalpha <code>true</code> if the alpha bits are valid;
* <code>false</code> otherwise
* @see java.awt.image.ColorModel#getRGBdefault
* @see #getRed
* @see #getGreen
* @see #getBlue
* @see #getAlpha
* @see #getRGB
*/
public Color(int rgba, boolean hasalpha) {
if (hasalpha) {
value = rgba;
} else {
value = 0xff000000 | rgba;
}
}
/** {@collect.stats}
* Creates an opaque sRGB color with the specified red, green, and blue
* values in the range (0.0 - 1.0). Alpha is defaulted to 1.0. The
* actual color used in rendering depends on finding the best
* match given the color space available for a particular output
* device.
*
* @throws IllegalArgumentException if <code>r</code>, <code>g</code>
* or <code>b</code> are outside of the range
* 0.0 to 1.0, inclusive
* @param r the red component
* @param g the green component
* @param b the blue component
* @see #getRed
* @see #getGreen
* @see #getBlue
* @see #getRGB
*/
public Color(float r, float g, float b) {
this( (int) (r*255+0.5), (int) (g*255+0.5), (int) (b*255+0.5));
testColorValueRange(r,g,b,1.0f);
frgbvalue = new float[3];
frgbvalue[0] = r;
frgbvalue[1] = g;
frgbvalue[2] = b;
falpha = 1.0f;
fvalue = frgbvalue;
}
/** {@collect.stats}
* Creates an sRGB color with the specified red, green, blue, and
* alpha values in the range (0.0 - 1.0). The actual color
* used in rendering depends on finding the best match given the
* color space available for a particular output device.
* @throws IllegalArgumentException if <code>r</code>, <code>g</code>
* <code>b</code> or <code>a</code> are outside of the range
* 0.0 to 1.0, inclusive
* @param r the red component
* @param g the green component
* @param b the blue component
* @param a the alpha component
* @see #getRed
* @see #getGreen
* @see #getBlue
* @see #getAlpha
* @see #getRGB
*/
public Color(float r, float g, float b, float a) {
this((int)(r*255+0.5), (int)(g*255+0.5), (int)(b*255+0.5), (int)(a*255+0.5));
frgbvalue = new float[3];
frgbvalue[0] = r;
frgbvalue[1] = g;
frgbvalue[2] = b;
falpha = a;
fvalue = frgbvalue;
}
/** {@collect.stats}
* Creates a color in the specified <code>ColorSpace</code>
* with the color components specified in the <code>float</code>
* array and the specified alpha. The number of components is
* determined by the type of the <code>ColorSpace</code>. For
* example, RGB requires 3 components, but CMYK requires 4
* components.
* @param cspace the <code>ColorSpace</code> to be used to
* interpret the components
* @param components an arbitrary number of color components
* that is compatible with the <code>ColorSpace</code>
* @param alpha alpha value
* @throws IllegalArgumentException if any of the values in the
* <code>components</code> array or <code>alpha</code> is
* outside of the range 0.0 to 1.0
* @see #getComponents
* @see #getColorComponents
*/
public Color(ColorSpace cspace, float components[], float alpha) {
boolean rangeError = false;
String badComponentString = "";
int n = cspace.getNumComponents();
fvalue = new float[n];
for (int i = 0; i < n; i++) {
if (components[i] < 0.0 || components[i] > 1.0) {
rangeError = true;
badComponentString = badComponentString + "Component " + i
+ " ";
} else {
fvalue[i] = components[i];
}
}
if (alpha < 0.0 || alpha > 1.0) {
rangeError = true;
badComponentString = badComponentString + "Alpha";
} else {
falpha = alpha;
}
if (rangeError) {
throw new IllegalArgumentException(
"Color parameter outside of expected range: " +
badComponentString);
}
frgbvalue = cspace.toRGB(fvalue);
cs = cspace;
value = ((((int)(falpha*255)) & 0xFF) << 24) |
((((int)(frgbvalue[0]*255)) & 0xFF) << 16) |
((((int)(frgbvalue[1]*255)) & 0xFF) << 8) |
((((int)(frgbvalue[2]*255)) & 0xFF) << 0);
}
/** {@collect.stats}
* Returns the red component in the range 0-255 in the default sRGB
* space.
* @return the red component.
* @see #getRGB
*/
public int getRed() {
return (getRGB() >> 16) & 0xFF;
}
/** {@collect.stats}
* Returns the green component in the range 0-255 in the default sRGB
* space.
* @return the green component.
* @see #getRGB
*/
public int getGreen() {
return (getRGB() >> 8) & 0xFF;
}
/** {@collect.stats}
* Returns the blue component in the range 0-255 in the default sRGB
* space.
* @return the blue component.
* @see #getRGB
*/
public int getBlue() {
return (getRGB() >> 0) & 0xFF;
}
/** {@collect.stats}
* Returns the alpha component in the range 0-255.
* @return the alpha component.
* @see #getRGB
*/
public int getAlpha() {
return (getRGB() >> 24) & 0xff;
}
/** {@collect.stats}
* Returns the RGB value representing the color in the default sRGB
* {@link ColorModel}.
* (Bits 24-31 are alpha, 16-23 are red, 8-15 are green, 0-7 are
* blue).
* @return the RGB value of the color in the default sRGB
* <code>ColorModel</code>.
* @see java.awt.image.ColorModel#getRGBdefault
* @see #getRed
* @see #getGreen
* @see #getBlue
* @since JDK1.0
*/
public int getRGB() {
return value;
}
private static final double FACTOR = 0.7;
/** {@collect.stats}
* Creates a new <code>Color</code> that is a brighter version of this
* <code>Color</code>.
* <p>
* This method applies an arbitrary scale factor to each of the three RGB
* components of this <code>Color</code> to create a brighter version
* of this <code>Color</code>. Although <code>brighter</code> and
* <code>darker</code> are inverse operations, the results of a
* series of invocations of these two methods might be inconsistent
* because of rounding errors.
* @return a new <code>Color</code> object that is
* a brighter version of this <code>Color</code>.
* @see java.awt.Color#darker
* @since JDK1.0
*/
public Color brighter() {
int r = getRed();
int g = getGreen();
int b = getBlue();
/* From 2D group:
* 1. black.brighter() should return grey
* 2. applying brighter to blue will always return blue, brighter
* 3. non pure color (non zero rgb) will eventually return white
*/
int i = (int)(1.0/(1.0-FACTOR));
if ( r == 0 && g == 0 && b == 0) {
return new Color(i, i, i);
}
if ( r > 0 && r < i ) r = i;
if ( g > 0 && g < i ) g = i;
if ( b > 0 && b < i ) b = i;
return new Color(Math.min((int)(r/FACTOR), 255),
Math.min((int)(g/FACTOR), 255),
Math.min((int)(b/FACTOR), 255));
}
/** {@collect.stats}
* Creates a new <code>Color</code> that is a darker version of this
* <code>Color</code>.
* <p>
* This method applies an arbitrary scale factor to each of the three RGB
* components of this <code>Color</code> to create a darker version of
* this <code>Color</code>. Although <code>brighter</code> and
* <code>darker</code> are inverse operations, the results of a series
* of invocations of these two methods might be inconsistent because
* of rounding errors.
* @return a new <code>Color</code> object that is
* a darker version of this <code>Color</code>.
* @see java.awt.Color#brighter
* @since JDK1.0
*/
public Color darker() {
return new Color(Math.max((int)(getRed() *FACTOR), 0),
Math.max((int)(getGreen()*FACTOR), 0),
Math.max((int)(getBlue() *FACTOR), 0));
}
/** {@collect.stats}
* Computes the hash code for this <code>Color</code>.
* @return a hash code value for this object.
* @since JDK1.0
*/
public int hashCode() {
return value;
}
/** {@collect.stats}
* Determines whether another object is equal to this
* <code>Color</code>.
* <p>
* The result is <code>true</code> if and only if the argument is not
* <code>null</code> and is a <code>Color</code> object that has the same
* red, green, blue, and alpha values as this object.
* @param obj the object to test for equality with this
* <code>Color</code>
* @return <code>true</code> if the objects are the same;
* <code>false</code> otherwise.
* @since JDK1.0
*/
public boolean equals(Object obj) {
return obj instanceof Color && ((Color)obj).getRGB() == this.getRGB();
}
/** {@collect.stats}
* Returns a string representation of this <code>Color</code>. This
* method is intended to be used only for debugging purposes. The
* content and format of the returned string might vary between
* implementations. The returned string might be empty but cannot
* be <code>null</code>.
*
* @return a string representation of this <code>Color</code>.
*/
public String toString() {
return getClass().getName() + "[r=" + getRed() + ",g=" + getGreen() + ",b=" + getBlue() + "]";
}
/** {@collect.stats}
* Converts a <code>String</code> to an integer and returns the
* specified opaque <code>Color</code>. This method handles string
* formats that are used to represent octal and hexadecimal numbers.
* @param nm a <code>String</code> that represents
* an opaque color as a 24-bit integer
* @return the new <code>Color</code> object.
* @see java.lang.Integer#decode
* @exception NumberFormatException if the specified string cannot
* be interpreted as a decimal,
* octal, or hexadecimal integer.
* @since JDK1.1
*/
public static Color decode(String nm) throws NumberFormatException {
Integer intval = Integer.decode(nm);
int i = intval.intValue();
return new Color((i >> 16) & 0xFF, (i >> 8) & 0xFF, i & 0xFF);
}
/** {@collect.stats}
* Finds a color in the system properties.
* <p>
* The argument is treated as the name of a system property to
* be obtained. The string value of this property is then interpreted
* as an integer which is then converted to a <code>Color</code>
* object.
* <p>
* If the specified property is not found or could not be parsed as
* an integer then <code>null</code> is returned.
* @param nm the name of the color property
* @return the <code>Color</code> converted from the system
* property.
* @see java.lang.System#getProperty(java.lang.String)
* @see java.lang.Integer#getInteger(java.lang.String)
* @see java.awt.Color#Color(int)
* @since JDK1.0
*/
public static Color getColor(String nm) {
return getColor(nm, null);
}
/** {@collect.stats}
* Finds a color in the system properties.
* <p>
* The first argument is treated as the name of a system property to
* be obtained. The string value of this property is then interpreted
* as an integer which is then converted to a <code>Color</code>
* object.
* <p>
* If the specified property is not found or cannot be parsed as
* an integer then the <code>Color</code> specified by the second
* argument is returned instead.
* @param nm the name of the color property
* @param v the default <code>Color</code>
* @return the <code>Color</code> converted from the system
* property, or the specified <code>Color</code>.
* @see java.lang.System#getProperty(java.lang.String)
* @see java.lang.Integer#getInteger(java.lang.String)
* @see java.awt.Color#Color(int)
* @since JDK1.0
*/
public static Color getColor(String nm, Color v) {
Integer intval = Integer.getInteger(nm);
if (intval == null) {
return v;
}
int i = intval.intValue();
return new Color((i >> 16) & 0xFF, (i >> 8) & 0xFF, i & 0xFF);
}
/** {@collect.stats}
* Finds a color in the system properties.
* <p>
* The first argument is treated as the name of a system property to
* be obtained. The string value of this property is then interpreted
* as an integer which is then converted to a <code>Color</code>
* object.
* <p>
* If the specified property is not found or could not be parsed as
* an integer then the integer value <code>v</code> is used instead,
* and is converted to a <code>Color</code> object.
* @param nm the name of the color property
* @param v the default color value, as an integer
* @return the <code>Color</code> converted from the system
* property or the <code>Color</code> converted from
* the specified integer.
* @see java.lang.System#getProperty(java.lang.String)
* @see java.lang.Integer#getInteger(java.lang.String)
* @see java.awt.Color#Color(int)
* @since JDK1.0
*/
public static Color getColor(String nm, int v) {
Integer intval = Integer.getInteger(nm);
int i = (intval != null) ? intval.intValue() : v;
return new Color((i >> 16) & 0xFF, (i >> 8) & 0xFF, (i >> 0) & 0xFF);
}
/** {@collect.stats}
* Converts the components of a color, as specified by the HSB
* model, to an equivalent set of values for the default RGB model.
* <p>
* The <code>saturation</code> and <code>brightness</code> components
* should be floating-point values between zero and one
* (numbers in the range 0.0-1.0). The <code>hue</code> component
* can be any floating-point number. The floor of this number is
* subtracted from it to create a fraction between 0 and 1. This
* fractional number is then multiplied by 360 to produce the hue
* angle in the HSB color model.
* <p>
* The integer that is returned by <code>HSBtoRGB</code> encodes the
* value of a color in bits 0-23 of an integer value that is the same
* format used by the method {@link #getRGB() <code>getRGB</code>}.
* This integer can be supplied as an argument to the
* <code>Color</code> constructor that takes a single integer argument.
* @param hue the hue component of the color
* @param saturation the saturation of the color
* @param brightness the brightness of the color
* @return the RGB value of the color with the indicated hue,
* saturation, and brightness.
* @see java.awt.Color#getRGB()
* @see java.awt.Color#Color(int)
* @see java.awt.image.ColorModel#getRGBdefault()
* @since JDK1.0
*/
public static int HSBtoRGB(float hue, float saturation, float brightness) {
int r = 0, g = 0, b = 0;
if (saturation == 0) {
r = g = b = (int) (brightness * 255.0f + 0.5f);
} else {
float h = (hue - (float)Math.floor(hue)) * 6.0f;
float f = h - (float)java.lang.Math.floor(h);
float p = brightness * (1.0f - saturation);
float q = brightness * (1.0f - saturation * f);
float t = brightness * (1.0f - (saturation * (1.0f - f)));
switch ((int) h) {
case 0:
r = (int) (brightness * 255.0f + 0.5f);
g = (int) (t * 255.0f + 0.5f);
b = (int) (p * 255.0f + 0.5f);
break;
case 1:
r = (int) (q * 255.0f + 0.5f);
g = (int) (brightness * 255.0f + 0.5f);
b = (int) (p * 255.0f + 0.5f);
break;
case 2:
r = (int) (p * 255.0f + 0.5f);
g = (int) (brightness * 255.0f + 0.5f);
b = (int) (t * 255.0f + 0.5f);
break;
case 3:
r = (int) (p * 255.0f + 0.5f);
g = (int) (q * 255.0f + 0.5f);
b = (int) (brightness * 255.0f + 0.5f);
break;
case 4:
r = (int) (t * 255.0f + 0.5f);
g = (int) (p * 255.0f + 0.5f);
b = (int) (brightness * 255.0f + 0.5f);
break;
case 5:
r = (int) (brightness * 255.0f + 0.5f);
g = (int) (p * 255.0f + 0.5f);
b = (int) (q * 255.0f + 0.5f);
break;
}
}
return 0xff000000 | (r << 16) | (g << 8) | (b << 0);
}
/** {@collect.stats}
* Converts the components of a color, as specified by the default RGB
* model, to an equivalent set of values for hue, saturation, and
* brightness that are the three components of the HSB model.
* <p>
* If the <code>hsbvals</code> argument is <code>null</code>, then a
* new array is allocated to return the result. Otherwise, the method
* returns the array <code>hsbvals</code>, with the values put into
* that array.
* @param r the red component of the color
* @param g the green component of the color
* @param b the blue component of the color
* @param hsbvals the array used to return the
* three HSB values, or <code>null</code>
* @return an array of three elements containing the hue, saturation,
* and brightness (in that order), of the color with
* the indicated red, green, and blue components.
* @see java.awt.Color#getRGB()
* @see java.awt.Color#Color(int)
* @see java.awt.image.ColorModel#getRGBdefault()
* @since JDK1.0
*/
public static float[] RGBtoHSB(int r, int g, int b, float[] hsbvals) {
float hue, saturation, brightness;
if (hsbvals == null) {
hsbvals = new float[3];
}
int cmax = (r > g) ? r : g;
if (b > cmax) cmax = b;
int cmin = (r < g) ? r : g;
if (b < cmin) cmin = b;
brightness = ((float) cmax) / 255.0f;
if (cmax != 0)
saturation = ((float) (cmax - cmin)) / ((float) cmax);
else
saturation = 0;
if (saturation == 0)
hue = 0;
else {
float redc = ((float) (cmax - r)) / ((float) (cmax - cmin));
float greenc = ((float) (cmax - g)) / ((float) (cmax - cmin));
float bluec = ((float) (cmax - b)) / ((float) (cmax - cmin));
if (r == cmax)
hue = bluec - greenc;
else if (g == cmax)
hue = 2.0f + redc - bluec;
else
hue = 4.0f + greenc - redc;
hue = hue / 6.0f;
if (hue < 0)
hue = hue + 1.0f;
}
hsbvals[0] = hue;
hsbvals[1] = saturation;
hsbvals[2] = brightness;
return hsbvals;
}
/** {@collect.stats}
* Creates a <code>Color</code> object based on the specified values
* for the HSB color model.
* <p>
* The <code>s</code> and <code>b</code> components should be
* floating-point values between zero and one
* (numbers in the range 0.0-1.0). The <code>h</code> component
* can be any floating-point number. The floor of this number is
* subtracted from it to create a fraction between 0 and 1. This
* fractional number is then multiplied by 360 to produce the hue
* angle in the HSB color model.
* @param h the hue component
* @param s the saturation of the color
* @param b the brightness of the color
* @return a <code>Color</code> object with the specified hue,
* saturation, and brightness.
* @since JDK1.0
*/
public static Color getHSBColor(float h, float s, float b) {
return new Color(HSBtoRGB(h, s, b));
}
/** {@collect.stats}
* Returns a <code>float</code> array containing the color and alpha
* components of the <code>Color</code>, as represented in the default
* sRGB color space.
* If <code>compArray</code> is <code>null</code>, an array of length
* 4 is created for the return value. Otherwise,
* <code>compArray</code> must have length 4 or greater,
* and it is filled in with the components and returned.
* @param compArray an array that this method fills with
* color and alpha components and returns
* @return the RGBA components in a <code>float</code> array.
*/
public float[] getRGBComponents(float[] compArray) {
float[] f;
if (compArray == null) {
f = new float[4];
} else {
f = compArray;
}
if (frgbvalue == null) {
f[0] = ((float)getRed())/255f;
f[1] = ((float)getGreen())/255f;
f[2] = ((float)getBlue())/255f;
f[3] = ((float)getAlpha())/255f;
} else {
f[0] = frgbvalue[0];
f[1] = frgbvalue[1];
f[2] = frgbvalue[2];
f[3] = falpha;
}
return f;
}
/** {@collect.stats}
* Returns a <code>float</code> array containing only the color
* components of the <code>Color</code>, in the default sRGB color
* space. If <code>compArray</code> is <code>null</code>, an array of
* length 3 is created for the return value. Otherwise,
* <code>compArray</code> must have length 3 or greater, and it is
* filled in with the components and returned.
* @param compArray an array that this method fills with color
* components and returns
* @return the RGB components in a <code>float</code> array.
*/
public float[] getRGBColorComponents(float[] compArray) {
float[] f;
if (compArray == null) {
f = new float[3];
} else {
f = compArray;
}
if (frgbvalue == null) {
f[0] = ((float)getRed())/255f;
f[1] = ((float)getGreen())/255f;
f[2] = ((float)getBlue())/255f;
} else {
f[0] = frgbvalue[0];
f[1] = frgbvalue[1];
f[2] = frgbvalue[2];
}
return f;
}
/** {@collect.stats}
* Returns a <code>float</code> array containing the color and alpha
* components of the <code>Color</code>, in the
* <code>ColorSpace</code> of the <code>Color</code>.
* If <code>compArray</code> is <code>null</code>, an array with
* length equal to the number of components in the associated
* <code>ColorSpace</code> plus one is created for
* the return value. Otherwise, <code>compArray</code> must have at
* least this length and it is filled in with the components and
* returned.
* @param compArray an array that this method fills with the color and
* alpha components of this <code>Color</code> in its
* <code>ColorSpace</code> and returns
* @return the color and alpha components in a <code>float</code>
* array.
*/
public float[] getComponents(float[] compArray) {
if (fvalue == null)
return getRGBComponents(compArray);
float[] f;
int n = fvalue.length;
if (compArray == null) {
f = new float[n + 1];
} else {
f = compArray;
}
for (int i = 0; i < n; i++) {
f[i] = fvalue[i];
}
f[n] = falpha;
return f;
}
/** {@collect.stats}
* Returns a <code>float</code> array containing only the color
* components of the <code>Color</code>, in the
* <code>ColorSpace</code> of the <code>Color</code>.
* If <code>compArray</code> is <code>null</code>, an array with
* length equal to the number of components in the associated
* <code>ColorSpace</code> is created for
* the return value. Otherwise, <code>compArray</code> must have at
* least this length and it is filled in with the components and
* returned.
* @param compArray an array that this method fills with the color
* components of this <code>Color</code> in its
* <code>ColorSpace</code> and returns
* @return the color components in a <code>float</code> array.
*/
public float[] getColorComponents(float[] compArray) {
if (fvalue == null)
return getRGBColorComponents(compArray);
float[] f;
int n = fvalue.length;
if (compArray == null) {
f = new float[n];
} else {
f = compArray;
}
for (int i = 0; i < n; i++) {
f[i] = fvalue[i];
}
return f;
}
/** {@collect.stats}
* Returns a <code>float</code> array containing the color and alpha
* components of the <code>Color</code>, in the
* <code>ColorSpace</code> specified by the <code>cspace</code>
* parameter. If <code>compArray</code> is <code>null</code>, an
* array with length equal to the number of components in
* <code>cspace</code> plus one is created for the return value.
* Otherwise, <code>compArray</code> must have at least this
* length, and it is filled in with the components and returned.
* @param cspace a specified <code>ColorSpace</code>
* @param compArray an array that this method fills with the
* color and alpha components of this <code>Color</code> in
* the specified <code>ColorSpace</code> and returns
* @return the color and alpha components in a <code>float</code>
* array.
*/
public float[] getComponents(ColorSpace cspace, float[] compArray) {
if (cs == null) {
cs = ColorSpace.getInstance(ColorSpace.CS_sRGB);
}
float f[];
if (fvalue == null) {
f = new float[3];
f[0] = ((float)getRed())/255f;
f[1] = ((float)getGreen())/255f;
f[2] = ((float)getBlue())/255f;
} else {
f = fvalue;
}
float tmp[] = cs.toCIEXYZ(f);
float tmpout[] = cspace.fromCIEXYZ(tmp);
if (compArray == null) {
compArray = new float[tmpout.length + 1];
}
for (int i = 0 ; i < tmpout.length ; i++) {
compArray[i] = tmpout[i];
}
if (fvalue == null) {
compArray[tmpout.length] = ((float)getAlpha())/255f;
} else {
compArray[tmpout.length] = falpha;
}
return compArray;
}
/** {@collect.stats}
* Returns a <code>float</code> array containing only the color
* components of the <code>Color</code> in the
* <code>ColorSpace</code> specified by the <code>cspace</code>
* parameter. If <code>compArray</code> is <code>null</code>, an array
* with length equal to the number of components in
* <code>cspace</code> is created for the return value. Otherwise,
* <code>compArray</code> must have at least this length, and it is
* filled in with the components and returned.
* @param cspace a specified <code>ColorSpace</code>
* @param compArray an array that this method fills with the color
* components of this <code>Color</code> in the specified
* <code>ColorSpace</code>
* @return the color components in a <code>float</code> array.
*/
public float[] getColorComponents(ColorSpace cspace, float[] compArray) {
if (cs == null) {
cs = ColorSpace.getInstance(ColorSpace.CS_sRGB);
}
float f[];
if (fvalue == null) {
f = new float[3];
f[0] = ((float)getRed())/255f;
f[1] = ((float)getGreen())/255f;
f[2] = ((float)getBlue())/255f;
} else {
f = fvalue;
}
float tmp[] = cs.toCIEXYZ(f);
float tmpout[] = cspace.fromCIEXYZ(tmp);
if (compArray == null) {
return tmpout;
}
for (int i = 0 ; i < tmpout.length ; i++) {
compArray[i] = tmpout[i];
}
return compArray;
}
/** {@collect.stats}
* Returns the <code>ColorSpace</code> of this <code>Color</code>.
* @return this <code>Color</code> object's <code>ColorSpace</code>.
*/
public ColorSpace getColorSpace() {
if (cs == null) {
cs = ColorSpace.getInstance(ColorSpace.CS_sRGB);
}
return cs;
}
/** {@collect.stats}
* Creates and returns a {@link PaintContext} used to
* generate a solid color field pattern.
* See the {@link Paint#createContext specification} of the
* method in the {@link Paint} interface for information
* on null parameter handling.
*
* @param cm the preferred {@link ColorModel} which represents the most convenient
* format for the caller to receive the pixel data, or {@code null}
* if there is no preference.
* @param r the device space bounding box
* of the graphics primitive being rendered.
* @param r2d the user space bounding box
* of the graphics primitive being rendered.
* @param xform the {@link AffineTransform} from user
* space into device space.
* @param hints the set of hints that the context object can use to
* choose between rendering alternatives.
* @return the {@code PaintContext} for
* generating color patterns.
* @see Paint
* @see PaintContext
* @see ColorModel
* @see Rectangle
* @see Rectangle2D
* @see AffineTransform
* @see RenderingHints
*/
public synchronized PaintContext createContext(ColorModel cm, Rectangle r,
Rectangle2D r2d,
AffineTransform xform,
RenderingHints hints) {
if (context == null ||
context.getRGB() != getRGB())
{
context = new ColorPaintContext(getRGB(), cm);
}
return context;
}
/** {@collect.stats}
* Returns the transparency mode for this <code>Color</code>. This is
* required to implement the <code>Paint</code> interface.
* @return this <code>Color</code> object's transparency mode.
* @see Paint
* @see Transparency
* @see #createContext
*/
public int getTransparency() {
int alpha = getAlpha();
if (alpha == 0xff) {
return Transparency.OPAQUE;
}
else if (alpha == 0) {
return Transparency.BITMASK;
}
else {
return Transparency.TRANSLUCENT;
}
}
}
|
Java
|
/*
* Copyright (c) 1999, 2000, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code 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
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package java.awt;
import java.awt.peer.LightweightPeer;
import sun.awt.SunGraphicsCallback;
abstract class GraphicsCallback extends SunGraphicsCallback {
static final class PaintCallback extends GraphicsCallback {
private static PaintCallback instance = new PaintCallback();
private PaintCallback() {}
public void run(Component comp, Graphics cg) {
comp.paint(cg);
}
static PaintCallback getInstance() {
return instance;
}
}
static final class PrintCallback extends GraphicsCallback {
private static PrintCallback instance = new PrintCallback();
private PrintCallback() {}
public void run(Component comp, Graphics cg) {
comp.print(cg);
}
static PrintCallback getInstance() {
return instance;
}
}
static final class PaintAllCallback extends GraphicsCallback {
private static PaintAllCallback instance = new PaintAllCallback();
private PaintAllCallback() {}
public void run(Component comp, Graphics cg) {
comp.paintAll(cg);
}
static PaintAllCallback getInstance() {
return instance;
}
}
static final class PrintAllCallback extends GraphicsCallback {
private static PrintAllCallback instance = new PrintAllCallback();
private PrintAllCallback() {}
public void run(Component comp, Graphics cg) {
comp.printAll(cg);
}
static PrintAllCallback getInstance() {
return instance;
}
}
static final class PeerPaintCallback extends GraphicsCallback {
private static PeerPaintCallback instance = new PeerPaintCallback();
private PeerPaintCallback() {}
public void run(Component comp, Graphics cg) {
comp.validate();
if (comp.peer instanceof LightweightPeer) {
comp.lightweightPaint(cg);
} else {
comp.peer.paint(cg);
}
}
static PeerPaintCallback getInstance() {
return instance;
}
}
static final class PeerPrintCallback extends GraphicsCallback {
private static PeerPrintCallback instance = new PeerPrintCallback();
private PeerPrintCallback() {}
public void run(Component comp, Graphics cg) {
comp.validate();
if (comp.peer instanceof LightweightPeer) {
comp.lightweightPrint(cg);
} else {
comp.peer.print(cg);
}
}
static PeerPrintCallback getInstance() {
return instance;
}
}
static final class PaintHeavyweightComponentsCallback
extends GraphicsCallback
{
private static PaintHeavyweightComponentsCallback instance =
new PaintHeavyweightComponentsCallback();
private PaintHeavyweightComponentsCallback() {}
public void run(Component comp, Graphics cg) {
if (comp.peer instanceof LightweightPeer) {
comp.paintHeavyweightComponents(cg);
} else {
comp.paintAll(cg);
}
}
static PaintHeavyweightComponentsCallback getInstance() {
return instance;
}
}
static final class PrintHeavyweightComponentsCallback
extends GraphicsCallback
{
private static PrintHeavyweightComponentsCallback instance =
new PrintHeavyweightComponentsCallback();
private PrintHeavyweightComponentsCallback() {}
public void run(Component comp, Graphics cg) {
if (comp.peer instanceof LightweightPeer) {
comp.printHeavyweightComponents(cg);
} else {
comp.printAll(cg);
}
}
static PrintHeavyweightComponentsCallback getInstance() {
return instance;
}
}
}
|
Java
|
/*
* Copyright (c) 1997, 2006, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code 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
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package java.awt;
import java.awt.image.ColorModel;
import sun.awt.AppContext;
/** {@collect.stats}
* The <code>GraphicsDevice</code> class describes the graphics devices
* that might be available in a particular graphics environment. These
* include screen and printer devices. Note that there can be many screens
* and many printers in an instance of {@link GraphicsEnvironment}. Each
* graphics device has one or more {@link GraphicsConfiguration} objects
* associated with it. These objects specify the different configurations
* in which the <code>GraphicsDevice</code> can be used.
* <p>
* In a multi-screen environment, the <code>GraphicsConfiguration</code>
* objects can be used to render components on multiple screens. The
* following code sample demonstrates how to create a <code>JFrame</code>
* object for each <code>GraphicsConfiguration</code> on each screen
* device in the <code>GraphicsEnvironment</code>:
* <pre>
* GraphicsEnvironment ge = GraphicsEnvironment.
* getLocalGraphicsEnvironment();
* GraphicsDevice[] gs = ge.getScreenDevices();
* for (int j = 0; j < gs.length; j++) {
* GraphicsDevice gd = gs[j];
* GraphicsConfiguration[] gc =
* gd.getConfigurations();
* for (int i=0; i < gc.length; i++) {
* JFrame f = new
* JFrame(gs[j].getDefaultConfiguration());
* Canvas c = new Canvas(gc[i]);
* Rectangle gcBounds = gc[i].getBounds();
* int xoffs = gcBounds.x;
* int yoffs = gcBounds.y;
* f.getContentPane().add(c);
* f.setLocation((i*50)+xoffs, (i*60)+yoffs);
* f.show();
* }
* }
* </pre>
* <p>
* For more information on full-screen exclusive mode API, see the
* <a href="http://java.sun.com/docs/books/tutorial/extra/fullscreen/index.html">
* Full-Screen Exclusive Mode API Tutorial</a>.
*
* @see GraphicsEnvironment
* @see GraphicsConfiguration
*/
public abstract class GraphicsDevice {
private Window fullScreenWindow;
private AppContext fullScreenAppContext; // tracks which AppContext
// created the FS window
// this lock is used for making synchronous changes to the AppContext's
// current full screen window
private final Object fsAppContextLock = new Object();
private Rectangle windowedModeBounds;
/** {@collect.stats}
* This is an abstract class that cannot be instantiated directly.
* Instances must be obtained from a suitable factory or query method.
* @see GraphicsEnvironment#getScreenDevices
* @see GraphicsEnvironment#getDefaultScreenDevice
* @see GraphicsConfiguration#getDevice
*/
protected GraphicsDevice() {
}
/** {@collect.stats}
* Device is a raster screen.
*/
public final static int TYPE_RASTER_SCREEN = 0;
/** {@collect.stats}
* Device is a printer.
*/
public final static int TYPE_PRINTER = 1;
/** {@collect.stats}
* Device is an image buffer. This buffer can reside in device
* or system memory but it is not physically viewable by the user.
*/
public final static int TYPE_IMAGE_BUFFER = 2;
/** {@collect.stats}
* Returns the type of this <code>GraphicsDevice</code>.
* @return the type of this <code>GraphicsDevice</code>, which can
* either be TYPE_RASTER_SCREEN, TYPE_PRINTER or TYPE_IMAGE_BUFFER.
* @see #TYPE_RASTER_SCREEN
* @see #TYPE_PRINTER
* @see #TYPE_IMAGE_BUFFER
*/
public abstract int getType();
/** {@collect.stats}
* Returns the identification string associated with this
* <code>GraphicsDevice</code>.
* <p>
* A particular program might use more than one
* <code>GraphicsDevice</code> in a <code>GraphicsEnvironment</code>.
* This method returns a <code>String</code> identifying a
* particular <code>GraphicsDevice</code> in the local
* <code>GraphicsEnvironment</code>. Although there is
* no public method to set this <code>String</code>, a programmer can
* use the <code>String</code> for debugging purposes. Vendors of
* the Java<sup><font size=-2>TM</font></sup> Runtime Environment can
* format the return value of the <code>String</code>. To determine
* how to interpret the value of the <code>String</code>, contact the
* vendor of your Java Runtime. To find out who the vendor is, from
* your program, call the
* {@link System#getProperty(String) getProperty} method of the
* System class with "java.vendor".
* @return a <code>String</code> that is the identification
* of this <code>GraphicsDevice</code>.
*/
public abstract String getIDstring();
/** {@collect.stats}
* Returns all of the <code>GraphicsConfiguration</code>
* objects associated with this <code>GraphicsDevice</code>.
* @return an array of <code>GraphicsConfiguration</code>
* objects that are associated with this
* <code>GraphicsDevice</code>.
*/
public abstract GraphicsConfiguration[] getConfigurations();
/** {@collect.stats}
* Returns the default <code>GraphicsConfiguration</code>
* associated with this <code>GraphicsDevice</code>.
* @return the default <code>GraphicsConfiguration</code>
* of this <code>GraphicsDevice</code>.
*/
public abstract GraphicsConfiguration getDefaultConfiguration();
/** {@collect.stats}
* Returns the "best" configuration possible that passes the
* criteria defined in the {@link GraphicsConfigTemplate}.
* @param gct the <code>GraphicsConfigTemplate</code> object
* used to obtain a valid <code>GraphicsConfiguration</code>
* @return a <code>GraphicsConfiguration</code> that passes
* the criteria defined in the specified
* <code>GraphicsConfigTemplate</code>.
* @see GraphicsConfigTemplate
*/
public GraphicsConfiguration
getBestConfiguration(GraphicsConfigTemplate gct) {
GraphicsConfiguration[] configs = getConfigurations();
return gct.getBestConfiguration(configs);
}
/** {@collect.stats}
* Returns <code>true</code> if this <code>GraphicsDevice</code>
* supports full-screen exclusive mode.
* If a SecurityManager is installed, its
* <code>checkPermission</code> method will be called
* with <code>AWTPermission("fullScreenExclusive")</code>.
* <code>isFullScreenSupported</code> returns true only if
* that permission is granted.
* @return whether full-screen exclusive mode is available for
* this graphics device
* @see java.awt.AWTPermission
* @since 1.4
*/
public boolean isFullScreenSupported() {
return false;
}
/** {@collect.stats}
* Enter full-screen mode, or return to windowed mode. The entered
* full-screen mode may be either exclusive or simulated. Exclusive
* mode is only available if <code>isFullScreenSupported</code>
* returns <code>true</code>.
* <p>
* Exclusive mode implies:
* <ul>
* <li>Windows cannot overlap the full-screen window. All other application
* windows will always appear beneath the full-screen window in the Z-order.
* <li>There can be only one full-screen window on a device at any time,
* so calling this method while there is an existing full-screen Window
* will cause the existing full-screen window to
* return to windowed mode.
* <li>Input method windows are disabled. It is advisable to call
* <code>Component.enableInputMethods(false)</code> to make a component
* a non-client of the input method framework.
* </ul>
* <p>
* Simulated full-screen mode resizes
* the window to the size of the screen and positions it at (0,0).
* <p>
* When entering full-screen mode, if the window to be used as the
* full-screen window is not visible, this method will make it visible.
* It will remain visible when returning to windowed mode.
* <p>
* When returning to windowed mode from an exclusive full-screen window, any
* display changes made by calling <code>setDisplayMode</code> are
* automatically restored to their original state.
*
* @param w a window to use as the full-screen window; <code>null</code>
* if returning to windowed mode. Some platforms expect the
* fullscreen window to be a top-level component (i.e., a Frame);
* therefore it is preferable to use a Frame here rather than a
* Window.
* @see #isFullScreenSupported
* @see #getFullScreenWindow
* @see #setDisplayMode
* @see Component#enableInputMethods
* @see Component#setVisible
* @since 1.4
*/
public void setFullScreenWindow(Window w) {
if (fullScreenWindow != null && windowedModeBounds != null) {
fullScreenWindow.setBounds(windowedModeBounds);
}
// Set the full screen window
synchronized (fsAppContextLock) {
// Associate fullscreen window with current AppContext
if (w == null) {
fullScreenAppContext = null;
} else {
fullScreenAppContext = AppContext.getAppContext();
}
fullScreenWindow = w;
}
if (fullScreenWindow != null) {
windowedModeBounds = fullScreenWindow.getBounds();
// Note that we use the graphics configuration of the device,
// not the window's, because we're setting the fs window for
// this device.
Rectangle screenBounds = getDefaultConfiguration().getBounds();
fullScreenWindow.setBounds(screenBounds.x, screenBounds.y,
screenBounds.width, screenBounds.height);
fullScreenWindow.setVisible(true);
fullScreenWindow.toFront();
}
}
/** {@collect.stats}
* Returns the <code>Window</code> object representing the
* full-screen window if the device is in full-screen mode.
*
* @return the full-screen window, or <code>null</code> if the device is
* not in full-screen mode.
* @see #setFullScreenWindow(Window)
* @since 1.4
*/
public Window getFullScreenWindow() {
Window returnWindow = null;
synchronized (fsAppContextLock) {
// Only return a handle to the current fs window if we are in the
// same AppContext that set the fs window
if (fullScreenAppContext == AppContext.getAppContext()) {
returnWindow = fullScreenWindow;
}
}
return returnWindow;
}
/** {@collect.stats}
* Returns <code>true</code> if this <code>GraphicsDevice</code>
* supports low-level display changes.
* On some platforms low-level display changes may only be allowed in
* full-screen exclusive mode (i.e., if {@link #isFullScreenSupported()}
* returns {@code true} and the application has already entered
* full-screen mode using {@link #setFullScreenWindow}).
* @return whether low-level display changes are supported for this
* graphics device.
* @see #isFullScreenSupported
* @see #setDisplayMode
* @see #setFullScreenWindow
* @since 1.4
*/
public boolean isDisplayChangeSupported() {
return false;
}
/** {@collect.stats}
* Sets the display mode of this graphics device. This is only allowed
* if {@link #isDisplayChangeSupported()} returns {@code true} and may
* require first entering full-screen exclusive mode using
* {@link #setFullScreenWindow} providing that full-screen exclusive mode is
* supported (i.e., {@link #isFullScreenSupported()} returns
* {@code true}).
* <p>
*
* The display mode must be one of the display modes returned by
* {@link #getDisplayModes()}, with one exception: passing a display mode
* with {@link DisplayMode#REFRESH_RATE_UNKNOWN} refresh rate will result in
* selecting a display mode from the list of available display modes with
* matching width, height and bit depth.
* However, passing a display mode with {@link DisplayMode#BIT_DEPTH_MULTI}
* for bit depth is only allowed if such mode exists in the list returned by
* {@link #getDisplayModes()}.
* <p>
* Example code:
* <pre><code>
* Frame frame;
* DisplayMode newDisplayMode;
* GraphicsDevice gd;
* // create a Frame, select desired DisplayMode from the list of modes
* // returned by gd.getDisplayModes() ...
*
* if (gd.isFullScreenSupported()) {
* gd.setFullScreenWindow(frame);
* } else {
* // proceed in non-full-screen mode
* frame.setSize(...);
* frame.setLocation(...);
* frame.setVisible(true);
* }
*
* if (gd.isDisplayChangeSupported()) {
* gd.setDisplayMode(newDisplayMode);
* }
* </code></pre>
*
* @param dm The new display mode of this graphics device.
* @exception IllegalArgumentException if the <code>DisplayMode</code>
* supplied is <code>null</code>, or is not available in the array returned
* by <code>getDisplayModes</code>
* @exception UnsupportedOperationException if
* <code>isDisplayChangeSupported</code> returns <code>false</code>
* @see #getDisplayMode
* @see #getDisplayModes
* @see #isDisplayChangeSupported
* @since 1.4
*/
public void setDisplayMode(DisplayMode dm) {
throw new UnsupportedOperationException("Cannot change display mode");
}
/** {@collect.stats}
* Returns the current display mode of this
* <code>GraphicsDevice</code>.
* The returned display mode is allowed to have a refresh rate
* {@link DisplayMode#REFRESH_RATE_UNKNOWN} if it is indeterminate.
* Likewise, the returned display mode is allowed to have a bit depth
* {@link DisplayMode#BIT_DEPTH_MULTI} if it is indeterminate or if multiple
* bit depths are supported.
* @return the current display mode of this graphics device.
* @see #setDisplayMode(DisplayMode)
* @since 1.4
*/
public DisplayMode getDisplayMode() {
GraphicsConfiguration gc = getDefaultConfiguration();
Rectangle r = gc.getBounds();
ColorModel cm = gc.getColorModel();
return new DisplayMode(r.width, r.height, cm.getPixelSize(), 0);
}
/** {@collect.stats}
* Returns all display modes available for this
* <code>GraphicsDevice</code>.
* The returned display modes are allowed to have a refresh rate
* {@link DisplayMode#REFRESH_RATE_UNKNOWN} if it is indeterminate.
* Likewise, the returned display modes are allowed to have a bit depth
* {@link DisplayMode#BIT_DEPTH_MULTI} if it is indeterminate or if multiple
* bit depths are supported.
* @return all of the display modes available for this graphics device.
* @since 1.4
*/
public DisplayMode[] getDisplayModes() {
return new DisplayMode[] { getDisplayMode() };
}
/** {@collect.stats}
* This method returns the number of bytes available in
* accelerated memory on this device.
* Some images are created or cached
* in accelerated memory on a first-come,
* first-served basis. On some operating systems,
* this memory is a finite resource. Calling this method
* and scheduling the creation and flushing of images carefully may
* enable applications to make the most efficient use of
* that finite resource.
* <br>
* Note that the number returned is a snapshot of how much
* memory is available; some images may still have problems
* being allocated into that memory. For example, depending
* on operating system, driver, memory configuration, and
* thread situations, the full extent of the size reported
* may not be available for a given image. There are further
* inquiry methods on the {@link ImageCapabilities} object
* associated with a VolatileImage that can be used to determine
* whether a particular VolatileImage has been created in accelerated
* memory.
* @return number of bytes available in accelerated memory.
* A negative return value indicates that the amount of accelerated memory
* on this GraphicsDevice is indeterminate.
* @see java.awt.image.VolatileImage#flush
* @see ImageCapabilities#isAccelerated
* @since 1.4
*/
public int getAvailableAcceleratedMemory() {
return -1;
}
}
|
Java
|
/*
* Copyright (c) 1996, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code 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
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package java.awt;
/** {@collect.stats}
* An abstract class which initiates and executes a print job.
* It provides access to a print graphics object which renders
* to an appropriate print device.
*
* @see Toolkit#getPrintJob
*
* @author Amy Fowler
*/
public abstract class PrintJob {
/** {@collect.stats}
* Gets a Graphics object that will draw to the next page.
* The page is sent to the printer when the graphics
* object is disposed. This graphics object will also implement
* the PrintGraphics interface.
* @see PrintGraphics
*/
public abstract Graphics getGraphics();
/** {@collect.stats}
* Returns the dimensions of the page in pixels.
* The resolution of the page is chosen so that it
* is similar to the screen resolution.
*/
public abstract Dimension getPageDimension();
/** {@collect.stats}
* Returns the resolution of the page in pixels per inch.
* Note that this doesn't have to correspond to the physical
* resolution of the printer.
*/
public abstract int getPageResolution();
/** {@collect.stats}
* Returns true if the last page will be printed first.
*/
public abstract boolean lastPageFirst();
/** {@collect.stats}
* Ends the print job and does any necessary cleanup.
*/
public abstract void end();
/** {@collect.stats}
* Ends this print job once it is no longer referenced.
* @see #end
*/
public void finalize() {
end();
}
}
|
Java
|
/*
* Copyright (c) 1997, 2006, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code 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
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package java.awt;
import java.awt.image.ColorModel;
import sun.java2d.SunCompositeContext;
/** {@collect.stats}
* The <code>AlphaComposite</code> class implements basic alpha
* compositing rules for combining source and destination colors
* to achieve blending and transparency effects with graphics and
* images.
* The specific rules implemented by this class are the basic set
* of 12 rules described in
* T. Porter and T. Duff, "Compositing Digital Images", SIGGRAPH 84,
* 253-259.
* The rest of this documentation assumes some familiarity with the
* definitions and concepts outlined in that paper.
*
* <p>
* This class extends the standard equations defined by Porter and
* Duff to include one additional factor.
* An instance of the <code>AlphaComposite</code> class can contain
* an alpha value that is used to modify the opacity or coverage of
* every source pixel before it is used in the blending equations.
*
* <p>
* It is important to note that the equations defined by the Porter
* and Duff paper are all defined to operate on color components
* that are premultiplied by their corresponding alpha components.
* Since the <code>ColorModel</code> and <code>Raster</code> classes
* allow the storage of pixel data in either premultiplied or
* non-premultiplied form, all input data must be normalized into
* premultiplied form before applying the equations and all results
* might need to be adjusted back to the form required by the destination
* before the pixel values are stored.
*
* <p>
* Also note that this class defines only the equations
* for combining color and alpha values in a purely mathematical
* sense. The accurate application of its equations depends
* on the way the data is retrieved from its sources and stored
* in its destinations.
* See <a href="#caveats">Implementation Caveats</a>
* for further information.
*
* <p>
* The following factors are used in the description of the blending
* equation in the Porter and Duff paper:
*
* <blockquote>
* <table summary="layout">
* <tr><th align=left>Factor <th align=left>Definition
* <tr><td><em>A<sub>s</sub></em><td>the alpha component of the source pixel
* <tr><td><em>C<sub>s</sub></em><td>a color component of the source pixel in premultiplied form
* <tr><td><em>A<sub>d</sub></em><td>the alpha component of the destination pixel
* <tr><td><em>C<sub>d</sub></em><td>a color component of the destination pixel in premultiplied form
* <tr><td><em>F<sub>s</sub></em><td>the fraction of the source pixel that contributes to the output
* <tr><td><em>F<sub>d</sub></em><td>the fraction of the destination pixel that contributes
* to the output
* <tr><td><em>A<sub>r</sub></em><td>the alpha component of the result
* <tr><td><em>C<sub>r</sub></em><td>a color component of the result in premultiplied form
* </table>
* </blockquote>
*
* <p>
* Using these factors, Porter and Duff define 12 ways of choosing
* the blending factors <em>F<sub>s</sub></em> and <em>F<sub>d</sub></em> to
* produce each of 12 desirable visual effects.
* The equations for determining <em>F<sub>s</sub></em> and <em>F<sub>d</sub></em>
* are given in the descriptions of the 12 static fields
* that specify visual effects.
* For example,
* the description for
* <a href="#SRC_OVER"><code>SRC_OVER</code></a>
* specifies that <em>F<sub>s</sub></em> = 1 and <em>F<sub>d</sub></em> = (1-<em>A<sub>s</sub></em>).
* Once a set of equations for determining the blending factors is
* known they can then be applied to each pixel to produce a result
* using the following set of equations:
*
* <pre>
* <em>F<sub>s</sub></em> = <em>f</em>(<em>A<sub>d</sub></em>)
* <em>F<sub>d</sub></em> = <em>f</em>(<em>A<sub>s</sub></em>)
* <em>A<sub>r</sub></em> = <em>A<sub>s</sub></em>*<em>F<sub>s</sub></em> + <em>A<sub>d</sub></em>*<em>F<sub>d</sub></em>
* <em>C<sub>r</sub></em> = <em>C<sub>s</sub></em>*<em>F<sub>s</sub></em> + <em>C<sub>d</sub></em>*<em>F<sub>d</sub></em></pre>
*
* <p>
* The following factors will be used to discuss our extensions to
* the blending equation in the Porter and Duff paper:
*
* <blockquote>
* <table summary="layout">
* <tr><th align=left>Factor <th align=left>Definition
* <tr><td><em>C<sub>sr</sub></em> <td>one of the raw color components of the source pixel
* <tr><td><em>C<sub>dr</sub></em> <td>one of the raw color components of the destination pixel
* <tr><td><em>A<sub>ac</sub></em> <td>the "extra" alpha component from the AlphaComposite instance
* <tr><td><em>A<sub>sr</sub></em> <td>the raw alpha component of the source pixel
* <tr><td><em>A<sub>dr</sub></em><td>the raw alpha component of the destination pixel
* <tr><td><em>A<sub>df</sub></em> <td>the final alpha component stored in the destination
* <tr><td><em>C<sub>df</sub></em> <td>the final raw color component stored in the destination
* </table>
*</blockquote>
*
* <h3>Preparing Inputs</h3>
*
* <p>
* The <code>AlphaComposite</code> class defines an additional alpha
* value that is applied to the source alpha.
* This value is applied as if an implicit SRC_IN rule were first
* applied to the source pixel against a pixel with the indicated
* alpha by multiplying both the raw source alpha and the raw
* source colors by the alpha in the <code>AlphaComposite</code>.
* This leads to the following equation for producing the alpha
* used in the Porter and Duff blending equation:
*
* <pre>
* <em>A<sub>s</sub></em> = <em>A<sub>sr</sub></em> * <em>A<sub>ac</sub></em> </pre>
*
* All of the raw source color components need to be multiplied
* by the alpha in the <code>AlphaComposite</code> instance.
* Additionally, if the source was not in premultiplied form
* then the color components also need to be multiplied by the
* source alpha.
* Thus, the equation for producing the source color components
* for the Porter and Duff equation depends on whether the source
* pixels are premultiplied or not:
*
* <pre>
* <em>C<sub>s</sub></em> = <em>C<sub>sr</sub></em> * <em>A<sub>sr</sub></em> * <em>A<sub>ac</sub></em> (if source is not premultiplied)
* <em>C<sub>s</sub></em> = <em>C<sub>sr</sub></em> * <em>A<sub>ac</sub></em> (if source is premultiplied) </pre>
*
* No adjustment needs to be made to the destination alpha:
*
* <pre>
* <em>A<sub>d</sub></em> = <em>A<sub>dr</sub></em> </pre>
*
* <p>
* The destination color components need to be adjusted only if
* they are not in premultiplied form:
*
* <pre>
* <em>C<sub>d</sub></em> = <em>C<sub>dr</sub></em> * <em>A<sub>d</sub></em> (if destination is not premultiplied)
* <em>C<sub>d</sub></em> = <em>C<sub>dr</sub></em> (if destination is premultiplied) </pre>
*
* <h3>Applying the Blending Equation</h3>
*
* <p>
* The adjusted <em>A<sub>s</sub></em>, <em>A<sub>d</sub></em>,
* <em>C<sub>s</sub></em>, and <em>C<sub>d</sub></em> are used in the standard
* Porter and Duff equations to calculate the blending factors
* <em>F<sub>s</sub></em> and <em>F<sub>d</sub></em> and then the resulting
* premultiplied components <em>A<sub>r</sub></em> and <em>C<sub>r</sub></em>.
*
* <p>
* <h3>Preparing Results</h3>
*
* <p>
* The results only need to be adjusted if they are to be stored
* back into a destination buffer that holds data that is not
* premultiplied, using the following equations:
*
* <pre>
* <em>A<sub>df</sub></em> = <em>A<sub>r</sub></em>
* <em>C<sub>df</sub></em> = <em>C<sub>r</sub></em> (if dest is premultiplied)
* <em>C<sub>df</sub></em> = <em>C<sub>r</sub></em> / <em>A<sub>r</sub></em> (if dest is not premultiplied) </pre>
*
* Note that since the division is undefined if the resulting alpha
* is zero, the division in that case is omitted to avoid the "divide
* by zero" and the color components are left as
* all zeros.
*
* <p>
* <h3>Performance Considerations</h3>
*
* <p>
* For performance reasons, it is preferrable that
* <code>Raster</code> objects passed to the <code>compose</code>
* method of a {@link CompositeContext} object created by the
* <code>AlphaComposite</code> class have premultiplied data.
* If either the source <code>Raster</code>
* or the destination <code>Raster</code>
* is not premultiplied, however,
* appropriate conversions are performed before and after the compositing
* operation.
*
* <h3><a name="caveats">Implementation Caveats</a></h3>
*
* <ul>
* <li>
* Many sources, such as some of the opaque image types listed
* in the <code>BufferedImage</code> class, do not store alpha values
* for their pixels. Such sources supply an alpha of 1.0 for
* all of their pixels.
*
* <p>
* <li>
* Many destinations also have no place to store the alpha values
* that result from the blending calculations performed by this class.
* Such destinations thus implicitly discard the resulting
* alpha values that this class produces.
* It is recommended that such destinations should treat their stored
* color values as non-premultiplied and divide the resulting color
* values by the resulting alpha value before storing the color
* values and discarding the alpha value.
*
* <p>
* <li>
* The accuracy of the results depends on the manner in which pixels
* are stored in the destination.
* An image format that provides at least 8 bits of storage per color
* and alpha component is at least adequate for use as a destination
* for a sequence of a few to a dozen compositing operations.
* An image format with fewer than 8 bits of storage per component
* is of limited use for just one or two compositing operations
* before the rounding errors dominate the results.
* An image format
* that does not separately store
* color components is not a
* good candidate for any type of translucent blending.
* For example, <code>BufferedImage.TYPE_BYTE_INDEXED</code>
* should not be used as a destination for a blending operation
* because every operation
* can introduce large errors, due to
* the need to choose a pixel from a limited palette to match the
* results of the blending equations.
*
* <p>
* <li>
* Nearly all formats store pixels as discrete integers rather than
* the floating point values used in the reference equations above.
* The implementation can either scale the integer pixel
* values into floating point values in the range 0.0 to 1.0 or
* use slightly modified versions of the equations
* that operate entirely in the integer domain and yet produce
* analogous results to the reference equations.
*
* <p>
* Typically the integer values are related to the floating point
* values in such a way that the integer 0 is equated
* to the floating point value 0.0 and the integer
* 2^<em>n</em>-1 (where <em>n</em> is the number of bits
* in the representation) is equated to 1.0.
* For 8-bit representations, this means that 0x00
* represents 0.0 and 0xff represents
* 1.0.
*
* <p>
* <li>
* The internal implementation can approximate some of the equations
* and it can also eliminate some steps to avoid unnecessary operations.
* For example, consider a discrete integer image with non-premultiplied
* alpha values that uses 8 bits per component for storage.
* The stored values for a
* nearly transparent darkened red might be:
*
* <pre>
* (A, R, G, B) = (0x01, 0xb0, 0x00, 0x00)</pre>
*
* <p>
* If integer math were being used and this value were being
* composited in
* <a href="#SRC"><code>SRC</code></a>
* mode with no extra alpha, then the math would
* indicate that the results were (in integer format):
*
* <pre>
* (A, R, G, B) = (0x01, 0x01, 0x00, 0x00)</pre>
*
* <p>
* Note that the intermediate values, which are always in premultiplied
* form, would only allow the integer red component to be either 0x00
* or 0x01. When we try to store this result back into a destination
* that is not premultiplied, dividing out the alpha will give us
* very few choices for the non-premultiplied red value.
* In this case an implementation that performs the math in integer
* space without shortcuts is likely to end up with the final pixel
* values of:
*
* <pre>
* (A, R, G, B) = (0x01, 0xff, 0x00, 0x00)</pre>
*
* <p>
* (Note that 0x01 divided by 0x01 gives you 1.0, which is equivalent
* to the value 0xff in an 8-bit storage format.)
*
* <p>
* Alternately, an implementation that uses floating point math
* might produce more accurate results and end up returning to the
* original pixel value with little, if any, roundoff error.
* Or, an implementation using integer math might decide that since
* the equations boil down to a virtual NOP on the color values
* if performed in a floating point space, it can transfer the
* pixel untouched to the destination and avoid all the math entirely.
*
* <p>
* These implementations all attempt to honor the
* same equations, but use different tradeoffs of integer and
* floating point math and reduced or full equations.
* To account for such differences, it is probably best to
* expect only that the premultiplied form of the results to
* match between implementations and image formats. In this
* case both answers, expressed in premultiplied form would
* equate to:
*
* <pre>
* (A, R, G, B) = (0x01, 0x01, 0x00, 0x00)</pre>
*
* <p>
* and thus they would all match.
*
* <p>
* <li>
* Because of the technique of simplifying the equations for
* calculation efficiency, some implementations might perform
* differently when encountering result alpha values of 0.0
* on a non-premultiplied destination.
* Note that the simplification of removing the divide by alpha
* in the case of the SRC rule is technically not valid if the
* denominator (alpha) is 0.
* But, since the results should only be expected to be accurate
* when viewed in premultiplied form, a resulting alpha of 0
* essentially renders the resulting color components irrelevant
* and so exact behavior in this case should not be expected.
* </ul>
* @see Composite
* @see CompositeContext
*/
public final class AlphaComposite implements Composite {
/** {@collect.stats}
* Both the color and the alpha of the destination are cleared
* (Porter-Duff Clear rule).
* Neither the source nor the destination is used as input.
*<p>
* <em>F<sub>s</sub></em> = 0 and <em>F<sub>d</sub></em> = 0, thus:
*<pre>
* <em>A<sub>r</sub></em> = 0
* <em>C<sub>r</sub></em> = 0
*</pre>
*/
public static final int CLEAR = 1;
/** {@collect.stats}
* The source is copied to the destination
* (Porter-Duff Source rule).
* The destination is not used as input.
*<p>
* <em>F<sub>s</sub></em> = 1 and <em>F<sub>d</sub></em> = 0, thus:
*<pre>
* <em>A<sub>r</sub></em> = <em>A<sub>s</sub></em>
* <em>C<sub>r</sub></em> = <em>C<sub>s</sub></em>
*</pre>
*/
public static final int SRC = 2;
/** {@collect.stats}
* The destination is left untouched
* (Porter-Duff Destination rule).
*<p>
* <em>F<sub>s</sub></em> = 0 and <em>F<sub>d</sub></em> = 1, thus:
*<pre>
* <em>A<sub>r</sub></em> = <em>A<sub>d</sub></em>
* <em>C<sub>r</sub></em> = <em>C<sub>d</sub></em>
*</pre>
* @since 1.4
*/
public static final int DST = 9;
// Note that DST was added in 1.4 so it is numbered out of order...
/** {@collect.stats}
* The source is composited over the destination
* (Porter-Duff Source Over Destination rule).
*<p>
* <em>F<sub>s</sub></em> = 1 and <em>F<sub>d</sub></em> = (1-<em>A<sub>s</sub></em>), thus:
*<pre>
* <em>A<sub>r</sub></em> = <em>A<sub>s</sub></em> + <em>A<sub>d</sub></em>*(1-<em>A<sub>s</sub></em>)
* <em>C<sub>r</sub></em> = <em>C<sub>s</sub></em> + <em>C<sub>d</sub></em>*(1-<em>A<sub>s</sub></em>)
*</pre>
*/
public static final int SRC_OVER = 3;
/** {@collect.stats}
* The destination is composited over the source and
* the result replaces the destination
* (Porter-Duff Destination Over Source rule).
*<p>
* <em>F<sub>s</sub></em> = (1-<em>A<sub>d</sub></em>) and <em>F<sub>d</sub></em> = 1, thus:
*<pre>
* <em>A<sub>r</sub></em> = <em>A<sub>s</sub></em>*(1-<em>A<sub>d</sub></em>) + <em>A<sub>d</sub></em>
* <em>C<sub>r</sub></em> = <em>C<sub>s</sub></em>*(1-<em>A<sub>d</sub></em>) + <em>C<sub>d</sub></em>
*</pre>
*/
public static final int DST_OVER = 4;
/** {@collect.stats}
* The part of the source lying inside of the destination replaces
* the destination
* (Porter-Duff Source In Destination rule).
*<p>
* <em>F<sub>s</sub></em> = <em>A<sub>d</sub></em> and <em>F<sub>d</sub></em> = 0, thus:
*<pre>
* <em>A<sub>r</sub></em> = <em>A<sub>s</sub></em>*<em>A<sub>d</sub></em>
* <em>C<sub>r</sub></em> = <em>C<sub>s</sub></em>*<em>A<sub>d</sub></em>
*</pre>
*/
public static final int SRC_IN = 5;
/** {@collect.stats}
* The part of the destination lying inside of the source
* replaces the destination
* (Porter-Duff Destination In Source rule).
*<p>
* <em>F<sub>s</sub></em> = 0 and <em>F<sub>d</sub></em> = <em>A<sub>s</sub></em>, thus:
*<pre>
* <em>A<sub>r</sub></em> = <em>A<sub>d</sub></em>*<em>A<sub>s</sub></em>
* <em>C<sub>r</sub></em> = <em>C<sub>d</sub></em>*<em>A<sub>s</sub></em>
*</pre>
*/
public static final int DST_IN = 6;
/** {@collect.stats}
* The part of the source lying outside of the destination
* replaces the destination
* (Porter-Duff Source Held Out By Destination rule).
*<p>
* <em>F<sub>s</sub></em> = (1-<em>A<sub>d</sub></em>) and <em>F<sub>d</sub></em> = 0, thus:
*<pre>
* <em>A<sub>r</sub></em> = <em>A<sub>s</sub></em>*(1-<em>A<sub>d</sub></em>)
* <em>C<sub>r</sub></em> = <em>C<sub>s</sub></em>*(1-<em>A<sub>d</sub></em>)
*</pre>
*/
public static final int SRC_OUT = 7;
/** {@collect.stats}
* The part of the destination lying outside of the source
* replaces the destination
* (Porter-Duff Destination Held Out By Source rule).
*<p>
* <em>F<sub>s</sub></em> = 0 and <em>F<sub>d</sub></em> = (1-<em>A<sub>s</sub></em>), thus:
*<pre>
* <em>A<sub>r</sub></em> = <em>A<sub>d</sub></em>*(1-<em>A<sub>s</sub></em>)
* <em>C<sub>r</sub></em> = <em>C<sub>d</sub></em>*(1-<em>A<sub>s</sub></em>)
*</pre>
*/
public static final int DST_OUT = 8;
// Rule 9 is DST which is defined above where it fits into the
// list logically, rather than numerically
//
// public static final int DST = 9;
/** {@collect.stats}
* The part of the source lying inside of the destination
* is composited onto the destination
* (Porter-Duff Source Atop Destination rule).
*<p>
* <em>F<sub>s</sub></em> = <em>A<sub>d</sub></em> and <em>F<sub>d</sub></em> = (1-<em>A<sub>s</sub></em>), thus:
*<pre>
* <em>A<sub>r</sub></em> = <em>A<sub>s</sub></em>*<em>A<sub>d</sub></em> + <em>A<sub>d</sub></em>*(1-<em>A<sub>s</sub></em>) = <em>A<sub>d</sub></em>
* <em>C<sub>r</sub></em> = <em>C<sub>s</sub></em>*<em>A<sub>d</sub></em> + <em>C<sub>d</sub></em>*(1-<em>A<sub>s</sub></em>)
*</pre>
* @since 1.4
*/
public static final int SRC_ATOP = 10;
/** {@collect.stats}
* The part of the destination lying inside of the source
* is composited over the source and replaces the destination
* (Porter-Duff Destination Atop Source rule).
*<p>
* <em>F<sub>s</sub></em> = (1-<em>A<sub>d</sub></em>) and <em>F<sub>d</sub></em> = <em>A<sub>s</sub></em>, thus:
*<pre>
* <em>A<sub>r</sub></em> = <em>A<sub>s</sub></em>*(1-<em>A<sub>d</sub></em>) + <em>A<sub>d</sub></em>*<em>A<sub>s</sub></em> = <em>A<sub>s</sub></em>
* <em>C<sub>r</sub></em> = <em>C<sub>s</sub></em>*(1-<em>A<sub>d</sub></em>) + <em>C<sub>d</sub></em>*<em>A<sub>s</sub></em>
*</pre>
* @since 1.4
*/
public static final int DST_ATOP = 11;
/** {@collect.stats}
* The part of the source that lies outside of the destination
* is combined with the part of the destination that lies outside
* of the source
* (Porter-Duff Source Xor Destination rule).
*<p>
* <em>F<sub>s</sub></em> = (1-<em>A<sub>d</sub></em>) and <em>F<sub>d</sub></em> = (1-<em>A<sub>s</sub></em>), thus:
*<pre>
* <em>A<sub>r</sub></em> = <em>A<sub>s</sub></em>*(1-<em>A<sub>d</sub></em>) + <em>A<sub>d</sub></em>*(1-<em>A<sub>s</sub></em>)
* <em>C<sub>r</sub></em> = <em>C<sub>s</sub></em>*(1-<em>A<sub>d</sub></em>) + <em>C<sub>d</sub></em>*(1-<em>A<sub>s</sub></em>)
*</pre>
* @since 1.4
*/
public static final int XOR = 12;
/** {@collect.stats}
* <code>AlphaComposite</code> object that implements the opaque CLEAR rule
* with an alpha of 1.0f.
* @see #CLEAR
*/
public static final AlphaComposite Clear = new AlphaComposite(CLEAR);
/** {@collect.stats}
* <code>AlphaComposite</code> object that implements the opaque SRC rule
* with an alpha of 1.0f.
* @see #SRC
*/
public static final AlphaComposite Src = new AlphaComposite(SRC);
/** {@collect.stats}
* <code>AlphaComposite</code> object that implements the opaque DST rule
* with an alpha of 1.0f.
* @see #DST
* @since 1.4
*/
public static final AlphaComposite Dst = new AlphaComposite(DST);
/** {@collect.stats}
* <code>AlphaComposite</code> object that implements the opaque SRC_OVER rule
* with an alpha of 1.0f.
* @see #SRC_OVER
*/
public static final AlphaComposite SrcOver = new AlphaComposite(SRC_OVER);
/** {@collect.stats}
* <code>AlphaComposite</code> object that implements the opaque DST_OVER rule
* with an alpha of 1.0f.
* @see #DST_OVER
*/
public static final AlphaComposite DstOver = new AlphaComposite(DST_OVER);
/** {@collect.stats}
* <code>AlphaComposite</code> object that implements the opaque SRC_IN rule
* with an alpha of 1.0f.
* @see #SRC_IN
*/
public static final AlphaComposite SrcIn = new AlphaComposite(SRC_IN);
/** {@collect.stats}
* <code>AlphaComposite</code> object that implements the opaque DST_IN rule
* with an alpha of 1.0f.
* @see #DST_IN
*/
public static final AlphaComposite DstIn = new AlphaComposite(DST_IN);
/** {@collect.stats}
* <code>AlphaComposite</code> object that implements the opaque SRC_OUT rule
* with an alpha of 1.0f.
* @see #SRC_OUT
*/
public static final AlphaComposite SrcOut = new AlphaComposite(SRC_OUT);
/** {@collect.stats}
* <code>AlphaComposite</code> object that implements the opaque DST_OUT rule
* with an alpha of 1.0f.
* @see #DST_OUT
*/
public static final AlphaComposite DstOut = new AlphaComposite(DST_OUT);
/** {@collect.stats}
* <code>AlphaComposite</code> object that implements the opaque SRC_ATOP rule
* with an alpha of 1.0f.
* @see #SRC_ATOP
* @since 1.4
*/
public static final AlphaComposite SrcAtop = new AlphaComposite(SRC_ATOP);
/** {@collect.stats}
* <code>AlphaComposite</code> object that implements the opaque DST_ATOP rule
* with an alpha of 1.0f.
* @see #DST_ATOP
* @since 1.4
*/
public static final AlphaComposite DstAtop = new AlphaComposite(DST_ATOP);
/** {@collect.stats}
* <code>AlphaComposite</code> object that implements the opaque XOR rule
* with an alpha of 1.0f.
* @see #XOR
* @since 1.4
*/
public static final AlphaComposite Xor = new AlphaComposite(XOR);
private static final int MIN_RULE = CLEAR;
private static final int MAX_RULE = XOR;
float extraAlpha;
int rule;
private AlphaComposite(int rule) {
this(rule, 1.0f);
}
private AlphaComposite(int rule, float alpha) {
if (alpha < 0.0f || alpha > 1.0f) {
throw new IllegalArgumentException("alpha value out of range");
}
if (rule < MIN_RULE || rule > MAX_RULE) {
throw new IllegalArgumentException("unknown composite rule");
}
this.rule = rule;
this.extraAlpha = alpha;
}
/** {@collect.stats}
* Creates an <code>AlphaComposite</code> object with the specified rule.
* @param rule the compositing rule
* @throws IllegalArgumentException if <code>rule</code> is not one of
* the following: {@link #CLEAR}, {@link #SRC}, {@link #DST},
* {@link #SRC_OVER}, {@link #DST_OVER}, {@link #SRC_IN},
* {@link #DST_IN}, {@link #SRC_OUT}, {@link #DST_OUT},
* {@link #SRC_ATOP}, {@link #DST_ATOP}, or {@link #XOR}
*/
public static AlphaComposite getInstance(int rule) {
switch (rule) {
case CLEAR:
return Clear;
case SRC:
return Src;
case DST:
return Dst;
case SRC_OVER:
return SrcOver;
case DST_OVER:
return DstOver;
case SRC_IN:
return SrcIn;
case DST_IN:
return DstIn;
case SRC_OUT:
return SrcOut;
case DST_OUT:
return DstOut;
case SRC_ATOP:
return SrcAtop;
case DST_ATOP:
return DstAtop;
case XOR:
return Xor;
default:
throw new IllegalArgumentException("unknown composite rule");
}
}
/** {@collect.stats}
* Creates an <code>AlphaComposite</code> object with the specified rule and
* the constant alpha to multiply with the alpha of the source.
* The source is multiplied with the specified alpha before being composited
* with the destination.
* @param rule the compositing rule
* @param alpha the constant alpha to be multiplied with the alpha of
* the source. <code>alpha</code> must be a floating point number in the
* inclusive range [0.0, 1.0].
* @throws IllegalArgumentException if
* <code>alpha</code> is less than 0.0 or greater than 1.0, or if
* <code>rule</code> is not one of
* the following: {@link #CLEAR}, {@link #SRC}, {@link #DST},
* {@link #SRC_OVER}, {@link #DST_OVER}, {@link #SRC_IN},
* {@link #DST_IN}, {@link #SRC_OUT}, {@link #DST_OUT},
* {@link #SRC_ATOP}, {@link #DST_ATOP}, or {@link #XOR}
*/
public static AlphaComposite getInstance(int rule, float alpha) {
if (alpha == 1.0f) {
return getInstance(rule);
}
return new AlphaComposite(rule, alpha);
}
/** {@collect.stats}
* Creates a context for the compositing operation.
* The context contains state that is used in performing
* the compositing operation.
* @param srcColorModel the {@link ColorModel} of the source
* @param dstColorModel the <code>ColorModel</code> of the destination
* @return the <code>CompositeContext</code> object to be used to perform
* compositing operations.
*/
public CompositeContext createContext(ColorModel srcColorModel,
ColorModel dstColorModel,
RenderingHints hints) {
return new SunCompositeContext(this, srcColorModel, dstColorModel);
}
/** {@collect.stats}
* Returns the alpha value of this <code>AlphaComposite</code>. If this
* <code>AlphaComposite</code> does not have an alpha value, 1.0 is returned.
* @return the alpha value of this <code>AlphaComposite</code>.
*/
public float getAlpha() {
return extraAlpha;
}
/** {@collect.stats}
* Returns the compositing rule of this <code>AlphaComposite</code>.
* @return the compositing rule of this <code>AlphaComposite</code>.
*/
public int getRule() {
return rule;
}
/** {@collect.stats}
* Returns a similar <code>AlphaComposite</code> object that uses
* the specified compositing rule.
* If this object already uses the specified compositing rule,
* this object is returned.
* @return an <code>AlphaComposite</code> object derived from
* this object that uses the specified compositing rule.
* @param rule the compositing rule
* @throws IllegalArgumentException if
* <code>rule</code> is not one of
* the following: {@link #CLEAR}, {@link #SRC}, {@link #DST},
* {@link #SRC_OVER}, {@link #DST_OVER}, {@link #SRC_IN},
* {@link #DST_IN}, {@link #SRC_OUT}, {@link #DST_OUT},
* {@link #SRC_ATOP}, {@link #DST_ATOP}, or {@link #XOR}
* @since 1.6
*/
public AlphaComposite derive(int rule) {
return (this.rule == rule)
? this
: getInstance(rule, this.extraAlpha);
}
/** {@collect.stats}
* Returns a similar <code>AlphaComposite</code> object that uses
* the specified alpha value.
* If this object already has the specified alpha value,
* this object is returned.
* @return an <code>AlphaComposite</code> object derived from
* this object that uses the specified alpha value.
* @param alpha the constant alpha to be multiplied with the alpha of
* the source. <code>alpha</code> must be a floating point number in the
* inclusive range [0.0, 1.0].
* @throws IllegalArgumentException if
* <code>alpha</code> is less than 0.0 or greater than 1.0
* @since 1.6
*/
public AlphaComposite derive(float alpha) {
return (this.extraAlpha == alpha)
? this
: getInstance(this.rule, alpha);
}
/** {@collect.stats}
* Returns the hashcode for this composite.
* @return a hash code for this composite.
*/
public int hashCode() {
return (Float.floatToIntBits(extraAlpha) * 31 + rule);
}
/** {@collect.stats}
* Determines whether the specified object is equal to this
* <code>AlphaComposite</code>.
* <p>
* The result is <code>true</code> if and only if
* the argument is not <code>null</code> and is an
* <code>AlphaComposite</code> object that has the same
* compositing rule and alpha value as this object.
*
* @param obj the <code>Object</code> to test for equality
* @return <code>true</code> if <code>obj</code> equals this
* <code>AlphaComposite</code>; <code>false</code> otherwise.
*/
public boolean equals(Object obj) {
if (!(obj instanceof AlphaComposite)) {
return false;
}
AlphaComposite ac = (AlphaComposite) obj;
if (rule != ac.rule) {
return false;
}
if (extraAlpha != ac.extraAlpha) {
return false;
}
return true;
}
}
|
Java
|
/*
* Copyright (c) 2005, 2007, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code 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
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package java.awt;
import java.io.IOException;
import java.awt.image.*;
import java.net.URL;
import java.net.URLConnection;
import java.io.File;
import java.util.logging.Logger;
import java.util.logging.Level;
import sun.awt.image.SunWritableRaster;
/** {@collect.stats}
* The splash screen can be created at application startup, before the
* Java Virtual Machine (JVM) starts. The splash screen is displayed as an
* undecorated window containing an image. You can use GIF, JPEG, and PNG files
* for the image. Animation (for GIF) and transparency (for GIF, PNG) are
* supported. The window is positioned at the center of the screen (the
* position on multi-monitor systems is not specified - it is platform and
* implementation dependent).
* The window is closed automatically as soon as the first window is displayed by
* Swing/AWT (may be also closed manually using the Java API, see below).
* <P>
* There are two ways to show the native splash screen:
* <P>
* <UL>
* <LI>If your application is run from the command line or from a shortcut,
* use the "-splash:" Java application launcher option to show a splash screen.
* <BR>
* For example:
* <PRE>
* java -splash:filename.gif Test
* </PRE>
* <LI>If your application is packaged in a jar file, you can use the
* "SplashScreen-Image" option in a manifest file to show a splash screen.
* Place the image in the jar archive and specify the path in the option.
* The path should not have a leading slash.
* <BR>
* For example, in the <code>manifest.mf</code> file:
* <PRE>
* Manifest-Version: 1.0
* Main-Class: Test
* SplashScreen-Image: filename.gif
* </PRE>
* The command line interface has higher precedence over the manifest
* setting.
* </UL>
* <p>
* The {@code SplashScreen} class provides the API for controlling the splash
* screen. This class may be used to close the splash screen, change the splash
* screen image, get the image position/size and paint in the splash screen. It
* cannot be used to create the splash screen; you should use the command line or manifest
* file option for that.
* <p>
* This class cannot be instantiated. Only a single instance of this class
* can exist, and it may be obtained using the {@link #getSplashScreen()}
* static method. In case the splash screen has not been created at
* application startup via the command line or manifest file option,
* the <code>getSplashScreen</code> method returns <code>null</code>.
*
* @author Oleg Semenov
* @since 1.6
*/
public final class SplashScreen {
SplashScreen(long ptr) { // non-public constructor
splashPtr = ptr;
}
/** {@collect.stats}
* Returns the {@code SplashScreen} object used for
* Java startup splash screen control.
*
* @throws UnsupportedOperationException if the splash screen feature is not
* supported by the current toolkit
* @throws HeadlessException if {@code GraphicsEnvironment.isHeadless()}
* returns true
* @return the {@link SplashScreen} instance, or <code>null</code> if there is
* none or it has already been closed
*/
public static SplashScreen getSplashScreen() {
synchronized (SplashScreen.class) {
if (GraphicsEnvironment.isHeadless()) {
throw new HeadlessException();
}
// SplashScreen class is now a singleton
if (!wasClosed && theInstance == null) {
java.security.AccessController.doPrivileged(
new sun.security.action.LoadLibraryAction("splashscreen"));
long ptr = _getInstance();
if (ptr != 0 && _isVisible(ptr)) {
theInstance = new SplashScreen(ptr);
}
}
return theInstance;
}
}
/** {@collect.stats}
* Changes the splash screen image. The new image is loaded from the
* specified URL; GIF, JPEG and PNG image formats are supported.
* The method returns after the image has finished loading and the window
* has been updated.
* The splash screen window is resized according to the size of
* the image and is centered on the screen.
*
* @param imageURL the non-<code>null</code> URL for the new
* splash screen image
* @throws NullPointerException if {@code imageURL} is <code>null</code>
* @throws IOException if there was an error while loading the image
* @throws IllegalStateException if the splash screen has already been
* closed
*/
public void setImageURL(URL imageURL) throws NullPointerException, IOException, IllegalStateException {
checkVisible();
URLConnection connection = imageURL.openConnection();
connection.connect();
int length = connection.getContentLength();
java.io.InputStream stream = connection.getInputStream();
byte[] buf = new byte[length];
int off = 0;
while(true) {
// check for available data
int available = stream.available();
if (available <= 0) {
// no data available... well, let's try reading one byte
// we'll see what happens then
available = 1;
}
// check for enough room in buffer, realloc if needed
// the buffer always grows in size 2x minimum
if (off + available > length) {
length = off*2;
if (off + available > length) {
length = available+off;
}
byte[] oldBuf = buf;
buf = new byte[length];
System.arraycopy(oldBuf, 0, buf, 0, off);
}
// now read the data
int result = stream.read(buf, off, available);
if (result < 0) {
break;
}
off += result;
}
synchronized(SplashScreen.class) {
checkVisible();
if (!_setImageData(splashPtr, buf)) {
throw new IOException("Bad image format or i/o error when loading image");
}
this.imageURL = imageURL;
}
}
private void checkVisible() {
if (!isVisible()) {
throw new IllegalStateException("no splash screen available");
}
}
/** {@collect.stats}
* Returns the current splash screen image.
*
* @return URL for the current splash screen image file
* @throws IllegalStateException if the splash screen has already been closed
*/
public URL getImageURL() throws IllegalStateException {
synchronized (SplashScreen.class) {
checkVisible();
if (imageURL == null) {
try {
String fileName = _getImageFileName(splashPtr);
String jarName = _getImageJarName(splashPtr);
if (fileName != null) {
if (jarName != null) {
imageURL = new URL("jar:"+(new File(jarName).toURL().toString())+"!/"+fileName);
} else {
imageURL = new File(fileName).toURL();
}
}
}
catch(java.net.MalformedURLException e) {
if (log.isLoggable(Level.FINE)) {
log.log(Level.FINE, "MalformedURLException caught in the getImageURL() method", e);
}
}
}
return imageURL;
}
}
/** {@collect.stats}
* Returns the bounds of the splash screen window as a {@link Rectangle}.
* This may be useful if, for example, you want to replace the splash
* screen with your window at the same location.
* <p>
* You cannot control the size or position of the splash screen.
* The splash screen size is adjusted automatically when the image changes.
*
* @return a {@code Rectangle} containing the splash screen bounds
* @throws IllegalStateException if the splash screen has already been closed
*/
public Rectangle getBounds() throws IllegalStateException {
synchronized (SplashScreen.class) {
checkVisible();
return _getBounds(splashPtr);
}
}
/** {@collect.stats}
* Returns the size of the splash screen window as a {@link Dimension}.
* This may be useful if, for example,
* you want to draw on the splash screen overlay surface.
* <p>
* You cannot control the size or position of the splash screen.
* The splash screen size is adjusted automatically when the image changes.
*
* @return a {@link Dimension} object indicating the splash screen size
* @throws IllegalStateException if the splash screen has already been closed
*/
public Dimension getSize() throws IllegalStateException {
return getBounds().getSize();
}
/** {@collect.stats}
* Creates a graphics context (as a {@link Graphics2D} object) for the splash
* screen overlay image, which allows you to draw over the splash screen.
* Note that you do not draw on the main image but on the image that is
* displayed over the main image using alpha blending. Also note that drawing
* on the overlay image does not necessarily update the contents of splash
* screen window. You should call {@code update()} on the
* <code>SplashScreen</code> when you want the splash screen to be
* updated immediately.
*
* @return graphics context for the splash screen overlay surface
* @throws IllegalStateException if the splash screen has already been closed
*/
public Graphics2D createGraphics() throws IllegalStateException {
synchronized (SplashScreen.class) {
if (image==null) {
Dimension dim = getSize();
image = new BufferedImage(dim.width, dim.height, BufferedImage.TYPE_INT_ARGB);
}
return image.createGraphics();
}
}
/** {@collect.stats}
* Updates the splash window with current contents of the overlay image.
*
* @throws IllegalStateException if the overlay image does not exist;
* for example, if {@code createGraphics} has never been called,
* or if the splash screen has already been closed
*/
public void update() throws IllegalStateException {
BufferedImage image;
synchronized (SplashScreen.class) {
checkVisible();
image = this.image;
}
if (image == null) {
throw new IllegalStateException("no overlay image available");
}
DataBuffer buf = image.getRaster().getDataBuffer();
if (!(buf instanceof DataBufferInt)) {
throw new AssertionError("Overlay image DataBuffer is of invalid type == "+buf.getClass().getName());
}
int numBanks = buf.getNumBanks();
if (numBanks!=1) {
throw new AssertionError("Invalid number of banks =="+numBanks+" in overlay image DataBuffer");
}
if (!(image.getSampleModel() instanceof SinglePixelPackedSampleModel)) {
throw new AssertionError("Overlay image has invalid sample model == "+image.getSampleModel().getClass().getName());
}
SinglePixelPackedSampleModel sm = (SinglePixelPackedSampleModel)image.getSampleModel();
int scanlineStride = sm.getScanlineStride();
Rectangle rect = image.getRaster().getBounds();
// Note that we steal the data array here, but just for reading
// so we do not need to mark the DataBuffer dirty...
int[] data = SunWritableRaster.stealData((DataBufferInt)buf, 0);
synchronized(SplashScreen.class) {
checkVisible();
_update(splashPtr, data, rect.x, rect.y, rect.width, rect.height, scanlineStride);
}
}
/** {@collect.stats}
* Hides the splash screen, closes the window, and releases all associated
* resources.
*
* @throws IllegalStateException if the splash screen has already been closed
*/
public void close() throws IllegalStateException {
synchronized (SplashScreen.class) {
checkVisible();
_close(splashPtr);
image = null;
wasClosed = true;
theInstance = null;
}
}
/** {@collect.stats}
* Determines whether the splash screen is visible. The splash screen may
* be hidden using {@link #close()}, it is also hidden automatically when
* the first AWT/Swing window is made visible.
*
* @return true if the splash screen is visible (has not been closed yet),
* false otherwise
*/
public boolean isVisible() {
synchronized (SplashScreen.class) {
return !wasClosed && _isVisible(splashPtr);
}
}
private BufferedImage image; // overlay image
private final long splashPtr; // pointer to native Splash structure
private static boolean wasClosed = false;
private URL imageURL;
/** {@collect.stats}
* The instance reference for the singleton.
* (<code>null</code> if no instance exists yet.)
*
* @see #getSplashScreen
* @see #close
*/
private static SplashScreen theInstance = null;
private static final Logger log = Logger.getLogger("java.awt.SplashScreen");
private native static void _update(long splashPtr, int[] data, int x, int y, int width, int height, int scanlineStride);
private native static boolean _isVisible(long splashPtr);
private native static Rectangle _getBounds(long splashPtr);
private native static long _getInstance();
private native static void _close(long splashPtr);
private native static String _getImageFileName(long splashPtr);
private native static String _getImageJarName(long SplashPtr);
private native static boolean _setImageData(long SplashPtr, byte[] data);
};
|
Java
|
/*
* Copyright (c) 2006, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code 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
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package java.awt;
import java.awt.geom.AffineTransform;
import java.awt.image.ColorModel;
import java.lang.ref.SoftReference;
import java.util.Arrays;
/** {@collect.stats}
* This is the superclass for Paints which use a multiple color
* gradient to fill in their raster. It provides storage for variables and
* enumerated values common to
* {@code LinearGradientPaint} and {@code RadialGradientPaint}.
*
* @author Nicholas Talian, Vincent Hardy, Jim Graham, Jerry Evans
* @since 1.6
*/
public abstract class MultipleGradientPaint implements Paint {
/** {@collect.stats} The method to use when painting outside the gradient bounds.
* @since 1.6
*/
public static enum CycleMethod {
/** {@collect.stats}
* Use the terminal colors to fill the remaining area.
*/
NO_CYCLE,
/** {@collect.stats}
* Cycle the gradient colors start-to-end, end-to-start
* to fill the remaining area.
*/
REFLECT,
/** {@collect.stats}
* Cycle the gradient colors start-to-end, start-to-end
* to fill the remaining area.
*/
REPEAT
}
/** {@collect.stats} The color space in which to perform the gradient interpolation.
* @since 1.6
*/
public static enum ColorSpaceType {
/** {@collect.stats}
* Indicates that the color interpolation should occur in sRGB space.
*/
SRGB,
/** {@collect.stats}
* Indicates that the color interpolation should occur in linearized
* RGB space.
*/
LINEAR_RGB
}
/** {@collect.stats} The transparency of this paint object. */
final int transparency;
/** {@collect.stats} Gradient keyframe values in the range 0 to 1. */
final float[] fractions;
/** {@collect.stats} Gradient colors. */
final Color[] colors;
/** {@collect.stats} Transform to apply to gradient. */
final AffineTransform gradientTransform;
/** {@collect.stats} The method to use when painting outside the gradient bounds. */
final CycleMethod cycleMethod;
/** {@collect.stats} The color space in which to perform the gradient interpolation. */
final ColorSpaceType colorSpace;
/** {@collect.stats}
* The following fields are used only by MultipleGradientPaintContext
* to cache certain values that remain constant and do not need to be
* recalculated for each context created from this paint instance.
*/
ColorModel model;
float[] normalizedIntervals;
boolean isSimpleLookup;
SoftReference<int[][]> gradients;
SoftReference<int[]> gradient;
int fastGradientArraySize;
/** {@collect.stats}
* Package-private constructor.
*
* @param fractions numbers ranging from 0.0 to 1.0 specifying the
* distribution of colors along the gradient
* @param colors array of colors corresponding to each fractional value
* @param cycleMethod either {@code NO_CYCLE}, {@code REFLECT},
* or {@code REPEAT}
* @param colorSpace which color space to use for interpolation,
* either {@code SRGB} or {@code LINEAR_RGB}
* @param gradientTransform transform to apply to the gradient
*
* @throws NullPointerException
* if {@code fractions} array is null,
* or {@code colors} array is null,
* or {@code gradientTransform} is null,
* or {@code cycleMethod} is null,
* or {@code colorSpace} is null
* @throws IllegalArgumentException
* if {@code fractions.length != colors.length},
* or {@code colors} is less than 2 in size,
* or a {@code fractions} value is less than 0.0 or greater than 1.0,
* or the {@code fractions} are not provided in strictly increasing order
*/
MultipleGradientPaint(float[] fractions,
Color[] colors,
CycleMethod cycleMethod,
ColorSpaceType colorSpace,
AffineTransform gradientTransform)
{
if (fractions == null) {
throw new NullPointerException("Fractions array cannot be null");
}
if (colors == null) {
throw new NullPointerException("Colors array cannot be null");
}
if (cycleMethod == null) {
throw new NullPointerException("Cycle method cannot be null");
}
if (colorSpace == null) {
throw new NullPointerException("Color space cannot be null");
}
if (gradientTransform == null) {
throw new NullPointerException("Gradient transform cannot be "+
"null");
}
if (fractions.length != colors.length) {
throw new IllegalArgumentException("Colors and fractions must " +
"have equal size");
}
if (colors.length < 2) {
throw new IllegalArgumentException("User must specify at least " +
"2 colors");
}
// check that values are in the proper range and progress
// in increasing order from 0 to 1
float previousFraction = -1.0f;
for (float currentFraction : fractions) {
if (currentFraction < 0f || currentFraction > 1f) {
throw new IllegalArgumentException("Fraction values must " +
"be in the range 0 to 1: " +
currentFraction);
}
if (currentFraction <= previousFraction) {
throw new IllegalArgumentException("Keyframe fractions " +
"must be increasing: " +
currentFraction);
}
previousFraction = currentFraction;
}
// We have to deal with the cases where the first gradient stop is not
// equal to 0 and/or the last gradient stop is not equal to 1.
// In both cases, create a new point and replicate the previous
// extreme point's color.
boolean fixFirst = false;
boolean fixLast = false;
int len = fractions.length;
int off = 0;
if (fractions[0] != 0f) {
// first stop is not equal to zero, fix this condition
fixFirst = true;
len++;
off++;
}
if (fractions[fractions.length-1] != 1f) {
// last stop is not equal to one, fix this condition
fixLast = true;
len++;
}
this.fractions = new float[len];
System.arraycopy(fractions, 0, this.fractions, off, fractions.length);
this.colors = new Color[len];
System.arraycopy(colors, 0, this.colors, off, colors.length);
if (fixFirst) {
this.fractions[0] = 0f;
this.colors[0] = colors[0];
}
if (fixLast) {
this.fractions[len-1] = 1f;
this.colors[len-1] = colors[colors.length - 1];
}
// copy some flags
this.colorSpace = colorSpace;
this.cycleMethod = cycleMethod;
// copy the gradient transform
this.gradientTransform = new AffineTransform(gradientTransform);
// determine transparency
boolean opaque = true;
for (int i = 0; i < colors.length; i++){
opaque = opaque && (colors[i].getAlpha() == 0xff);
}
this.transparency = opaque ? OPAQUE : TRANSLUCENT;
}
/** {@collect.stats}
* Returns a copy of the array of floats used by this gradient
* to calculate color distribution.
* The returned array always has 0 as its first value and 1 as its
* last value, with increasing values in between.
*
* @return a copy of the array of floats used by this gradient to
* calculate color distribution
*/
public final float[] getFractions() {
return Arrays.copyOf(fractions, fractions.length);
}
/** {@collect.stats}
* Returns a copy of the array of colors used by this gradient.
* The first color maps to the first value in the fractions array,
* and the last color maps to the last value in the fractions array.
*
* @return a copy of the array of colors used by this gradient
*/
public final Color[] getColors() {
return Arrays.copyOf(colors, colors.length);
}
/** {@collect.stats}
* Returns the enumerated type which specifies cycling behavior.
*
* @return the enumerated type which specifies cycling behavior
*/
public final CycleMethod getCycleMethod() {
return cycleMethod;
}
/** {@collect.stats}
* Returns the enumerated type which specifies color space for
* interpolation.
*
* @return the enumerated type which specifies color space for
* interpolation
*/
public final ColorSpaceType getColorSpace() {
return colorSpace;
}
/** {@collect.stats}
* Returns a copy of the transform applied to the gradient.
*
* @return a copy of the transform applied to the gradient
*/
public final AffineTransform getTransform() {
return new AffineTransform(gradientTransform);
}
/** {@collect.stats}
* Returns the transparency mode for this Paint object.
*
* @return an integer value representing the transparency mode for
* this Paint object
* @see java.awt.Transparency
*/
public final int getTransparency() {
return transparency;
}
}
|
Java
|
/*
* Copyright (c) 1996, 2011, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code 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
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package java.awt;
import java.awt.event.InputEvent;
import java.awt.event.MouseEvent;
import java.awt.event.ActionEvent;
import java.awt.event.WindowEvent;
import java.lang.reflect.Method;
import java.security.AccessController;
import sun.security.action.GetPropertyAction;
import sun.awt.AWTAutoShutdown;
import sun.awt.SunToolkit;
import java.util.Vector;
import java.util.logging.*;
import sun.awt.dnd.SunDragSourceContextPeer;
/** {@collect.stats}
* EventDispatchThread is a package-private AWT class which takes
* events off the EventQueue and dispatches them to the appropriate
* AWT components.
*
* The Thread starts a "permanent" event pump with a call to
* pumpEvents(Conditional) in its run() method. Event handlers can choose to
* block this event pump at any time, but should start a new pump (<b>not</b>
* a new EventDispatchThread) by again calling pumpEvents(Conditional). This
* secondary event pump will exit automatically as soon as the Condtional
* evaluate()s to false and an additional Event is pumped and dispatched.
*
* @author Tom Ball
* @author Amy Fowler
* @author Fred Ecks
* @author David Mendenhall
*
* @since 1.1
*/
class EventDispatchThread extends Thread {
private static final Logger eventLog = Logger.getLogger("java.awt.event.EventDispatchThread");
private EventQueue theQueue;
private boolean doDispatch = true;
private static final int ANY_EVENT = -1;
private Vector<EventFilter> eventFilters = new Vector<EventFilter>();
// used in handleException
private int modalFiltersCount = 0;
EventDispatchThread(ThreadGroup group, String name, EventQueue queue) {
super(group, name);
theQueue = queue;
}
void stopDispatchingImpl(boolean wait) {
// Note: We stop dispatching via a flag rather than using
// Thread.interrupt() because we can't guarantee that the wait()
// we interrupt will be EventQueue.getNextEvent()'s. -fredx 8-11-98
StopDispatchEvent stopEvent = new StopDispatchEvent();
// wait for the dispatcher to complete
if (Thread.currentThread() != this) {
// fix 4122683, 4128923
// Post an empty event to ensure getNextEvent is unblocked
//
// We have to use postEventPrivate instead of postEvent because
// EventQueue.pop calls EventDispatchThread.stopDispatching.
// Calling SunToolkit.flushPendingEvents in this case could
// lead to deadlock.
theQueue.postEventPrivate(stopEvent);
if (wait) {
try {
join();
} catch(InterruptedException e) {
}
}
} else {
stopEvent.dispatch();
}
synchronized (theQueue) {
if (theQueue.getDispatchThread() == this) {
theQueue.detachDispatchThread();
}
}
}
public void stopDispatching() {
stopDispatchingImpl(true);
}
public void stopDispatchingLater() {
stopDispatchingImpl(false);
}
class StopDispatchEvent extends AWTEvent implements ActiveEvent {
/*
* serialVersionUID
*/
static final long serialVersionUID = -3692158172100730735L;
public StopDispatchEvent() {
super(EventDispatchThread.this,0);
}
public void dispatch() {
doDispatch = false;
}
}
public void run() {
try {
pumpEvents(new Conditional() {
public boolean evaluate() {
return true;
}
});
} finally {
/*
* This synchronized block is to secure that the event dispatch
* thread won't die in the middle of posting a new event to the
* associated event queue. It is important because we notify
* that the event dispatch thread is busy after posting a new event
* to its queue, so the EventQueue.dispatchThread reference must
* be valid at that point.
*/
synchronized (theQueue) {
if (theQueue.getDispatchThread() == this) {
theQueue.detachDispatchThread();
}
/*
* Event dispatch thread dies in case of an uncaught exception.
* A new event dispatch thread for this queue will be started
* only if a new event is posted to it. In case if no more
* events are posted after this thread died all events that
* currently are in the queue will never be dispatched.
*/
/*
* Fix for 4648733. Check both the associated java event
* queue and the PostEventQueue.
*/
if (theQueue.peekEvent() != null ||
!SunToolkit.isPostEventQueueEmpty()) {
theQueue.initDispatchThread();
}
AWTAutoShutdown.getInstance().notifyThreadFree(this);
}
}
}
void pumpEvents(Conditional cond) {
pumpEvents(ANY_EVENT, cond);
}
void pumpEventsForHierarchy(Conditional cond, Component modalComponent) {
pumpEventsForHierarchy(ANY_EVENT, cond, modalComponent);
}
void pumpEvents(int id, Conditional cond) {
pumpEventsForHierarchy(id, cond, null);
}
void pumpEventsForHierarchy(int id, Conditional cond, Component modalComponent)
{
pumpEventsForFilter(id, cond, new HierarchyEventFilter(modalComponent));
}
void pumpEventsForFilter(Conditional cond, EventFilter filter) {
pumpEventsForFilter(ANY_EVENT, cond, filter);
}
void pumpEventsForFilter(int id, Conditional cond, EventFilter filter) {
addEventFilter(filter);
while (doDispatch && cond.evaluate()) {
if (isInterrupted() || !pumpOneEventForFilters(id)) {
doDispatch = false;
}
}
removeEventFilter(filter);
}
void addEventFilter(EventFilter filter) {
synchronized (eventFilters) {
if (!eventFilters.contains(filter)) {
if (filter instanceof ModalEventFilter) {
ModalEventFilter newFilter = (ModalEventFilter)filter;
int k = 0;
for (k = 0; k < eventFilters.size(); k++) {
EventFilter f = eventFilters.get(k);
if (f instanceof ModalEventFilter) {
ModalEventFilter cf = (ModalEventFilter)f;
if (cf.compareTo(newFilter) > 0) {
break;
}
}
}
eventFilters.add(k, filter);
modalFiltersCount++;
} else {
eventFilters.add(filter);
}
}
}
}
void removeEventFilter(EventFilter filter) {
synchronized (eventFilters) {
if (eventFilters.contains(filter)) {
if (filter instanceof ModalEventFilter) {
modalFiltersCount--;
}
eventFilters.remove(filter);
}
}
}
boolean pumpOneEventForFilters(int id) {
try {
AWTEvent event;
boolean eventOK;
do {
event = (id == ANY_EVENT)
? theQueue.getNextEvent()
: theQueue.getNextEvent(id);
eventOK = true;
synchronized (eventFilters) {
for (int i = eventFilters.size() - 1; i >= 0; i--) {
EventFilter f = eventFilters.get(i);
EventFilter.FilterAction accept = f.acceptEvent(event);
if (accept == EventFilter.FilterAction.REJECT) {
eventOK = false;
break;
} else if (accept == EventFilter.FilterAction.ACCEPT_IMMEDIATELY) {
break;
}
}
}
eventOK = eventOK && SunDragSourceContextPeer.checkEvent(event);
if (!eventOK) {
event.consume();
}
}
while (eventOK == false);
if (eventLog.isLoggable(Level.FINEST)) {
eventLog.log(Level.FINEST, "Dispatching: " + event);
}
theQueue.dispatchEvent(event);
return true;
}
catch (ThreadDeath death) {
return false;
}
catch (InterruptedException interruptedException) {
return false; // AppContext.dispose() interrupts all
// Threads in the AppContext
}
catch (Throwable e) {
processException(e, modalFiltersCount > 0);
}
return true;
}
private void processException(Throwable e, boolean isModal) {
if (eventLog.isLoggable(Level.FINE)) {
eventLog.log(Level.FINE, "Processing exception: " + e +
", isModal = " + isModal);
}
if (!handleException(e)) {
// See bug ID 4499199.
// If we are in a modal dialog, we cannot throw
// an exception for the ThreadGroup to handle (as added
// in RFE 4063022). If we did, the message pump of
// the modal dialog would be interrupted.
// We instead choose to handle the exception ourselves.
// It may be useful to add either a runtime flag or API
// later if someone would like to instead dispose the
// dialog and allow the thread group to handle it.
if (isModal) {
System.err.println(
"Exception occurred during event dispatching:");
e.printStackTrace();
} else if (e instanceof RuntimeException) {
throw (RuntimeException)e;
} else if (e instanceof Error) {
throw (Error)e;
}
}
}
private static final String handlerPropName = "sun.awt.exception.handler";
private static String handlerClassName = null;
private static String NO_HANDLER = new String();
/** {@collect.stats}
* Handles an exception thrown in the event-dispatch thread.
*
* <p> If the system property "sun.awt.exception.handler" is defined, then
* when this method is invoked it will attempt to do the following:
*
* <ol>
* <li> Load the class named by the value of that property, using the
* current thread's context class loader,
* <li> Instantiate that class using its zero-argument constructor,
* <li> Find the resulting handler object's <tt>public void handle</tt>
* method, which should take a single argument of type
* <tt>Throwable</tt>, and
* <li> Invoke the handler's <tt>handle</tt> method, passing it the
* <tt>thrown</tt> argument that was passed to this method.
* </ol>
*
* If any of the first three steps fail then this method will return
* <tt>false</tt> and all following invocations of this method will return
* <tt>false</tt> immediately. An exception thrown by the handler object's
* <tt>handle</tt> will be caught, and will cause this method to return
* <tt>false</tt>. If the handler's <tt>handle</tt> method is successfully
* invoked, then this method will return <tt>true</tt>. This method will
* never throw any sort of exception.
*
* <p> <i>Note:</i> This method is a temporary hack to work around the
* absence of a real API that provides the ability to replace the
* event-dispatch thread. The magic "sun.awt.exception.handler" property
* <i>will be removed</i> in a future release.
*
* @param thrown The Throwable that was thrown in the event-dispatch
* thread
*
* @return <tt>false</tt> if any of the above steps failed, otherwise
* <tt>true</tt>
*/
private boolean handleException(Throwable thrown) {
try {
if (handlerClassName == NO_HANDLER) {
return false; /* Already tried, and failed */
}
/* Look up the class name */
if (handlerClassName == null) {
handlerClassName = ((String) AccessController.doPrivileged(
new GetPropertyAction(handlerPropName)));
if (handlerClassName == null) {
handlerClassName = NO_HANDLER; /* Do not try this again */
return false;
}
}
/* Load the class, instantiate it, and find its handle method */
Method m;
Object h;
try {
ClassLoader cl = Thread.currentThread().getContextClassLoader();
Class c = Class.forName(handlerClassName, true, cl);
m = c.getMethod("handle", new Class[] { Throwable.class });
h = c.newInstance();
} catch (Throwable x) {
handlerClassName = NO_HANDLER; /* Do not try this again */
return false;
}
/* Finally, invoke the handler */
m.invoke(h, new Object[] { thrown });
} catch (Throwable x) {
return false;
}
return true;
}
boolean isDispatching(EventQueue eq) {
return theQueue.equals(eq);
}
EventQueue getEventQueue() { return theQueue; }
private static class HierarchyEventFilter implements EventFilter {
private Component modalComponent;
public HierarchyEventFilter(Component modalComponent) {
this.modalComponent = modalComponent;
}
public FilterAction acceptEvent(AWTEvent event) {
if (modalComponent != null) {
int eventID = event.getID();
boolean mouseEvent = (eventID >= MouseEvent.MOUSE_FIRST) &&
(eventID <= MouseEvent.MOUSE_LAST);
boolean actionEvent = (eventID >= ActionEvent.ACTION_FIRST) &&
(eventID <= ActionEvent.ACTION_LAST);
boolean windowClosingEvent = (eventID == WindowEvent.WINDOW_CLOSING);
/*
* filter out MouseEvent and ActionEvent that's outside
* the modalComponent hierarchy.
* KeyEvent is handled by using enqueueKeyEvent
* in Dialog.show
*/
if (Component.isInstanceOf(modalComponent, "javax.swing.JInternalFrame")) {
/*
* Modal internal frames are handled separately. If event is
* for some component from another heavyweight than modalComp,
* it is accepted. If heavyweight is the same - we still accept
* event and perform further filtering in LightweightDispatcher
*/
return windowClosingEvent ? FilterAction.REJECT : FilterAction.ACCEPT;
}
if (mouseEvent || actionEvent || windowClosingEvent) {
Object o = event.getSource();
if (o instanceof sun.awt.ModalExclude) {
// Exclude this object from modality and
// continue to pump it's events.
return FilterAction.ACCEPT;
} else if (o instanceof Component) {
Component c = (Component) o;
// 5.0u3 modal exclusion
boolean modalExcluded = false;
if (modalComponent instanceof Container) {
while (c != modalComponent && c != null) {
if ((c instanceof Window) &&
(sun.awt.SunToolkit.isModalExcluded((Window)c))) {
// Exclude this window and all its children from
// modality and continue to pump it's events.
modalExcluded = true;
break;
}
c = c.getParent();
}
}
if (!modalExcluded && (c != modalComponent)) {
return FilterAction.REJECT;
}
}
}
}
return FilterAction.ACCEPT;
}
}
}
|
Java
|
/*
* Copyright (c) 1995, 2006, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code 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
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package java.awt;
import java.util.Hashtable;
import java.util.Vector;
import java.util.Enumeration;
import java.io.Serializable;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.ObjectStreamField;
import java.io.IOException;
/** {@collect.stats}
* A <code>CardLayout</code> object is a layout manager for a
* container. It treats each component in the container as a card.
* Only one card is visible at a time, and the container acts as
* a stack of cards. The first component added to a
* <code>CardLayout</code> object is the visible component when the
* container is first displayed.
* <p>
* The ordering of cards is determined by the container's own internal
* ordering of its component objects. <code>CardLayout</code>
* defines a set of methods that allow an application to flip
* through these cards sequentially, or to show a specified card.
* The {@link CardLayout#addLayoutComponent}
* method can be used to associate a string identifier with a given card
* for fast random access.
*
* @author Arthur van Hoff
* @see java.awt.Container
* @since JDK1.0
*/
public class CardLayout implements LayoutManager2,
Serializable {
private static final long serialVersionUID = -4328196481005934313L;
/*
* This creates a Vector to store associated
* pairs of components and their names.
* @see java.util.Vector
*/
Vector vector = new Vector();
/*
* A pair of Component and String that represents its name.
*/
class Card implements Serializable {
static final long serialVersionUID = 6640330810709497518L;
public String name;
public Component comp;
public Card(String cardName, Component cardComponent) {
name = cardName;
comp = cardComponent;
}
}
/*
* Index of Component currently displayed by CardLayout.
*/
int currentCard = 0;
/*
* A cards horizontal Layout gap (inset). It specifies
* the space between the left and right edges of a
* container and the current component.
* This should be a non negative Integer.
* @see getHgap()
* @see setHgap()
*/
int hgap;
/*
* A cards vertical Layout gap (inset). It specifies
* the space between the top and bottom edges of a
* container and the current component.
* This should be a non negative Integer.
* @see getVgap()
* @see setVgap()
*/
int vgap;
/** {@collect.stats}
* @serialField tab Hashtable
* deprectated, for forward compatibility only
* @serialField hgap int
* @serialField vgap int
* @serialField vector Vector
* @serialField currentCard int
*/
private static final ObjectStreamField[] serialPersistentFields = {
new ObjectStreamField("tab", Hashtable.class),
new ObjectStreamField("hgap", Integer.TYPE),
new ObjectStreamField("vgap", Integer.TYPE),
new ObjectStreamField("vector", Vector.class),
new ObjectStreamField("currentCard", Integer.TYPE)
};
/** {@collect.stats}
* Creates a new card layout with gaps of size zero.
*/
public CardLayout() {
this(0, 0);
}
/** {@collect.stats}
* Creates a new card layout with the specified horizontal and
* vertical gaps. The horizontal gaps are placed at the left and
* right edges. The vertical gaps are placed at the top and bottom
* edges.
* @param hgap the horizontal gap.
* @param vgap the vertical gap.
*/
public CardLayout(int hgap, int vgap) {
this.hgap = hgap;
this.vgap = vgap;
}
/** {@collect.stats}
* Gets the horizontal gap between components.
* @return the horizontal gap between components.
* @see java.awt.CardLayout#setHgap(int)
* @see java.awt.CardLayout#getVgap()
* @since JDK1.1
*/
public int getHgap() {
return hgap;
}
/** {@collect.stats}
* Sets the horizontal gap between components.
* @param hgap the horizontal gap between components.
* @see java.awt.CardLayout#getHgap()
* @see java.awt.CardLayout#setVgap(int)
* @since JDK1.1
*/
public void setHgap(int hgap) {
this.hgap = hgap;
}
/** {@collect.stats}
* Gets the vertical gap between components.
* @return the vertical gap between components.
* @see java.awt.CardLayout#setVgap(int)
* @see java.awt.CardLayout#getHgap()
*/
public int getVgap() {
return vgap;
}
/** {@collect.stats}
* Sets the vertical gap between components.
* @param vgap the vertical gap between components.
* @see java.awt.CardLayout#getVgap()
* @see java.awt.CardLayout#setHgap(int)
* @since JDK1.1
*/
public void setVgap(int vgap) {
this.vgap = vgap;
}
/** {@collect.stats}
* Adds the specified component to this card layout's internal
* table of names. The object specified by <code>constraints</code>
* must be a string. The card layout stores this string as a key-value
* pair that can be used for random access to a particular card.
* By calling the <code>show</code> method, an application can
* display the component with the specified name.
* @param comp the component to be added.
* @param constraints a tag that identifies a particular
* card in the layout.
* @see java.awt.CardLayout#show(java.awt.Container, java.lang.String)
* @exception IllegalArgumentException if the constraint is not a string.
*/
public void addLayoutComponent(Component comp, Object constraints) {
synchronized (comp.getTreeLock()) {
if (constraints == null){
constraints = "";
}
if (constraints instanceof String) {
addLayoutComponent((String)constraints, comp);
} else {
throw new IllegalArgumentException("cannot add to layout: constraint must be a string");
}
}
}
/** {@collect.stats}
* @deprecated replaced by
* <code>addLayoutComponent(Component, Object)</code>.
*/
@Deprecated
public void addLayoutComponent(String name, Component comp) {
synchronized (comp.getTreeLock()) {
if (!vector.isEmpty()) {
comp.setVisible(false);
}
for (int i=0; i < vector.size(); i++) {
if (((Card)vector.get(i)).name.equals(name)) {
((Card)vector.get(i)).comp = comp;
return;
}
}
vector.add(new Card(name, comp));
}
}
/** {@collect.stats}
* Removes the specified component from the layout.
* If the card was visible on top, the next card underneath it is shown.
* @param comp the component to be removed.
* @see java.awt.Container#remove(java.awt.Component)
* @see java.awt.Container#removeAll()
*/
public void removeLayoutComponent(Component comp) {
synchronized (comp.getTreeLock()) {
for (int i = 0; i < vector.size(); i++) {
if (((Card)vector.get(i)).comp == comp) {
// if we remove current component we should show next one
if (comp.isVisible() && (comp.getParent() != null)) {
next(comp.getParent());
}
vector.remove(i);
// correct currentCard if this is necessary
if (currentCard > i) {
currentCard--;
}
break;
}
}
}
}
/** {@collect.stats}
* Determines the preferred size of the container argument using
* this card layout.
* @param parent the parent container in which to do the layout
* @return the preferred dimensions to lay out the subcomponents
* of the specified container
* @see java.awt.Container#getPreferredSize
* @see java.awt.CardLayout#minimumLayoutSize
*/
public Dimension preferredLayoutSize(Container parent) {
synchronized (parent.getTreeLock()) {
Insets insets = parent.getInsets();
int ncomponents = parent.getComponentCount();
int w = 0;
int h = 0;
for (int i = 0 ; i < ncomponents ; i++) {
Component comp = parent.getComponent(i);
Dimension d = comp.getPreferredSize();
if (d.width > w) {
w = d.width;
}
if (d.height > h) {
h = d.height;
}
}
return new Dimension(insets.left + insets.right + w + hgap*2,
insets.top + insets.bottom + h + vgap*2);
}
}
/** {@collect.stats}
* Calculates the minimum size for the specified panel.
* @param parent the parent container in which to do the layout
* @return the minimum dimensions required to lay out the
* subcomponents of the specified container
* @see java.awt.Container#doLayout
* @see java.awt.CardLayout#preferredLayoutSize
*/
public Dimension minimumLayoutSize(Container parent) {
synchronized (parent.getTreeLock()) {
Insets insets = parent.getInsets();
int ncomponents = parent.getComponentCount();
int w = 0;
int h = 0;
for (int i = 0 ; i < ncomponents ; i++) {
Component comp = parent.getComponent(i);
Dimension d = comp.getMinimumSize();
if (d.width > w) {
w = d.width;
}
if (d.height > h) {
h = d.height;
}
}
return new Dimension(insets.left + insets.right + w + hgap*2,
insets.top + insets.bottom + h + vgap*2);
}
}
/** {@collect.stats}
* Returns the maximum dimensions for this layout given the components
* in the specified target container.
* @param target the component which needs to be laid out
* @see Container
* @see #minimumLayoutSize
* @see #preferredLayoutSize
*/
public Dimension maximumLayoutSize(Container target) {
return new Dimension(Integer.MAX_VALUE, Integer.MAX_VALUE);
}
/** {@collect.stats}
* Returns the alignment along the x axis. This specifies how
* the component would like to be aligned relative to other
* components. The value should be a number between 0 and 1
* where 0 represents alignment along the origin, 1 is aligned
* the furthest away from the origin, 0.5 is centered, etc.
*/
public float getLayoutAlignmentX(Container parent) {
return 0.5f;
}
/** {@collect.stats}
* Returns the alignment along the y axis. This specifies how
* the component would like to be aligned relative to other
* components. The value should be a number between 0 and 1
* where 0 represents alignment along the origin, 1 is aligned
* the furthest away from the origin, 0.5 is centered, etc.
*/
public float getLayoutAlignmentY(Container parent) {
return 0.5f;
}
/** {@collect.stats}
* Invalidates the layout, indicating that if the layout manager
* has cached information it should be discarded.
*/
public void invalidateLayout(Container target) {
}
/** {@collect.stats}
* Lays out the specified container using this card layout.
* <p>
* Each component in the <code>parent</code> container is reshaped
* to be the size of the container, minus space for surrounding
* insets, horizontal gaps, and vertical gaps.
*
* @param parent the parent container in which to do the layout
* @see java.awt.Container#doLayout
*/
public void layoutContainer(Container parent) {
synchronized (parent.getTreeLock()) {
Insets insets = parent.getInsets();
int ncomponents = parent.getComponentCount();
Component comp = null;
boolean currentFound = false;
for (int i = 0 ; i < ncomponents ; i++) {
comp = parent.getComponent(i);
comp.setBounds(hgap + insets.left, vgap + insets.top,
parent.width - (hgap*2 + insets.left + insets.right),
parent.height - (vgap*2 + insets.top + insets.bottom));
if (comp.isVisible()) {
currentFound = true;
}
}
if (!currentFound && ncomponents > 0) {
parent.getComponent(0).setVisible(true);
}
}
}
/** {@collect.stats}
* Make sure that the Container really has a CardLayout installed.
* Otherwise havoc can ensue!
*/
void checkLayout(Container parent) {
if (parent.getLayout() != this) {
throw new IllegalArgumentException("wrong parent for CardLayout");
}
}
/** {@collect.stats}
* Flips to the first card of the container.
* @param parent the parent container in which to do the layout
* @see java.awt.CardLayout#last
*/
public void first(Container parent) {
synchronized (parent.getTreeLock()) {
checkLayout(parent);
int ncomponents = parent.getComponentCount();
for (int i = 0 ; i < ncomponents ; i++) {
Component comp = parent.getComponent(i);
if (comp.isVisible()) {
comp.setVisible(false);
break;
}
}
if (ncomponents > 0) {
currentCard = 0;
parent.getComponent(0).setVisible(true);
parent.validate();
}
}
}
/** {@collect.stats}
* Flips to the next card of the specified container. If the
* currently visible card is the last one, this method flips to the
* first card in the layout.
* @param parent the parent container in which to do the layout
* @see java.awt.CardLayout#previous
*/
public void next(Container parent) {
synchronized (parent.getTreeLock()) {
checkLayout(parent);
int ncomponents = parent.getComponentCount();
for (int i = 0 ; i < ncomponents ; i++) {
Component comp = parent.getComponent(i);
if (comp.isVisible()) {
comp.setVisible(false);
currentCard = (i + 1) % ncomponents;
comp = parent.getComponent(currentCard);
comp.setVisible(true);
parent.validate();
return;
}
}
showDefaultComponent(parent);
}
}
/** {@collect.stats}
* Flips to the previous card of the specified container. If the
* currently visible card is the first one, this method flips to the
* last card in the layout.
* @param parent the parent container in which to do the layout
* @see java.awt.CardLayout#next
*/
public void previous(Container parent) {
synchronized (parent.getTreeLock()) {
checkLayout(parent);
int ncomponents = parent.getComponentCount();
for (int i = 0 ; i < ncomponents ; i++) {
Component comp = parent.getComponent(i);
if (comp.isVisible()) {
comp.setVisible(false);
currentCard = ((i > 0) ? i-1 : ncomponents-1);
comp = parent.getComponent(currentCard);
comp.setVisible(true);
parent.validate();
return;
}
}
showDefaultComponent(parent);
}
}
void showDefaultComponent(Container parent) {
if (parent.getComponentCount() > 0) {
currentCard = 0;
parent.getComponent(0).setVisible(true);
parent.validate();
}
}
/** {@collect.stats}
* Flips to the last card of the container.
* @param parent the parent container in which to do the layout
* @see java.awt.CardLayout#first
*/
public void last(Container parent) {
synchronized (parent.getTreeLock()) {
checkLayout(parent);
int ncomponents = parent.getComponentCount();
for (int i = 0 ; i < ncomponents ; i++) {
Component comp = parent.getComponent(i);
if (comp.isVisible()) {
comp.setVisible(false);
break;
}
}
if (ncomponents > 0) {
currentCard = ncomponents - 1;
parent.getComponent(currentCard).setVisible(true);
parent.validate();
}
}
}
/** {@collect.stats}
* Flips to the component that was added to this layout with the
* specified <code>name</code>, using <code>addLayoutComponent</code>.
* If no such component exists, then nothing happens.
* @param parent the parent container in which to do the layout
* @param name the component name
* @see java.awt.CardLayout#addLayoutComponent(java.awt.Component, java.lang.Object)
*/
public void show(Container parent, String name) {
synchronized (parent.getTreeLock()) {
checkLayout(parent);
Component next = null;
int ncomponents = vector.size();
for (int i = 0; i < ncomponents; i++) {
Card card = (Card)vector.get(i);
if (card.name.equals(name)) {
next = card.comp;
currentCard = i;
break;
}
}
if ((next != null) && !next.isVisible()) {
ncomponents = parent.getComponentCount();
for (int i = 0; i < ncomponents; i++) {
Component comp = parent.getComponent(i);
if (comp.isVisible()) {
comp.setVisible(false);
break;
}
}
next.setVisible(true);
parent.validate();
}
}
}
/** {@collect.stats}
* Returns a string representation of the state of this card layout.
* @return a string representation of this card layout.
*/
public String toString() {
return getClass().getName() + "[hgap=" + hgap + ",vgap=" + vgap + "]";
}
/** {@collect.stats}
* Reads serializable fields from stream.
*/
private void readObject(ObjectInputStream s)
throws ClassNotFoundException, IOException
{
ObjectInputStream.GetField f = s.readFields();
hgap = f.get("hgap", 0);
vgap = f.get("vgap", 0);
if (f.defaulted("vector")) {
// pre-1.4 stream
Hashtable tab = (Hashtable)f.get("tab", null);
vector = new Vector();
if (tab != null && !tab.isEmpty()) {
for (Enumeration e = tab.keys() ; e.hasMoreElements() ; ) {
String key = (String)e.nextElement();
Component comp = (Component)tab.get(key);
vector.add(new Card(key, comp));
if (comp.isVisible()) {
currentCard = vector.size() - 1;
}
}
}
} else {
vector = (Vector)f.get("vector", null);
currentCard = f.get("currentCard", 0);
}
}
/** {@collect.stats}
* Writes serializable fields to stream.
*/
private void writeObject(ObjectOutputStream s)
throws IOException
{
Hashtable tab = new Hashtable();
int ncomponents = vector.size();
for (int i = 0; i < ncomponents; i++) {
Card card = (Card)vector.get(i);
tab.put(card.name, card.comp);
}
ObjectOutputStream.PutField f = s.putFields();
f.put("hgap", hgap);
f.put("vgap", vgap);
f.put("vector", vector);
f.put("currentCard", currentCard);
f.put("tab", tab);
s.writeFields();
}
}
|
Java
|
/*
* Copyright (c) 2005, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code 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
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package java.awt;
import java.awt.event.*;
import sun.awt.AppContext;
abstract class ModalEventFilter implements EventFilter {
protected Dialog modalDialog;
protected boolean disabled;
protected ModalEventFilter(Dialog modalDialog) {
this.modalDialog = modalDialog;
disabled = false;
}
Dialog getModalDialog() {
return modalDialog;
}
public FilterAction acceptEvent(AWTEvent event) {
if (disabled || !modalDialog.isVisible()) {
return FilterAction.ACCEPT;
}
int eventID = event.getID();
if ((eventID >= MouseEvent.MOUSE_FIRST &&
eventID <= MouseEvent.MOUSE_LAST) ||
(eventID >= ActionEvent.ACTION_FIRST &&
eventID <= ActionEvent.ACTION_LAST) ||
eventID == WindowEvent.WINDOW_CLOSING)
{
Object o = event.getSource();
if (o instanceof sun.awt.ModalExclude) {
// Exclude this object from modality and
// continue to pump it's events.
} else if (o instanceof Component) {
Component c = (Component)o;
while ((c != null) && !(c instanceof Window)) {
c = c.getParent_NoClientCode();
}
if (c != null) {
return acceptWindow((Window)c);
}
}
}
return FilterAction.ACCEPT;
}
protected abstract FilterAction acceptWindow(Window w);
// When a modal dialog is hidden its modal filter may not be deleted from
// EventDispatchThread event filters immediately, so we need to mark the filter
// as disabled to prevent it from working. Simple checking for visibility of
// the modalDialog is not enough, as it can be hidden and then shown again
// with a new event pump and a new filter
void disable() {
disabled = true;
}
int compareTo(ModalEventFilter another) {
Dialog anotherDialog = another.getModalDialog();
// check if modalDialog is from anotherDialog's hierarchy
// or vice versa
Component c = modalDialog;
while (c != null) {
if (c == anotherDialog) {
return 1;
}
c = c.getParent_NoClientCode();
}
c = anotherDialog;
while (c != null) {
if (c == modalDialog) {
return -1;
}
c = c.getParent_NoClientCode();
}
// check if one dialog blocks (directly or indirectly) another
Dialog blocker = modalDialog.getModalBlocker();
while (blocker != null) {
if (blocker == anotherDialog) {
return -1;
}
blocker = blocker.getModalBlocker();
}
blocker = anotherDialog.getModalBlocker();
while (blocker != null) {
if (blocker == modalDialog) {
return 1;
}
blocker = blocker.getModalBlocker();
}
// compare modality types
return modalDialog.getModalityType().compareTo(anotherDialog.getModalityType());
}
static ModalEventFilter createFilterForDialog(Dialog modalDialog) {
switch (modalDialog.getModalityType()) {
case DOCUMENT_MODAL: return new DocumentModalEventFilter(modalDialog);
case APPLICATION_MODAL: return new ApplicationModalEventFilter(modalDialog);
case TOOLKIT_MODAL: return new ToolkitModalEventFilter(modalDialog);
}
return null;
}
private static class ToolkitModalEventFilter extends ModalEventFilter {
private AppContext appContext;
ToolkitModalEventFilter(Dialog modalDialog) {
super(modalDialog);
appContext = modalDialog.appContext;
}
protected FilterAction acceptWindow(Window w) {
if (w.isModalExcluded(Dialog.ModalExclusionType.TOOLKIT_EXCLUDE)) {
return FilterAction.ACCEPT;
}
if (w.appContext != appContext) {
return FilterAction.REJECT;
}
while (w != null) {
if (w == modalDialog) {
return FilterAction.ACCEPT_IMMEDIATELY;
}
w = w.getOwner();
}
return FilterAction.REJECT;
}
}
private static class ApplicationModalEventFilter extends ModalEventFilter {
private AppContext appContext;
ApplicationModalEventFilter(Dialog modalDialog) {
super(modalDialog);
appContext = modalDialog.appContext;
}
protected FilterAction acceptWindow(Window w) {
if (w.isModalExcluded(Dialog.ModalExclusionType.APPLICATION_EXCLUDE)) {
return FilterAction.ACCEPT;
}
if (w.appContext == appContext) {
while (w != null) {
if (w == modalDialog) {
return FilterAction.ACCEPT_IMMEDIATELY;
}
w = w.getOwner();
}
return FilterAction.REJECT;
}
return FilterAction.ACCEPT;
}
}
private static class DocumentModalEventFilter extends ModalEventFilter {
private Window documentRoot;
DocumentModalEventFilter(Dialog modalDialog) {
super(modalDialog);
documentRoot = modalDialog.getDocumentRoot();
}
protected FilterAction acceptWindow(Window w) {
// application- and toolkit-excluded windows are blocked by
// document-modal dialogs from their child hierarchy
if (w.isModalExcluded(Dialog.ModalExclusionType.APPLICATION_EXCLUDE)) {
Window w1 = modalDialog.getOwner();
while (w1 != null) {
if (w1 == w) {
return FilterAction.REJECT;
}
w1 = w1.getOwner();
}
return FilterAction.ACCEPT;
}
while (w != null) {
if (w == modalDialog) {
return FilterAction.ACCEPT_IMMEDIATELY;
}
if (w == documentRoot) {
return FilterAction.REJECT;
}
w = w.getOwner();
}
return FilterAction.ACCEPT;
}
}
}
|
Java
|
/*
* Copyright (c) 1996, 2006, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code 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
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package java.awt;
import java.awt.event.*;
import java.lang.reflect.Array;
import java.util.EventListener;
import java.io.Serializable;
import java.io.ObjectOutputStream;
import java.io.IOException;
import java.util.EventListener;
/** {@collect.stats}
* {@code AWTEventMulticaster} implements efficient and thread-safe multi-cast
* event dispatching for the AWT events defined in the {@code java.awt.event}
* package.
* <p>
* The following example illustrates how to use this class:
*
* <pre><code>
* public myComponent extends Component {
* ActionListener actionListener = null;
*
* public synchronized void addActionListener(ActionListener l) {
* actionListener = AWTEventMulticaster.add(actionListener, l);
* }
* public synchronized void removeActionListener(ActionListener l) {
* actionListener = AWTEventMulticaster.remove(actionListener, l);
* }
* public void processEvent(AWTEvent e) {
* // when event occurs which causes "action" semantic
* ActionListener listener = actionListener;
* if (listener != null) {
* listener.actionPerformed(new ActionEvent());
* }
* }
* }
* </code></pre>
* The important point to note is the first argument to the {@code
* add} and {@code remove} methods is the field maintaining the
* listeners. In addition you must assign the result of the {@code add}
* and {@code remove} methods to the field maintaining the listeners.
* <p>
* {@code AWTEventMulticaster} is implemented as a pair of {@code
* EventListeners} that are set at construction time. {@code
* AWTEventMulticaster} is immutable. The {@code add} and {@code
* remove} methods do not alter {@code AWTEventMulticaster} in
* anyway. If necessary, a new {@code AWTEventMulticaster} is
* created. In this way it is safe to add and remove listeners during
* the process of an event dispatching. However, event listeners
* added during the process of an event dispatch operation are not
* notified of the event currently being dispatched.
* <p>
* All of the {@code add} methods allow {@code null} arguments. If the
* first argument is {@code null}, the second argument is returned. If
* the first argument is not {@code null} and the second argument is
* {@code null}, the first argument is returned. If both arguments are
* {@code non-null}, a new {@code AWTEventMulticaster} is created using
* the two arguments and returned.
* <p>
* For the {@code remove} methods that take two arguments, the following is
* returned:
* <ul>
* <li>{@code null}, if the first argument is {@code null}, or
* the arguments are equal, by way of {@code ==}.
* <li>the first argument, if the first argument is not an instance of
* {@code AWTEventMulticaster}.
* <li>result of invoking {@code remove(EventListener)} on the
* first argument, supplying the second argument to the
* {@code remove(EventListener)} method.
* </ul>
* <p>Swing makes use of
* {@link javax.swing.event.EventListenerList EventListenerList} for
* similar logic. Refer to it for details.
*
* @see javax.swing.event.EventListenerList
*
* @author John Rose
* @author Amy Fowler
* @since 1.1
*/
public class AWTEventMulticaster implements
ComponentListener, ContainerListener, FocusListener, KeyListener,
MouseListener, MouseMotionListener, WindowListener, WindowFocusListener,
WindowStateListener, ActionListener, ItemListener, AdjustmentListener,
TextListener, InputMethodListener, HierarchyListener,
HierarchyBoundsListener, MouseWheelListener {
protected final EventListener a, b;
/** {@collect.stats}
* Creates an event multicaster instance which chains listener-a
* with listener-b. Input parameters <code>a</code> and <code>b</code>
* should not be <code>null</code>, though implementations may vary in
* choosing whether or not to throw <code>NullPointerException</code>
* in that case.
* @param a listener-a
* @param b listener-b
*/
protected AWTEventMulticaster(EventListener a, EventListener b) {
this.a = a; this.b = b;
}
/** {@collect.stats}
* Removes a listener from this multicaster.
* <p>
* The returned multicaster contains all the listeners in this
* multicaster with the exception of all occurrences of {@code oldl}.
* If the resulting multicaster contains only one regular listener
* the regular listener may be returned. If the resulting multicaster
* is empty, then {@code null} may be returned instead.
* <p>
* No exception is thrown if {@code oldl} is {@code null}.
*
* @param oldl the listener to be removed
* @return resulting listener
*/
protected EventListener remove(EventListener oldl) {
if (oldl == a) return b;
if (oldl == b) return a;
EventListener a2 = removeInternal(a, oldl);
EventListener b2 = removeInternal(b, oldl);
if (a2 == a && b2 == b) {
return this; // it's not here
}
return addInternal(a2, b2);
}
/** {@collect.stats}
* Handles the componentResized event by invoking the
* componentResized methods on listener-a and listener-b.
* @param e the component event
*/
public void componentResized(ComponentEvent e) {
((ComponentListener)a).componentResized(e);
((ComponentListener)b).componentResized(e);
}
/** {@collect.stats}
* Handles the componentMoved event by invoking the
* componentMoved methods on listener-a and listener-b.
* @param e the component event
*/
public void componentMoved(ComponentEvent e) {
((ComponentListener)a).componentMoved(e);
((ComponentListener)b).componentMoved(e);
}
/** {@collect.stats}
* Handles the componentShown event by invoking the
* componentShown methods on listener-a and listener-b.
* @param e the component event
*/
public void componentShown(ComponentEvent e) {
((ComponentListener)a).componentShown(e);
((ComponentListener)b).componentShown(e);
}
/** {@collect.stats}
* Handles the componentHidden event by invoking the
* componentHidden methods on listener-a and listener-b.
* @param e the component event
*/
public void componentHidden(ComponentEvent e) {
((ComponentListener)a).componentHidden(e);
((ComponentListener)b).componentHidden(e);
}
/** {@collect.stats}
* Handles the componentAdded container event by invoking the
* componentAdded methods on listener-a and listener-b.
* @param e the component event
*/
public void componentAdded(ContainerEvent e) {
((ContainerListener)a).componentAdded(e);
((ContainerListener)b).componentAdded(e);
}
/** {@collect.stats}
* Handles the componentRemoved container event by invoking the
* componentRemoved methods on listener-a and listener-b.
* @param e the component event
*/
public void componentRemoved(ContainerEvent e) {
((ContainerListener)a).componentRemoved(e);
((ContainerListener)b).componentRemoved(e);
}
/** {@collect.stats}
* Handles the focusGained event by invoking the
* focusGained methods on listener-a and listener-b.
* @param e the focus event
*/
public void focusGained(FocusEvent e) {
((FocusListener)a).focusGained(e);
((FocusListener)b).focusGained(e);
}
/** {@collect.stats}
* Handles the focusLost event by invoking the
* focusLost methods on listener-a and listener-b.
* @param e the focus event
*/
public void focusLost(FocusEvent e) {
((FocusListener)a).focusLost(e);
((FocusListener)b).focusLost(e);
}
/** {@collect.stats}
* Handles the keyTyped event by invoking the
* keyTyped methods on listener-a and listener-b.
* @param e the key event
*/
public void keyTyped(KeyEvent e) {
((KeyListener)a).keyTyped(e);
((KeyListener)b).keyTyped(e);
}
/** {@collect.stats}
* Handles the keyPressed event by invoking the
* keyPressed methods on listener-a and listener-b.
* @param e the key event
*/
public void keyPressed(KeyEvent e) {
((KeyListener)a).keyPressed(e);
((KeyListener)b).keyPressed(e);
}
/** {@collect.stats}
* Handles the keyReleased event by invoking the
* keyReleased methods on listener-a and listener-b.
* @param e the key event
*/
public void keyReleased(KeyEvent e) {
((KeyListener)a).keyReleased(e);
((KeyListener)b).keyReleased(e);
}
/** {@collect.stats}
* Handles the mouseClicked event by invoking the
* mouseClicked methods on listener-a and listener-b.
* @param e the mouse event
*/
public void mouseClicked(MouseEvent e) {
((MouseListener)a).mouseClicked(e);
((MouseListener)b).mouseClicked(e);
}
/** {@collect.stats}
* Handles the mousePressed event by invoking the
* mousePressed methods on listener-a and listener-b.
* @param e the mouse event
*/
public void mousePressed(MouseEvent e) {
((MouseListener)a).mousePressed(e);
((MouseListener)b).mousePressed(e);
}
/** {@collect.stats}
* Handles the mouseReleased event by invoking the
* mouseReleased methods on listener-a and listener-b.
* @param e the mouse event
*/
public void mouseReleased(MouseEvent e) {
((MouseListener)a).mouseReleased(e);
((MouseListener)b).mouseReleased(e);
}
/** {@collect.stats}
* Handles the mouseEntered event by invoking the
* mouseEntered methods on listener-a and listener-b.
* @param e the mouse event
*/
public void mouseEntered(MouseEvent e) {
((MouseListener)a).mouseEntered(e);
((MouseListener)b).mouseEntered(e);
}
/** {@collect.stats}
* Handles the mouseExited event by invoking the
* mouseExited methods on listener-a and listener-b.
* @param e the mouse event
*/
public void mouseExited(MouseEvent e) {
((MouseListener)a).mouseExited(e);
((MouseListener)b).mouseExited(e);
}
/** {@collect.stats}
* Handles the mouseDragged event by invoking the
* mouseDragged methods on listener-a and listener-b.
* @param e the mouse event
*/
public void mouseDragged(MouseEvent e) {
((MouseMotionListener)a).mouseDragged(e);
((MouseMotionListener)b).mouseDragged(e);
}
/** {@collect.stats}
* Handles the mouseMoved event by invoking the
* mouseMoved methods on listener-a and listener-b.
* @param e the mouse event
*/
public void mouseMoved(MouseEvent e) {
((MouseMotionListener)a).mouseMoved(e);
((MouseMotionListener)b).mouseMoved(e);
}
/** {@collect.stats}
* Handles the windowOpened event by invoking the
* windowOpened methods on listener-a and listener-b.
* @param e the window event
*/
public void windowOpened(WindowEvent e) {
((WindowListener)a).windowOpened(e);
((WindowListener)b).windowOpened(e);
}
/** {@collect.stats}
* Handles the windowClosing event by invoking the
* windowClosing methods on listener-a and listener-b.
* @param e the window event
*/
public void windowClosing(WindowEvent e) {
((WindowListener)a).windowClosing(e);
((WindowListener)b).windowClosing(e);
}
/** {@collect.stats}
* Handles the windowClosed event by invoking the
* windowClosed methods on listener-a and listener-b.
* @param e the window event
*/
public void windowClosed(WindowEvent e) {
((WindowListener)a).windowClosed(e);
((WindowListener)b).windowClosed(e);
}
/** {@collect.stats}
* Handles the windowIconified event by invoking the
* windowIconified methods on listener-a and listener-b.
* @param e the window event
*/
public void windowIconified(WindowEvent e) {
((WindowListener)a).windowIconified(e);
((WindowListener)b).windowIconified(e);
}
/** {@collect.stats}
* Handles the windowDeiconfied event by invoking the
* windowDeiconified methods on listener-a and listener-b.
* @param e the window event
*/
public void windowDeiconified(WindowEvent e) {
((WindowListener)a).windowDeiconified(e);
((WindowListener)b).windowDeiconified(e);
}
/** {@collect.stats}
* Handles the windowActivated event by invoking the
* windowActivated methods on listener-a and listener-b.
* @param e the window event
*/
public void windowActivated(WindowEvent e) {
((WindowListener)a).windowActivated(e);
((WindowListener)b).windowActivated(e);
}
/** {@collect.stats}
* Handles the windowDeactivated event by invoking the
* windowDeactivated methods on listener-a and listener-b.
* @param e the window event
*/
public void windowDeactivated(WindowEvent e) {
((WindowListener)a).windowDeactivated(e);
((WindowListener)b).windowDeactivated(e);
}
/** {@collect.stats}
* Handles the windowStateChanged event by invoking the
* windowStateChanged methods on listener-a and listener-b.
* @param e the window event
* @since 1.4
*/
public void windowStateChanged(WindowEvent e) {
((WindowStateListener)a).windowStateChanged(e);
((WindowStateListener)b).windowStateChanged(e);
}
/** {@collect.stats}
* Handles the windowGainedFocus event by invoking the windowGainedFocus
* methods on listener-a and listener-b.
* @param e the window event
* @since 1.4
*/
public void windowGainedFocus(WindowEvent e) {
((WindowFocusListener)a).windowGainedFocus(e);
((WindowFocusListener)b).windowGainedFocus(e);
}
/** {@collect.stats}
* Handles the windowLostFocus event by invoking the windowLostFocus
* methods on listener-a and listener-b.
* @param e the window event
* @since 1.4
*/
public void windowLostFocus(WindowEvent e) {
((WindowFocusListener)a).windowLostFocus(e);
((WindowFocusListener)b).windowLostFocus(e);
}
/** {@collect.stats}
* Handles the actionPerformed event by invoking the
* actionPerformed methods on listener-a and listener-b.
* @param e the action event
*/
public void actionPerformed(ActionEvent e) {
((ActionListener)a).actionPerformed(e);
((ActionListener)b).actionPerformed(e);
}
/** {@collect.stats}
* Handles the itemStateChanged event by invoking the
* itemStateChanged methods on listener-a and listener-b.
* @param e the item event
*/
public void itemStateChanged(ItemEvent e) {
((ItemListener)a).itemStateChanged(e);
((ItemListener)b).itemStateChanged(e);
}
/** {@collect.stats}
* Handles the adjustmentValueChanged event by invoking the
* adjustmentValueChanged methods on listener-a and listener-b.
* @param e the adjustment event
*/
public void adjustmentValueChanged(AdjustmentEvent e) {
((AdjustmentListener)a).adjustmentValueChanged(e);
((AdjustmentListener)b).adjustmentValueChanged(e);
}
public void textValueChanged(TextEvent e) {
((TextListener)a).textValueChanged(e);
((TextListener)b).textValueChanged(e);
}
/** {@collect.stats}
* Handles the inputMethodTextChanged event by invoking the
* inputMethodTextChanged methods on listener-a and listener-b.
* @param e the item event
*/
public void inputMethodTextChanged(InputMethodEvent e) {
((InputMethodListener)a).inputMethodTextChanged(e);
((InputMethodListener)b).inputMethodTextChanged(e);
}
/** {@collect.stats}
* Handles the caretPositionChanged event by invoking the
* caretPositionChanged methods on listener-a and listener-b.
* @param e the item event
*/
public void caretPositionChanged(InputMethodEvent e) {
((InputMethodListener)a).caretPositionChanged(e);
((InputMethodListener)b).caretPositionChanged(e);
}
/** {@collect.stats}
* Handles the hierarchyChanged event by invoking the
* hierarchyChanged methods on listener-a and listener-b.
* @param e the item event
* @since 1.3
*/
public void hierarchyChanged(HierarchyEvent e) {
((HierarchyListener)a).hierarchyChanged(e);
((HierarchyListener)b).hierarchyChanged(e);
}
/** {@collect.stats}
* Handles the ancestorMoved event by invoking the
* ancestorMoved methods on listener-a and listener-b.
* @param e the item event
* @since 1.3
*/
public void ancestorMoved(HierarchyEvent e) {
((HierarchyBoundsListener)a).ancestorMoved(e);
((HierarchyBoundsListener)b).ancestorMoved(e);
}
/** {@collect.stats}
* Handles the ancestorResized event by invoking the
* ancestorResized methods on listener-a and listener-b.
* @param e the item event
* @since 1.3
*/
public void ancestorResized(HierarchyEvent e) {
((HierarchyBoundsListener)a).ancestorResized(e);
((HierarchyBoundsListener)b).ancestorResized(e);
}
/** {@collect.stats}
* Handles the mouseWheelMoved event by invoking the
* mouseWheelMoved methods on listener-a and listener-b.
* @param e the mouse event
* @since 1.4
*/
public void mouseWheelMoved(MouseWheelEvent e) {
((MouseWheelListener)a).mouseWheelMoved(e);
((MouseWheelListener)b).mouseWheelMoved(e);
}
/** {@collect.stats}
* Adds component-listener-a with component-listener-b and
* returns the resulting multicast listener.
* @param a component-listener-a
* @param b component-listener-b
*/
public static ComponentListener add(ComponentListener a, ComponentListener b) {
return (ComponentListener)addInternal(a, b);
}
/** {@collect.stats}
* Adds container-listener-a with container-listener-b and
* returns the resulting multicast listener.
* @param a container-listener-a
* @param b container-listener-b
*/
public static ContainerListener add(ContainerListener a, ContainerListener b) {
return (ContainerListener)addInternal(a, b);
}
/** {@collect.stats}
* Adds focus-listener-a with focus-listener-b and
* returns the resulting multicast listener.
* @param a focus-listener-a
* @param b focus-listener-b
*/
public static FocusListener add(FocusListener a, FocusListener b) {
return (FocusListener)addInternal(a, b);
}
/** {@collect.stats}
* Adds key-listener-a with key-listener-b and
* returns the resulting multicast listener.
* @param a key-listener-a
* @param b key-listener-b
*/
public static KeyListener add(KeyListener a, KeyListener b) {
return (KeyListener)addInternal(a, b);
}
/** {@collect.stats}
* Adds mouse-listener-a with mouse-listener-b and
* returns the resulting multicast listener.
* @param a mouse-listener-a
* @param b mouse-listener-b
*/
public static MouseListener add(MouseListener a, MouseListener b) {
return (MouseListener)addInternal(a, b);
}
/** {@collect.stats}
* Adds mouse-motion-listener-a with mouse-motion-listener-b and
* returns the resulting multicast listener.
* @param a mouse-motion-listener-a
* @param b mouse-motion-listener-b
*/
public static MouseMotionListener add(MouseMotionListener a, MouseMotionListener b) {
return (MouseMotionListener)addInternal(a, b);
}
/** {@collect.stats}
* Adds window-listener-a with window-listener-b and
* returns the resulting multicast listener.
* @param a window-listener-a
* @param b window-listener-b
*/
public static WindowListener add(WindowListener a, WindowListener b) {
return (WindowListener)addInternal(a, b);
}
/** {@collect.stats}
* Adds window-state-listener-a with window-state-listener-b
* and returns the resulting multicast listener.
* @param a window-state-listener-a
* @param b window-state-listener-b
* @since 1.4
*/
public static WindowStateListener add(WindowStateListener a,
WindowStateListener b) {
return (WindowStateListener)addInternal(a, b);
}
/** {@collect.stats}
* Adds window-focus-listener-a with window-focus-listener-b
* and returns the resulting multicast listener.
* @param a window-focus-listener-a
* @param b window-focus-listener-b
* @since 1.4
*/
public static WindowFocusListener add(WindowFocusListener a,
WindowFocusListener b) {
return (WindowFocusListener)addInternal(a, b);
}
/** {@collect.stats}
* Adds action-listener-a with action-listener-b and
* returns the resulting multicast listener.
* @param a action-listener-a
* @param b action-listener-b
*/
public static ActionListener add(ActionListener a, ActionListener b) {
return (ActionListener)addInternal(a, b);
}
/** {@collect.stats}
* Adds item-listener-a with item-listener-b and
* returns the resulting multicast listener.
* @param a item-listener-a
* @param b item-listener-b
*/
public static ItemListener add(ItemListener a, ItemListener b) {
return (ItemListener)addInternal(a, b);
}
/** {@collect.stats}
* Adds adjustment-listener-a with adjustment-listener-b and
* returns the resulting multicast listener.
* @param a adjustment-listener-a
* @param b adjustment-listener-b
*/
public static AdjustmentListener add(AdjustmentListener a, AdjustmentListener b) {
return (AdjustmentListener)addInternal(a, b);
}
public static TextListener add(TextListener a, TextListener b) {
return (TextListener)addInternal(a, b);
}
/** {@collect.stats}
* Adds input-method-listener-a with input-method-listener-b and
* returns the resulting multicast listener.
* @param a input-method-listener-a
* @param b input-method-listener-b
*/
public static InputMethodListener add(InputMethodListener a, InputMethodListener b) {
return (InputMethodListener)addInternal(a, b);
}
/** {@collect.stats}
* Adds hierarchy-listener-a with hierarchy-listener-b and
* returns the resulting multicast listener.
* @param a hierarchy-listener-a
* @param b hierarchy-listener-b
* @since 1.3
*/
public static HierarchyListener add(HierarchyListener a, HierarchyListener b) {
return (HierarchyListener)addInternal(a, b);
}
/** {@collect.stats}
* Adds hierarchy-bounds-listener-a with hierarchy-bounds-listener-b and
* returns the resulting multicast listener.
* @param a hierarchy-bounds-listener-a
* @param b hierarchy-bounds-listener-b
* @since 1.3
*/
public static HierarchyBoundsListener add(HierarchyBoundsListener a, HierarchyBoundsListener b) {
return (HierarchyBoundsListener)addInternal(a, b);
}
/** {@collect.stats}
* Adds mouse-wheel-listener-a with mouse-wheel-listener-b and
* returns the resulting multicast listener.
* @param a mouse-wheel-listener-a
* @param b mouse-wheel-listener-b
* @since 1.4
*/
public static MouseWheelListener add(MouseWheelListener a,
MouseWheelListener b) {
return (MouseWheelListener)addInternal(a, b);
}
/** {@collect.stats}
* Removes the old component-listener from component-listener-l and
* returns the resulting multicast listener.
* @param l component-listener-l
* @param oldl the component-listener being removed
*/
public static ComponentListener remove(ComponentListener l, ComponentListener oldl) {
return (ComponentListener) removeInternal(l, oldl);
}
/** {@collect.stats}
* Removes the old container-listener from container-listener-l and
* returns the resulting multicast listener.
* @param l container-listener-l
* @param oldl the container-listener being removed
*/
public static ContainerListener remove(ContainerListener l, ContainerListener oldl) {
return (ContainerListener) removeInternal(l, oldl);
}
/** {@collect.stats}
* Removes the old focus-listener from focus-listener-l and
* returns the resulting multicast listener.
* @param l focus-listener-l
* @param oldl the focus-listener being removed
*/
public static FocusListener remove(FocusListener l, FocusListener oldl) {
return (FocusListener) removeInternal(l, oldl);
}
/** {@collect.stats}
* Removes the old key-listener from key-listener-l and
* returns the resulting multicast listener.
* @param l key-listener-l
* @param oldl the key-listener being removed
*/
public static KeyListener remove(KeyListener l, KeyListener oldl) {
return (KeyListener) removeInternal(l, oldl);
}
/** {@collect.stats}
* Removes the old mouse-listener from mouse-listener-l and
* returns the resulting multicast listener.
* @param l mouse-listener-l
* @param oldl the mouse-listener being removed
*/
public static MouseListener remove(MouseListener l, MouseListener oldl) {
return (MouseListener) removeInternal(l, oldl);
}
/** {@collect.stats}
* Removes the old mouse-motion-listener from mouse-motion-listener-l
* and returns the resulting multicast listener.
* @param l mouse-motion-listener-l
* @param oldl the mouse-motion-listener being removed
*/
public static MouseMotionListener remove(MouseMotionListener l, MouseMotionListener oldl) {
return (MouseMotionListener) removeInternal(l, oldl);
}
/** {@collect.stats}
* Removes the old window-listener from window-listener-l and
* returns the resulting multicast listener.
* @param l window-listener-l
* @param oldl the window-listener being removed
*/
public static WindowListener remove(WindowListener l, WindowListener oldl) {
return (WindowListener) removeInternal(l, oldl);
}
/** {@collect.stats}
* Removes the old window-state-listener from window-state-listener-l
* and returns the resulting multicast listener.
* @param l window-state-listener-l
* @param oldl the window-state-listener being removed
* @since 1.4
*/
public static WindowStateListener remove(WindowStateListener l,
WindowStateListener oldl) {
return (WindowStateListener) removeInternal(l, oldl);
}
/** {@collect.stats}
* Removes the old window-focus-listener from window-focus-listener-l
* and returns the resulting multicast listener.
* @param l window-focus-listener-l
* @param oldl the window-focus-listener being removed
* @since 1.4
*/
public static WindowFocusListener remove(WindowFocusListener l,
WindowFocusListener oldl) {
return (WindowFocusListener) removeInternal(l, oldl);
}
/** {@collect.stats}
* Removes the old action-listener from action-listener-l and
* returns the resulting multicast listener.
* @param l action-listener-l
* @param oldl the action-listener being removed
*/
public static ActionListener remove(ActionListener l, ActionListener oldl) {
return (ActionListener) removeInternal(l, oldl);
}
/** {@collect.stats}
* Removes the old item-listener from item-listener-l and
* returns the resulting multicast listener.
* @param l item-listener-l
* @param oldl the item-listener being removed
*/
public static ItemListener remove(ItemListener l, ItemListener oldl) {
return (ItemListener) removeInternal(l, oldl);
}
/** {@collect.stats}
* Removes the old adjustment-listener from adjustment-listener-l and
* returns the resulting multicast listener.
* @param l adjustment-listener-l
* @param oldl the adjustment-listener being removed
*/
public static AdjustmentListener remove(AdjustmentListener l, AdjustmentListener oldl) {
return (AdjustmentListener) removeInternal(l, oldl);
}
public static TextListener remove(TextListener l, TextListener oldl) {
return (TextListener) removeInternal(l, oldl);
}
/** {@collect.stats}
* Removes the old input-method-listener from input-method-listener-l and
* returns the resulting multicast listener.
* @param l input-method-listener-l
* @param oldl the input-method-listener being removed
*/
public static InputMethodListener remove(InputMethodListener l, InputMethodListener oldl) {
return (InputMethodListener) removeInternal(l, oldl);
}
/** {@collect.stats}
* Removes the old hierarchy-listener from hierarchy-listener-l and
* returns the resulting multicast listener.
* @param l hierarchy-listener-l
* @param oldl the hierarchy-listener being removed
* @since 1.3
*/
public static HierarchyListener remove(HierarchyListener l, HierarchyListener oldl) {
return (HierarchyListener) removeInternal(l, oldl);
}
/** {@collect.stats}
* Removes the old hierarchy-bounds-listener from
* hierarchy-bounds-listener-l and returns the resulting multicast
* listener.
* @param l hierarchy-bounds-listener-l
* @param oldl the hierarchy-bounds-listener being removed
* @since 1.3
*/
public static HierarchyBoundsListener remove(HierarchyBoundsListener l, HierarchyBoundsListener oldl) {
return (HierarchyBoundsListener) removeInternal(l, oldl);
}
/** {@collect.stats}
* Removes the old mouse-wheel-listener from mouse-wheel-listener-l
* and returns the resulting multicast listener.
* @param l mouse-wheel-listener-l
* @param oldl the mouse-wheel-listener being removed
* @since 1.4
*/
public static MouseWheelListener remove(MouseWheelListener l,
MouseWheelListener oldl) {
return (MouseWheelListener) removeInternal(l, oldl);
}
/** {@collect.stats}
* Returns the resulting multicast listener from adding listener-a
* and listener-b together.
* If listener-a is null, it returns listener-b;
* If listener-b is null, it returns listener-a
* If neither are null, then it creates and returns
* a new AWTEventMulticaster instance which chains a with b.
* @param a event listener-a
* @param b event listener-b
*/
protected static EventListener addInternal(EventListener a, EventListener b) {
if (a == null) return b;
if (b == null) return a;
return new AWTEventMulticaster(a, b);
}
/** {@collect.stats}
* Returns the resulting multicast listener after removing the
* old listener from listener-l.
* If listener-l equals the old listener OR listener-l is null,
* returns null.
* Else if listener-l is an instance of AWTEventMulticaster,
* then it removes the old listener from it.
* Else, returns listener l.
* @param l the listener being removed from
* @param oldl the listener being removed
*/
protected static EventListener removeInternal(EventListener l, EventListener oldl) {
if (l == oldl || l == null) {
return null;
} else if (l instanceof AWTEventMulticaster) {
return ((AWTEventMulticaster)l).remove(oldl);
} else {
return l; // it's not here
}
}
/* Serialization support.
*/
protected void saveInternal(ObjectOutputStream s, String k) throws IOException {
if (a instanceof AWTEventMulticaster) {
((AWTEventMulticaster)a).saveInternal(s, k);
}
else if (a instanceof Serializable) {
s.writeObject(k);
s.writeObject(a);
}
if (b instanceof AWTEventMulticaster) {
((AWTEventMulticaster)b).saveInternal(s, k);
}
else if (b instanceof Serializable) {
s.writeObject(k);
s.writeObject(b);
}
}
protected static void save(ObjectOutputStream s, String k, EventListener l) throws IOException {
if (l == null) {
return;
}
else if (l instanceof AWTEventMulticaster) {
((AWTEventMulticaster)l).saveInternal(s, k);
}
else if (l instanceof Serializable) {
s.writeObject(k);
s.writeObject(l);
}
}
/*
* Recursive method which returns a count of the number of listeners in
* EventListener, handling the (common) case of l actually being an
* AWTEventMulticaster. Additionally, only listeners of type listenerType
* are counted. Method modified to fix bug 4513402. -bchristi
*/
private static int getListenerCount(EventListener l, Class listenerType) {
if (l instanceof AWTEventMulticaster) {
AWTEventMulticaster mc = (AWTEventMulticaster)l;
return getListenerCount(mc.a, listenerType) +
getListenerCount(mc.b, listenerType);
}
else {
// Only count listeners of correct type
return listenerType.isInstance(l) ? 1 : 0;
}
}
/*
* Recusive method which populates EventListener array a with EventListeners
* from l. l is usually an AWTEventMulticaster. Bug 4513402 revealed that
* if l differed in type from the element type of a, an ArrayStoreException
* would occur. Now l is only inserted into a if it's of the appropriate
* type. -bchristi
*/
private static int populateListenerArray(EventListener[] a, EventListener l, int index) {
if (l instanceof AWTEventMulticaster) {
AWTEventMulticaster mc = (AWTEventMulticaster)l;
int lhs = populateListenerArray(a, mc.a, index);
return populateListenerArray(a, mc.b, lhs);
}
else if (a.getClass().getComponentType().isInstance(l)) {
a[index] = l;
return index + 1;
}
// Skip nulls, instances of wrong class
else {
return index;
}
}
/** {@collect.stats}
* Returns an array of all the objects chained as
* <code><em>Foo</em>Listener</code>s by the specified
* <code>java.util.EventListener</code>.
* <code><em>Foo</em>Listener</code>s are chained by the
* <code>AWTEventMulticaster</code> using the
* <code>add<em>Foo</em>Listener</code> method.
* If a <code>null</code> listener is specified, this method returns an
* empty array. If the specified listener is not an instance of
* <code>AWTEventMulticaster</code>, this method returns an array which
* contains only the specified listener. If no such listeners are chanined,
* this method returns an empty array.
*
* @param l the specified <code>java.util.EventListener</code>
* @param listenerType the type of listeners requested; this parameter
* should specify an interface that descends from
* <code>java.util.EventListener</code>
* @return an array of all objects chained as
* <code><em>Foo</em>Listener</code>s by the specified multicast
* listener, or an empty array if no such listeners have been
* chained by the specified multicast listener
* @exception NullPointerException if the specified
* {@code listenertype} parameter is {@code null}
* @exception ClassCastException if <code>listenerType</code>
* doesn't specify a class or interface that implements
* <code>java.util.EventListener</code>
*
* @since 1.4
*/
public static <T extends EventListener> T[]
getListeners(EventListener l, Class<T> listenerType)
{
if (listenerType == null) {
throw new NullPointerException ("Listener type should not be null");
}
int n = getListenerCount(l, listenerType);
T[] result = (T[])Array.newInstance(listenerType, n);
populateListenerArray(result, l, 0);
return result;
}
}
|
Java
|
/*
* Copyright (c) 1995, 2006, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code 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
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package java.awt;
import java.awt.peer.ScrollbarPeer;
import java.awt.event.*;
import java.util.EventListener;
import java.io.ObjectOutputStream;
import java.io.ObjectInputStream;
import java.io.IOException;
import javax.accessibility.*;
/** {@collect.stats}
* The <code>Scrollbar</code> class embodies a scroll bar, a
* familiar user-interface object. A scroll bar provides a
* convenient means for allowing a user to select from a
* range of values. The following three vertical
* scroll bars could be used as slider controls to pick
* the red, green, and blue components of a color:
* <p>
* <img src="doc-files/Scrollbar-1.gif" alt="Image shows 3 vertical sliders, side-by-side."
* ALIGN=center HSPACE=10 VSPACE=7>
* <p>
* Each scroll bar in this example could be created with
* code similar to the following:
* <p>
* <hr><blockquote><pre>
* redSlider=new Scrollbar(Scrollbar.VERTICAL, 0, 1, 0, 255);
* add(redSlider);
* </pre></blockquote><hr>
* <p>
* Alternatively, a scroll bar can represent a range of values. For
* example, if a scroll bar is used for scrolling through text, the
* width of the "bubble" (also called the "thumb" or "scroll box")
* can be used to represent the amount of text that is visible.
* Here is an example of a scroll bar that represents a range:
* <p>
* <img src="doc-files/Scrollbar-2.gif"
* alt="Image shows horizontal slider with starting range of 0 and ending range of 300. The slider thumb is labeled 60."
* ALIGN=center HSPACE=10 VSPACE=7>
* <p>
* The value range represented by the bubble in this example
* is the <em>visible amount</em>. The horizontal scroll bar
* in this example could be created with code like the following:
* <p>
* <hr><blockquote><pre>
* ranger = new Scrollbar(Scrollbar.HORIZONTAL, 0, 60, 0, 300);
* add(ranger);
* </pre></blockquote><hr>
* <p>
* Note that the actual maximum value of the scroll bar is the
* <code>maximum</code> minus the <code>visible amount</code>.
* In the previous example, because the <code>maximum</code> is
* 300 and the <code>visible amount</code> is 60, the actual maximum
* value is 240. The range of the scrollbar track is 0 - 300.
* The left side of the bubble indicates the value of the
* scroll bar.
* <p>
* Normally, the user changes the value of the scroll bar by
* making a gesture with the mouse. For example, the user can
* drag the scroll bar's bubble up and down, or click in the
* scroll bar's unit increment or block increment areas. Keyboard
* gestures can also be mapped to the scroll bar. By convention,
* the <b>Page Up</b> and <b>Page Down</b>
* keys are equivalent to clicking in the scroll bar's block
* increment and block decrement areas.
* <p>
* When the user changes the value of the scroll bar, the scroll bar
* receives an instance of <code>AdjustmentEvent</code>.
* The scroll bar processes this event, passing it along to
* any registered listeners.
* <p>
* Any object that wishes to be notified of changes to the
* scroll bar's value should implement
* <code>AdjustmentListener</code>, an interface defined in
* the package <code>java.awt.event</code>.
* Listeners can be added and removed dynamically by calling
* the methods <code>addAdjustmentListener</code> and
* <code>removeAdjustmentListener</code>.
* <p>
* The <code>AdjustmentEvent</code> class defines five types
* of adjustment event, listed here:
* <p>
* <ul>
* <li><code>AdjustmentEvent.TRACK</code> is sent out when the
* user drags the scroll bar's bubble.
* <li><code>AdjustmentEvent.UNIT_INCREMENT</code> is sent out
* when the user clicks in the left arrow of a horizontal scroll
* bar, or the top arrow of a vertical scroll bar, or makes the
* equivalent gesture from the keyboard.
* <li><code>AdjustmentEvent.UNIT_DECREMENT</code> is sent out
* when the user clicks in the right arrow of a horizontal scroll
* bar, or the bottom arrow of a vertical scroll bar, or makes the
* equivalent gesture from the keyboard.
* <li><code>AdjustmentEvent.BLOCK_INCREMENT</code> is sent out
* when the user clicks in the track, to the left of the bubble
* on a horizontal scroll bar, or above the bubble on a vertical
* scroll bar. By convention, the <b>Page Up</b>
* key is equivalent, if the user is using a keyboard that
* defines a <b>Page Up</b> key.
* <li><code>AdjustmentEvent.BLOCK_DECREMENT</code> is sent out
* when the user clicks in the track, to the right of the bubble
* on a horizontal scroll bar, or below the bubble on a vertical
* scroll bar. By convention, the <b>Page Down</b>
* key is equivalent, if the user is using a keyboard that
* defines a <b>Page Down</b> key.
* </ul>
* <p>
* The JDK 1.0 event system is supported for backwards
* compatibility, but its use with newer versions of the platform is
* discouraged. The five types of adjustment events introduced
* with JDK 1.1 correspond to the five event types
* that are associated with scroll bars in previous platform versions.
* The following list gives the adjustment event type,
* and the corresponding JDK 1.0 event type it replaces.
* <p>
* <ul>
* <li><code>AdjustmentEvent.TRACK</code> replaces
* <code>Event.SCROLL_ABSOLUTE</code>
* <li><code>AdjustmentEvent.UNIT_INCREMENT</code> replaces
* <code>Event.SCROLL_LINE_UP</code>
* <li><code>AdjustmentEvent.UNIT_DECREMENT</code> replaces
* <code>Event.SCROLL_LINE_DOWN</code>
* <li><code>AdjustmentEvent.BLOCK_INCREMENT</code> replaces
* <code>Event.SCROLL_PAGE_UP</code>
* <li><code>AdjustmentEvent.BLOCK_DECREMENT</code> replaces
* <code>Event.SCROLL_PAGE_DOWN</code>
* </ul>
* <p>
* <b>Note</b>: We recommend using a <code>Scrollbar</code>
* for value selection only. If you want to implement
* a scrollable component inside a container, we recommend you use
* a {@link ScrollPane ScrollPane}. If you use a
* <code>Scrollbar</code> for this purpose, you are likely to
* encounter issues with painting, key handling, sizing and
* positioning.
*
* @author Sami Shaio
* @see java.awt.event.AdjustmentEvent
* @see java.awt.event.AdjustmentListener
* @since JDK1.0
*/
public class Scrollbar extends Component implements Adjustable, Accessible {
/** {@collect.stats}
* A constant that indicates a horizontal scroll bar.
*/
public static final int HORIZONTAL = 0;
/** {@collect.stats}
* A constant that indicates a vertical scroll bar.
*/
public static final int VERTICAL = 1;
/** {@collect.stats}
* The value of the <code>Scrollbar</code>.
* This property must be greater than or equal to <code>minimum</code>
* and less than or equal to
* <code>maximum - visibleAmount</code>
*
* @serial
* @see #getValue
* @see #setValue
*/
int value;
/** {@collect.stats}
* The maximum value of the <code>Scrollbar</code>.
* This value must be greater than the <code>minimum</code>
* value.<br>
*
* @serial
* @see #getMaximum
* @see #setMaximum
*/
int maximum;
/** {@collect.stats}
* The minimum value of the <code>Scrollbar</code>.
* This value must be less than the <code>maximum</code>
* value.<br>
*
* @serial
* @see #getMinimum
* @see #setMinimum
*/
int minimum;
/** {@collect.stats}
* The size of the <code>Scrollbar</code>'s bubble.
* When a scroll bar is used to select a range of values,
* the visibleAmount represents the size of this range.
* This is visually indicated by the size of the bubble.
*
* @serial
* @see #getVisibleAmount
* @see #setVisibleAmount
*/
int visibleAmount;
/** {@collect.stats}
* The <code>Scrollbar</code>'s orientation--being either horizontal
* or vertical.
* This value should be specified when the scrollbar is created.<BR>
* orientation can be either : <code>VERTICAL</code> or
* <code>HORIZONTAL</code> only.
*
* @serial
* @see #getOrientation
* @see #setOrientation
*/
int orientation;
/** {@collect.stats}
* The amount by which the scrollbar value will change when going
* up or down by a line.
* This value must be greater than zero.
*
* @serial
* @see #getLineIncrement
* @see #setLineIncrement
*/
int lineIncrement = 1;
/** {@collect.stats}
* The amount by which the scrollbar value will change when going
* up or down by a page.
* This value must be greater than zero.
*
* @serial
* @see #getPageIncrement
* @see #setPageIncrement
*/
int pageIncrement = 10;
/** {@collect.stats}
* The adjusting status of the <code>Scrollbar</code>.
* True if the value is in the process of changing as a result of
* actions being taken by the user.
*
* @see #getValueIsAdjusting
* @see #setValueIsAdjusting
* @since 1.4
*/
transient boolean isAdjusting;
transient AdjustmentListener adjustmentListener;
private static final String base = "scrollbar";
private static int nameCounter = 0;
/*
* JDK 1.1 serialVersionUID
*/
private static final long serialVersionUID = 8451667562882310543L;
/** {@collect.stats}
* Initialize JNI field and method IDs.
*/
private static native void initIDs();
static {
/* ensure that the necessary native libraries are loaded */
Toolkit.loadLibraries();
if (!GraphicsEnvironment.isHeadless()) {
initIDs();
}
}
/** {@collect.stats}
* Constructs a new vertical scroll bar.
* The default properties of the scroll bar are listed in
* the following table:
* <p> </p>
* <table border=1 summary="Scrollbar default properties">
* <tr>
* <th>Property</th>
* <th>Description</th>
* <th>Default Value</th>
* </tr>
* <tr>
* <td>orientation</td>
* <td>indicates whether the scroll bar is vertical
* <br>or horizontal</td>
* <td><code>Scrollbar.VERTICAL</code></td>
* </tr>
* <tr>
* <td>value</td>
* <td>value which controls the location
* <br>of the scroll bar's bubble</td>
* <td>0</td>
* </tr>
* <tr>
* <td>visible amount</td>
* <td>visible amount of the scroll bar's range,
* <br>typically represented by the size of the
* <br>scroll bar's bubble</td>
* <td>10</td>
* </tr>
* <tr>
* <td>minimum</td>
* <td>minimum value of the scroll bar</td>
* <td>0</td>
* </tr>
* <tr>
* <td>maximum</td>
* <td>maximum value of the scroll bar</td>
* <td>100</td>
* </tr>
* <tr>
* <td>unit increment</td>
* <td>amount the value changes when the
* <br>Line Up or Line Down key is pressed,
* <br>or when the end arrows of the scrollbar
* <br>are clicked </td>
* <td>1</td>
* </tr>
* <tr>
* <td>block increment</td>
* <td>amount the value changes when the
* <br>Page Up or Page Down key is pressed,
* <br>or when the scrollbar track is clicked
* <br>on either side of the bubble </td>
* <td>10</td>
* </tr>
* </table>
*
* @exception HeadlessException if GraphicsEnvironment.isHeadless()
* returns true.
* @see java.awt.GraphicsEnvironment#isHeadless
*/
public Scrollbar() throws HeadlessException {
this(VERTICAL, 0, 10, 0, 100);
}
/** {@collect.stats}
* Constructs a new scroll bar with the specified orientation.
* <p>
* The <code>orientation</code> argument must take one of the two
* values <code>Scrollbar.HORIZONTAL</code>,
* or <code>Scrollbar.VERTICAL</code>,
* indicating a horizontal or vertical scroll bar, respectively.
*
* @param orientation indicates the orientation of the scroll bar
* @exception IllegalArgumentException when an illegal value for
* the <code>orientation</code> argument is supplied
* @exception HeadlessException if GraphicsEnvironment.isHeadless()
* returns true.
* @see java.awt.GraphicsEnvironment#isHeadless
*/
public Scrollbar(int orientation) throws HeadlessException {
this(orientation, 0, 10, 0, 100);
}
/** {@collect.stats}
* Constructs a new scroll bar with the specified orientation,
* initial value, visible amount, and minimum and maximum values.
* <p>
* The <code>orientation</code> argument must take one of the two
* values <code>Scrollbar.HORIZONTAL</code>,
* or <code>Scrollbar.VERTICAL</code>,
* indicating a horizontal or vertical scroll bar, respectively.
* <p>
* The parameters supplied to this constructor are subject to the
* constraints described in {@link #setValues(int, int, int, int)}.
*
* @param orientation indicates the orientation of the scroll bar.
* @param value the initial value of the scroll bar
* @param visible the visible amount of the scroll bar, typically
* represented by the size of the bubble
* @param minimum the minimum value of the scroll bar
* @param maximum the maximum value of the scroll bar
* @exception IllegalArgumentException when an illegal value for
* the <code>orientation</code> argument is supplied
* @exception HeadlessException if GraphicsEnvironment.isHeadless()
* returns true.
* @see #setValues
* @see java.awt.GraphicsEnvironment#isHeadless
*/
public Scrollbar(int orientation, int value, int visible, int minimum,
int maximum) throws HeadlessException {
GraphicsEnvironment.checkHeadless();
switch (orientation) {
case HORIZONTAL:
case VERTICAL:
this.orientation = orientation;
break;
default:
throw new IllegalArgumentException("illegal scrollbar orientation");
}
setValues(value, visible, minimum, maximum);
}
/** {@collect.stats}
* Constructs a name for this component. Called by <code>getName</code>
* when the name is <code>null</code>.
*/
String constructComponentName() {
synchronized (Scrollbar.class) {
return base + nameCounter++;
}
}
/** {@collect.stats}
* Creates the <code>Scrollbar</code>'s peer. The peer allows you to modify
* the appearance of the <code>Scrollbar</code> without changing any of its
* functionality.
*/
public void addNotify() {
synchronized (getTreeLock()) {
if (peer == null)
peer = getToolkit().createScrollbar(this);
super.addNotify();
}
}
/** {@collect.stats}
* Returns the orientation of this scroll bar.
*
* @return the orientation of this scroll bar, either
* <code>Scrollbar.HORIZONTAL</code> or
* <code>Scrollbar.VERTICAL</code>
* @see java.awt.Scrollbar#setOrientation
*/
public int getOrientation() {
return orientation;
}
/** {@collect.stats}
* Sets the orientation for this scroll bar.
*
* @param orientation the orientation of this scroll bar, either
* <code>Scrollbar.HORIZONTAL</code> or
* <code>Scrollbar.VERTICAL</code>
* @see java.awt.Scrollbar#getOrientation
* @exception IllegalArgumentException if the value supplied
* for <code>orientation</code> is not a
* legal value
* @since JDK1.1
*/
public void setOrientation(int orientation) {
synchronized (getTreeLock()) {
if (orientation == this.orientation) {
return;
}
switch (orientation) {
case HORIZONTAL:
case VERTICAL:
this.orientation = orientation;
break;
default:
throw new IllegalArgumentException("illegal scrollbar orientation");
}
/* Create a new peer with the specified orientation. */
if (peer != null) {
removeNotify();
addNotify();
invalidate();
}
}
if (accessibleContext != null) {
accessibleContext.firePropertyChange(
AccessibleContext.ACCESSIBLE_STATE_PROPERTY,
((orientation == VERTICAL)
? AccessibleState.HORIZONTAL : AccessibleState.VERTICAL),
((orientation == VERTICAL)
? AccessibleState.VERTICAL : AccessibleState.HORIZONTAL));
}
}
/** {@collect.stats}
* Gets the current value of this scroll bar.
*
* @return the current value of this scroll bar
* @see java.awt.Scrollbar#getMinimum
* @see java.awt.Scrollbar#getMaximum
*/
public int getValue() {
return value;
}
/** {@collect.stats}
* Sets the value of this scroll bar to the specified value.
* <p>
* If the value supplied is less than the current <code>minimum</code>
* or greater than the current <code>maximum - visibleAmount</code>,
* then either <code>minimum</code> or <code>maximum - visibleAmount</code>
* is substituted, as appropriate.
* <p>
* Normally, a program should change a scroll bar's
* value only by calling <code>setValues</code>.
* The <code>setValues</code> method simultaneously
* and synchronously sets the minimum, maximum, visible amount,
* and value properties of a scroll bar, so that they are
* mutually consistent.
* <p>
* Calling this method does not fire an
* <code>AdjustmentEvent</code>.
*
* @param newValue the new value of the scroll bar
* @see java.awt.Scrollbar#setValues
* @see java.awt.Scrollbar#getValue
* @see java.awt.Scrollbar#getMinimum
* @see java.awt.Scrollbar#getMaximum
*/
public void setValue(int newValue) {
// Use setValues so that a consistent policy relating
// minimum, maximum, visible amount, and value is enforced.
setValues(newValue, visibleAmount, minimum, maximum);
}
/** {@collect.stats}
* Gets the minimum value of this scroll bar.
*
* @return the minimum value of this scroll bar
* @see java.awt.Scrollbar#getValue
* @see java.awt.Scrollbar#getMaximum
*/
public int getMinimum() {
return minimum;
}
/** {@collect.stats}
* Sets the minimum value of this scroll bar.
* <p>
* When <code>setMinimum</code> is called, the minimum value
* is changed, and other values (including the maximum, the
* visible amount, and the current scroll bar value)
* are changed to be consistent with the new minimum.
* <p>
* Normally, a program should change a scroll bar's minimum
* value only by calling <code>setValues</code>.
* The <code>setValues</code> method simultaneously
* and synchronously sets the minimum, maximum, visible amount,
* and value properties of a scroll bar, so that they are
* mutually consistent.
* <p>
* Note that setting the minimum value to <code>Integer.MAX_VALUE</code>
* will result in the new minimum value being set to
* <code>Integer.MAX_VALUE - 1</code>.
*
* @param newMinimum the new minimum value for this scroll bar
* @see java.awt.Scrollbar#setValues
* @see java.awt.Scrollbar#setMaximum
* @since JDK1.1
*/
public void setMinimum(int newMinimum) {
// No checks are necessary in this method since minimum is
// the first variable checked in the setValues function.
// Use setValues so that a consistent policy relating
// minimum, maximum, visible amount, and value is enforced.
setValues(value, visibleAmount, newMinimum, maximum);
}
/** {@collect.stats}
* Gets the maximum value of this scroll bar.
*
* @return the maximum value of this scroll bar
* @see java.awt.Scrollbar#getValue
* @see java.awt.Scrollbar#getMinimum
*/
public int getMaximum() {
return maximum;
}
/** {@collect.stats}
* Sets the maximum value of this scroll bar.
* <p>
* When <code>setMaximum</code> is called, the maximum value
* is changed, and other values (including the minimum, the
* visible amount, and the current scroll bar value)
* are changed to be consistent with the new maximum.
* <p>
* Normally, a program should change a scroll bar's maximum
* value only by calling <code>setValues</code>.
* The <code>setValues</code> method simultaneously
* and synchronously sets the minimum, maximum, visible amount,
* and value properties of a scroll bar, so that they are
* mutually consistent.
* <p>
* Note that setting the maximum value to <code>Integer.MIN_VALUE</code>
* will result in the new maximum value being set to
* <code>Integer.MIN_VALUE + 1</code>.
*
* @param newMaximum the new maximum value
* for this scroll bar
* @see java.awt.Scrollbar#setValues
* @see java.awt.Scrollbar#setMinimum
* @since JDK1.1
*/
public void setMaximum(int newMaximum) {
// minimum is checked first in setValues, so we need to
// enforce minimum and maximum checks here.
if (newMaximum == Integer.MIN_VALUE) {
newMaximum = Integer.MIN_VALUE + 1;
}
if (minimum >= newMaximum) {
minimum = newMaximum - 1;
}
// Use setValues so that a consistent policy relating
// minimum, maximum, visible amount, and value is enforced.
setValues(value, visibleAmount, minimum, newMaximum);
}
/** {@collect.stats}
* Gets the visible amount of this scroll bar.
* <p>
* When a scroll bar is used to select a range of values,
* the visible amount is used to represent the range of values
* that are currently visible. The size of the scroll bar's
* bubble (also called a thumb or scroll box), usually gives a
* visual representation of the relationship of the visible
* amount to the range of the scroll bar.
* <p>
* The scroll bar's bubble may not be displayed when it is not
* moveable (e.g. when it takes up the entire length of the
* scroll bar's track, or when the scroll bar is disabled).
* Whether the bubble is displayed or not will not affect
* the value returned by <code>getVisibleAmount</code>.
*
* @return the visible amount of this scroll bar
* @see java.awt.Scrollbar#setVisibleAmount
* @since JDK1.1
*/
public int getVisibleAmount() {
return getVisible();
}
/** {@collect.stats}
* @deprecated As of JDK version 1.1,
* replaced by <code>getVisibleAmount()</code>.
*/
@Deprecated
public int getVisible() {
return visibleAmount;
}
/** {@collect.stats}
* Sets the visible amount of this scroll bar.
* <p>
* When a scroll bar is used to select a range of values,
* the visible amount is used to represent the range of values
* that are currently visible. The size of the scroll bar's
* bubble (also called a thumb or scroll box), usually gives a
* visual representation of the relationship of the visible
* amount to the range of the scroll bar.
* <p>
* The scroll bar's bubble may not be displayed when it is not
* moveable (e.g. when it takes up the entire length of the
* scroll bar's track, or when the scroll bar is disabled).
* Whether the bubble is displayed or not will not affect
* the value returned by <code>getVisibleAmount</code>.
* <p>
* If the visible amount supplied is less than <code>one</code>
* or greater than the current <code>maximum - minimum</code>,
* then either <code>one</code> or <code>maximum - minimum</code>
* is substituted, as appropriate.
* <p>
* Normally, a program should change a scroll bar's
* value only by calling <code>setValues</code>.
* The <code>setValues</code> method simultaneously
* and synchronously sets the minimum, maximum, visible amount,
* and value properties of a scroll bar, so that they are
* mutually consistent.
*
* @param newAmount the new visible amount
* @see java.awt.Scrollbar#getVisibleAmount
* @see java.awt.Scrollbar#setValues
* @since JDK1.1
*/
public void setVisibleAmount(int newAmount) {
// Use setValues so that a consistent policy relating
// minimum, maximum, visible amount, and value is enforced.
setValues(value, newAmount, minimum, maximum);
}
/** {@collect.stats}
* Sets the unit increment for this scroll bar.
* <p>
* The unit increment is the value that is added or subtracted
* when the user activates the unit increment area of the
* scroll bar, generally through a mouse or keyboard gesture
* that the scroll bar receives as an adjustment event.
* The unit increment must be greater than zero.
* Attepts to set the unit increment to a value lower than 1
* will result in a value of 1 being set.
*
* @param v the amount by which to increment or decrement
* the scroll bar's value
* @see java.awt.Scrollbar#getUnitIncrement
* @since JDK1.1
*/
public void setUnitIncrement(int v) {
setLineIncrement(v);
}
/** {@collect.stats}
* @deprecated As of JDK version 1.1,
* replaced by <code>setUnitIncrement(int)</code>.
*/
@Deprecated
public synchronized void setLineIncrement(int v) {
int tmp = (v < 1) ? 1 : v;
if (lineIncrement == tmp) {
return;
}
lineIncrement = tmp;
ScrollbarPeer peer = (ScrollbarPeer)this.peer;
if (peer != null) {
peer.setLineIncrement(lineIncrement);
}
}
/** {@collect.stats}
* Gets the unit increment for this scrollbar.
* <p>
* The unit increment is the value that is added or subtracted
* when the user activates the unit increment area of the
* scroll bar, generally through a mouse or keyboard gesture
* that the scroll bar receives as an adjustment event.
* The unit increment must be greater than zero.
*
* @return the unit increment of this scroll bar
* @see java.awt.Scrollbar#setUnitIncrement
* @since JDK1.1
*/
public int getUnitIncrement() {
return getLineIncrement();
}
/** {@collect.stats}
* @deprecated As of JDK version 1.1,
* replaced by <code>getUnitIncrement()</code>.
*/
@Deprecated
public int getLineIncrement() {
return lineIncrement;
}
/** {@collect.stats}
* Sets the block increment for this scroll bar.
* <p>
* The block increment is the value that is added or subtracted
* when the user activates the block increment area of the
* scroll bar, generally through a mouse or keyboard gesture
* that the scroll bar receives as an adjustment event.
* The block increment must be greater than zero.
* Attepts to set the block increment to a value lower than 1
* will result in a value of 1 being set.
*
* @param v the amount by which to increment or decrement
* the scroll bar's value
* @see java.awt.Scrollbar#getBlockIncrement
* @since JDK1.1
*/
public void setBlockIncrement(int v) {
setPageIncrement(v);
}
/** {@collect.stats}
* @deprecated As of JDK version 1.1,
* replaced by <code>setBlockIncrement()</code>.
*/
@Deprecated
public synchronized void setPageIncrement(int v) {
int tmp = (v < 1) ? 1 : v;
if (pageIncrement == tmp) {
return;
}
pageIncrement = tmp;
ScrollbarPeer peer = (ScrollbarPeer)this.peer;
if (peer != null) {
peer.setPageIncrement(pageIncrement);
}
}
/** {@collect.stats}
* Gets the block increment of this scroll bar.
* <p>
* The block increment is the value that is added or subtracted
* when the user activates the block increment area of the
* scroll bar, generally through a mouse or keyboard gesture
* that the scroll bar receives as an adjustment event.
* The block increment must be greater than zero.
*
* @return the block increment of this scroll bar
* @see java.awt.Scrollbar#setBlockIncrement
* @since JDK1.1
*/
public int getBlockIncrement() {
return getPageIncrement();
}
/** {@collect.stats}
* @deprecated As of JDK version 1.1,
* replaced by <code>getBlockIncrement()</code>.
*/
@Deprecated
public int getPageIncrement() {
return pageIncrement;
}
/** {@collect.stats}
* Sets the values of four properties for this scroll bar:
* <code>value</code>, <code>visibleAmount</code>,
* <code>minimum</code>, and <code>maximum</code>.
* If the values supplied for these properties are inconsistent
* or incorrect, they will be changed to ensure consistency.
* <p>
* This method simultaneously and synchronously sets the values
* of four scroll bar properties, assuring that the values of
* these properties are mutually consistent. It enforces the
* following constraints:
* <code>maximum</code> must be greater than <code>minimum</code>,
* <code>maximum - minimum</code> must not be greater
* than <code>Integer.MAX_VALUE</code>,
* <code>visibleAmount</code> must be greater than zero.
* <code>visibleAmount</code> must not be greater than
* <code>maximum - minimum</code>,
* <code>value</code> must not be less than <code>minimum</code>,
* and <code>value</code> must not be greater than
* <code>maximum - visibleAmount</code>
* <p>
* Calling this method does not fire an
* <code>AdjustmentEvent</code>.
*
* @param value is the position in the current window
* @param visible is the visible amount of the scroll bar
* @param minimum is the minimum value of the scroll bar
* @param maximum is the maximum value of the scroll bar
* @see #setMinimum
* @see #setMaximum
* @see #setVisibleAmount
* @see #setValue
*/
public void setValues(int value, int visible, int minimum, int maximum) {
int oldValue;
synchronized (this) {
if (minimum == Integer.MAX_VALUE) {
minimum = Integer.MAX_VALUE - 1;
}
if (maximum <= minimum) {
maximum = minimum + 1;
}
long maxMinusMin = (long) maximum - (long) minimum;
if (maxMinusMin > Integer.MAX_VALUE) {
maxMinusMin = Integer.MAX_VALUE;
maximum = minimum + (int) maxMinusMin;
}
if (visible > (int) maxMinusMin) {
visible = (int) maxMinusMin;
}
if (visible < 1) {
visible = 1;
}
if (value < minimum) {
value = minimum;
}
if (value > maximum - visible) {
value = maximum - visible;
}
oldValue = this.value;
this.value = value;
this.visibleAmount = visible;
this.minimum = minimum;
this.maximum = maximum;
ScrollbarPeer peer = (ScrollbarPeer)this.peer;
if (peer != null) {
peer.setValues(value, visibleAmount, minimum, maximum);
}
}
if ((oldValue != value) && (accessibleContext != null)) {
accessibleContext.firePropertyChange(
AccessibleContext.ACCESSIBLE_VALUE_PROPERTY,
Integer.valueOf(oldValue),
Integer.valueOf(value));
}
}
/** {@collect.stats}
* Returns true if the value is in the process of changing as a
* result of actions being taken by the user.
*
* @return the value of the <code>valueIsAdjusting</code> property
* @see #setValueIsAdjusting
* @since 1.4
*/
public boolean getValueIsAdjusting() {
return isAdjusting;
}
/** {@collect.stats}
* Sets the <code>valueIsAdjusting</code> property.
*
* @param b new adjustment-in-progress status
* @see #getValueIsAdjusting
* @since 1.4
*/
public void setValueIsAdjusting(boolean b) {
boolean oldValue;
synchronized (this) {
oldValue = isAdjusting;
isAdjusting = b;
}
if ((oldValue != b) && (accessibleContext != null)) {
accessibleContext.firePropertyChange(
AccessibleContext.ACCESSIBLE_STATE_PROPERTY,
((oldValue) ? AccessibleState.BUSY : null),
((b) ? AccessibleState.BUSY : null));
}
}
/** {@collect.stats}
* Adds the specified adjustment listener to receive instances of
* <code>AdjustmentEvent</code> from this scroll bar.
* If l is <code>null</code>, no exception is thrown and no
* action is performed.
* <p>Refer to <a href="doc-files/AWTThreadIssues.html#ListenersThreads"
* >AWT Threading Issues</a> for details on AWT's threading model.
*
* @param l the adjustment listener
* @see #removeAdjustmentListener
* @see #getAdjustmentListeners
* @see java.awt.event.AdjustmentEvent
* @see java.awt.event.AdjustmentListener
* @since JDK1.1
*/
public synchronized void addAdjustmentListener(AdjustmentListener l) {
if (l == null) {
return;
}
adjustmentListener = AWTEventMulticaster.add(adjustmentListener, l);
newEventsOnly = true;
}
/** {@collect.stats}
* Removes the specified adjustment listener so that it no longer
* receives instances of <code>AdjustmentEvent</code> from this scroll bar.
* If l is <code>null</code>, no exception is thrown and no action
* is performed.
* <p>Refer to <a href="doc-files/AWTThreadIssues.html#ListenersThreads"
* >AWT Threading Issues</a> for details on AWT's threading model.
*
* @param l the adjustment listener
* @see #addAdjustmentListener
* @see #getAdjustmentListeners
* @see java.awt.event.AdjustmentEvent
* @see java.awt.event.AdjustmentListener
* @since JDK1.1
*/
public synchronized void removeAdjustmentListener(AdjustmentListener l) {
if (l == null) {
return;
}
adjustmentListener = AWTEventMulticaster.remove(adjustmentListener, l);
}
/** {@collect.stats}
* Returns an array of all the adjustment listeners
* registered on this scrollbar.
*
* @return all of this scrollbar's <code>AdjustmentListener</code>s
* or an empty array if no adjustment
* listeners are currently registered
* @see #addAdjustmentListener
* @see #removeAdjustmentListener
* @see java.awt.event.AdjustmentEvent
* @see java.awt.event.AdjustmentListener
* @since 1.4
*/
public synchronized AdjustmentListener[] getAdjustmentListeners() {
return (AdjustmentListener[])(getListeners(AdjustmentListener.class));
}
/** {@collect.stats}
* Returns an array of all the objects currently registered
* as <code><em>Foo</em>Listener</code>s
* upon this <code>Scrollbar</code>.
* <code><em>Foo</em>Listener</code>s are registered using the
* <code>add<em>Foo</em>Listener</code> method.
* <p>
* You can specify the <code>listenerType</code> argument
* with a class literal, such as
* <code><em>Foo</em>Listener.class</code>.
* For example, you can query a
* <code>Scrollbar</code> <code>c</code>
* for its mouse listeners with the following code:
*
* <pre>MouseListener[] mls = (MouseListener[])(c.getListeners(MouseListener.class));</pre>
*
* If no such listeners exist, this method returns an empty array.
*
* @param listenerType the type of listeners requested; this parameter
* should specify an interface that descends from
* <code>java.util.EventListener</code>
* @return an array of all objects registered as
* <code><em>Foo</em>Listener</code>s on this component,
* or an empty array if no such listeners have been added
* @exception ClassCastException if <code>listenerType</code>
* doesn't specify a class or interface that implements
* <code>java.util.EventListener</code>
*
* @since 1.3
*/
public <T extends EventListener> T[] getListeners(Class<T> listenerType) {
EventListener l = null;
if (listenerType == AdjustmentListener.class) {
l = adjustmentListener;
} else {
return super.getListeners(listenerType);
}
return AWTEventMulticaster.getListeners(l, listenerType);
}
// REMIND: remove when filtering is done at lower level
boolean eventEnabled(AWTEvent e) {
if (e.id == AdjustmentEvent.ADJUSTMENT_VALUE_CHANGED) {
if ((eventMask & AWTEvent.ADJUSTMENT_EVENT_MASK) != 0 ||
adjustmentListener != null) {
return true;
}
return false;
}
return super.eventEnabled(e);
}
/** {@collect.stats}
* Processes events on this scroll bar. If the event is an
* instance of <code>AdjustmentEvent</code>, it invokes the
* <code>processAdjustmentEvent</code> method.
* Otherwise, it invokes its superclass's
* <code>processEvent</code> method.
* <p>Note that if the event parameter is <code>null</code>
* the behavior is unspecified and may result in an
* exception.
*
* @param e the event
* @see java.awt.event.AdjustmentEvent
* @see java.awt.Scrollbar#processAdjustmentEvent
* @since JDK1.1
*/
protected void processEvent(AWTEvent e) {
if (e instanceof AdjustmentEvent) {
processAdjustmentEvent((AdjustmentEvent)e);
return;
}
super.processEvent(e);
}
/** {@collect.stats}
* Processes adjustment events occurring on this
* scrollbar by dispatching them to any registered
* <code>AdjustmentListener</code> objects.
* <p>
* This method is not called unless adjustment events are
* enabled for this component. Adjustment events are enabled
* when one of the following occurs:
* <p><ul>
* <li>An <code>AdjustmentListener</code> object is registered
* via <code>addAdjustmentListener</code>.
* <li>Adjustment events are enabled via <code>enableEvents</code>.
* </ul><p>
* <p>Note that if the event parameter is <code>null</code>
* the behavior is unspecified and may result in an
* exception.
*
* @param e the adjustment event
* @see java.awt.event.AdjustmentEvent
* @see java.awt.event.AdjustmentListener
* @see java.awt.Scrollbar#addAdjustmentListener
* @see java.awt.Component#enableEvents
* @since JDK1.1
*/
protected void processAdjustmentEvent(AdjustmentEvent e) {
AdjustmentListener listener = adjustmentListener;
if (listener != null) {
listener.adjustmentValueChanged(e);
}
}
/** {@collect.stats}
* Returns a string representing the state of this <code>Scrollbar</code>.
* This method is intended to be used only for debugging purposes, and the
* content and format of the returned string may vary between
* implementations. The returned string may be empty but may not be
* <code>null</code>.
*
* @return the parameter string of this scroll bar
*/
protected String paramString() {
return super.paramString() +
",val=" + value +
",vis=" + visibleAmount +
",min=" + minimum +
",max=" + maximum +
((orientation == VERTICAL) ? ",vert" : ",horz") +
",isAdjusting=" + isAdjusting;
}
/* Serialization support.
*/
/** {@collect.stats}
* The scroll bar's serialized Data Version.
*
* @serial
*/
private int scrollbarSerializedDataVersion = 1;
/** {@collect.stats}
* Writes default serializable fields to stream. Writes
* a list of serializable <code>AdjustmentListeners</code>
* as optional data. The non-serializable listeners are
* detected and no attempt is made to serialize them.
*
* @param s the <code>ObjectOutputStream</code> to write
* @serialData <code>null</code> terminated sequence of 0
* or more pairs; the pair consists of a <code>String</code>
* and an <code>Object</code>; the <code>String</code> indicates
* the type of object and is one of the following:
* <code>adjustmentListenerK</code> indicating an
* <code>AdjustmentListener</code> object
*
* @see AWTEventMulticaster#save(ObjectOutputStream, String, EventListener)
* @see java.awt.Component#adjustmentListenerK
* @see #readObject(ObjectInputStream)
*/
private void writeObject(ObjectOutputStream s)
throws IOException
{
s.defaultWriteObject();
AWTEventMulticaster.save(s, adjustmentListenerK, adjustmentListener);
s.writeObject(null);
}
/** {@collect.stats}
* Reads the <code>ObjectInputStream</code> and if
* it isn't <code>null</code> adds a listener to
* receive adjustment events fired by the
* <code>Scrollbar</code>.
* Unrecognized keys or values will be ignored.
*
* @param s the <code>ObjectInputStream</code> to read
* @exception HeadlessException if
* <code>GraphicsEnvironment.isHeadless</code> returns
* <code>true</code>
* @see java.awt.GraphicsEnvironment#isHeadless
* @see #writeObject(ObjectOutputStream)
*/
private void readObject(ObjectInputStream s)
throws ClassNotFoundException, IOException, HeadlessException
{
GraphicsEnvironment.checkHeadless();
s.defaultReadObject();
Object keyOrNull;
while(null != (keyOrNull = s.readObject())) {
String key = ((String)keyOrNull).intern();
if (adjustmentListenerK == key)
addAdjustmentListener((AdjustmentListener)(s.readObject()));
else // skip value for unrecognized key
s.readObject();
}
}
/////////////////
// Accessibility support
////////////////
/** {@collect.stats}
* Gets the <code>AccessibleContext</code> associated with this
* <code>Scrollbar</code>. For scrollbars, the
* <code>AccessibleContext</code> takes the form of an
* <code>AccessibleAWTScrollBar</code>. A new
* <code>AccessibleAWTScrollBar</code> instance is created if necessary.
*
* @return an <code>AccessibleAWTScrollBar</code> that serves as the
* <code>AccessibleContext</code> of this <code>ScrollBar</code>
* @since 1.3
*/
public AccessibleContext getAccessibleContext() {
if (accessibleContext == null) {
accessibleContext = new AccessibleAWTScrollBar();
}
return accessibleContext;
}
/** {@collect.stats}
* This class implements accessibility support for the
* <code>Scrollbar</code> class. It provides an implementation of
* the Java Accessibility API appropriate to scrollbar
* user-interface elements.
* @since 1.3
*/
protected class AccessibleAWTScrollBar extends AccessibleAWTComponent
implements AccessibleValue
{
/*
* JDK 1.3 serialVersionUID
*/
private static final long serialVersionUID = -344337268523697807L;
/** {@collect.stats}
* Get the state set of this object.
*
* @return an instance of <code>AccessibleState</code>
* containing the current state of the object
* @see AccessibleState
*/
public AccessibleStateSet getAccessibleStateSet() {
AccessibleStateSet states = super.getAccessibleStateSet();
if (getValueIsAdjusting()) {
states.add(AccessibleState.BUSY);
}
if (getOrientation() == VERTICAL) {
states.add(AccessibleState.VERTICAL);
} else {
states.add(AccessibleState.HORIZONTAL);
}
return states;
}
/** {@collect.stats}
* Get the role of this object.
*
* @return an instance of <code>AccessibleRole</code>
* describing the role of the object
*/
public AccessibleRole getAccessibleRole() {
return AccessibleRole.SCROLL_BAR;
}
/** {@collect.stats}
* Get the <code>AccessibleValue</code> associated with this
* object. In the implementation of the Java Accessibility
* API for this class, return this object, which is
* responsible for implementing the
* <code>AccessibleValue</code> interface on behalf of itself.
*
* @return this object
*/
public AccessibleValue getAccessibleValue() {
return this;
}
/** {@collect.stats}
* Get the accessible value of this object.
*
* @return The current value of this object.
*/
public Number getCurrentAccessibleValue() {
return Integer.valueOf(getValue());
}
/** {@collect.stats}
* Set the value of this object as a Number.
*
* @return True if the value was set.
*/
public boolean setCurrentAccessibleValue(Number n) {
if (n instanceof Integer) {
setValue(n.intValue());
return true;
} else {
return false;
}
}
/** {@collect.stats}
* Get the minimum accessible value of this object.
*
* @return The minimum value of this object.
*/
public Number getMinimumAccessibleValue() {
return Integer.valueOf(getMinimum());
}
/** {@collect.stats}
* Get the maximum accessible value of this object.
*
* @return The maximum value of this object.
*/
public Number getMaximumAccessibleValue() {
return Integer.valueOf(getMaximum());
}
} // AccessibleAWTScrollBar
}
|
Java
|
/*
* Copyright (c) 1998, 2006, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code 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
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package java.awt.event;
import java.awt.ActiveEvent;
import java.awt.AWTEvent;
/** {@collect.stats}
* An event which executes the <code>run()</code> method on a <code>Runnable
* </code> when dispatched by the AWT event dispatcher thread. This class can
* be used as a reference implementation of <code>ActiveEvent</code> rather
* than declaring a new class and defining <code>dispatch()</code>.<p>
*
* Instances of this class are placed on the <code>EventQueue</code> by calls
* to <code>invokeLater</code> and <code>invokeAndWait</code>. Client code
* can use this fact to write replacement functions for <code>invokeLater
* </code> and <code>invokeAndWait</code> without writing special-case code
* in any <code>AWTEventListener</code> objects.
*
* @author Fred Ecks
* @author David Mendenhall
*
* @see java.awt.ActiveEvent
* @see java.awt.EventQueue#invokeLater
* @see java.awt.EventQueue#invokeAndWait
* @see AWTEventListener
*
* @since 1.2
*/
public class InvocationEvent extends AWTEvent implements ActiveEvent {
/** {@collect.stats}
* Marks the first integer id for the range of invocation event ids.
*/
public static final int INVOCATION_FIRST = 1200;
/** {@collect.stats}
* The default id for all InvocationEvents.
*/
public static final int INVOCATION_DEFAULT = INVOCATION_FIRST;
/** {@collect.stats}
* Marks the last integer id for the range of invocation event ids.
*/
public static final int INVOCATION_LAST = INVOCATION_DEFAULT;
/** {@collect.stats}
* The Runnable whose run() method will be called.
*/
protected Runnable runnable;
/** {@collect.stats}
* The (potentially null) Object whose notifyAll() method will be called
* immediately after the Runnable.run() method returns.
*/
protected Object notifier;
/** {@collect.stats}
* Set to true if dispatch() catches Throwable and stores it in the
* exception instance variable. If false, Throwables are propagated up
* to the EventDispatchThread's dispatch loop.
*/
protected boolean catchExceptions;
/** {@collect.stats}
* The (potentially null) Exception thrown during execution of the
* Runnable.run() method. This variable will also be null if a particular
* instance does not catch exceptions.
*/
private Exception exception = null;
/** {@collect.stats}
* The (potentially null) Throwable thrown during execution of the
* Runnable.run() method. This variable will also be null if a particular
* instance does not catch exceptions.
*/
private Throwable throwable = null;
/** {@collect.stats}
* The timestamp of when this event occurred.
*
* @serial
* @see #getWhen
*/
private long when;
/*
* JDK 1.1 serialVersionUID.
*/
private static final long serialVersionUID = 436056344909459450L;
/** {@collect.stats}
* Constructs an <code>InvocationEvent</code> with the specified
* source which will execute the runnable's <code>run</code>
* method when dispatched.
* <p>This is a convenience constructor. An invocation of the form
* <tt>InvocationEvent(source, runnable)</tt>
* behaves in exactly the same way as the invocation of
* <tt>{@link #InvocationEvent(Object, Runnable, Object, boolean) InvocationEvent}(source, runnable, null, false)</tt>.
* <p> This method throws an <code>IllegalArgumentException</code>
* if <code>source</code> is <code>null</code>.
*
* @param source the <code>Object</code> that originated the event
* @param runnable the <code>Runnable</code> whose <code>run</code>
* method will be executed
* @throws IllegalArgumentException if <code>source</code> is null
*
* @see #InvocationEvent(Object, Runnable, Object, boolean)
*/
public InvocationEvent(Object source, Runnable runnable) {
this(source, runnable, null, false);
}
/** {@collect.stats}
* Constructs an <code>InvocationEvent</code> with the specified
* source which will execute the runnable's <code>run</code>
* method when dispatched. If notifier is non-<code>null</code>,
* <code>notifyAll()</code> will be called on it
* immediately after <code>run</code> returns.
* <p>An invocation of the form <tt>InvocationEvent(source,
* runnable, notifier, catchThrowables)</tt>
* behaves in exactly the same way as the invocation of
* <tt>{@link #InvocationEvent(Object, int, Runnable, Object, boolean) InvocationEvent}(source, InvocationEvent.INVOCATION_DEFAULT, runnable, notifier, catchThrowables)</tt>.
* <p>This method throws an <code>IllegalArgumentException</code>
* if <code>source</code> is <code>null</code>.
*
* @param source the <code>Object</code> that originated
* the event
* @param runnable the <code>Runnable</code> whose
* <code>run</code> method will be
* executed
* @param notifier the Object whose <code>notifyAll</code>
* method will be called after
* <code>Runnable.run</code> has returned
* @param catchThrowables specifies whether <code>dispatch</code>
* should catch Throwable when executing
* the <code>Runnable</code>'s <code>run</code>
* method, or should instead propagate those
* Throwables to the EventDispatchThread's
* dispatch loop
* @throws IllegalArgumentException if <code>source</code> is null
*
* @see #InvocationEvent(Object, int, Runnable, Object, boolean)
*/
public InvocationEvent(Object source, Runnable runnable, Object notifier,
boolean catchThrowables) {
this(source, INVOCATION_DEFAULT, runnable, notifier, catchThrowables);
}
/** {@collect.stats}
* Constructs an <code>InvocationEvent</code> with the specified
* source and ID which will execute the runnable's <code>run</code>
* method when dispatched. If notifier is non-<code>null</code>,
* <code>notifyAll</code> will be called on it
* immediately after <code>run</code> returns.
* <p>Note that passing in an invalid <code>id</code> results in
* unspecified behavior. This method throws an
* <code>IllegalArgumentException</code> if <code>source</code>
* is <code>null</code>.
*
* @param source the <code>Object</code> that originated
* the event
* @param id the ID for the event
* @param runnable the <code>Runnable</code> whose
* <code>run</code> method will be executed
* @param notifier the <code>Object</code> whose <code>notifyAll</code>
* method will be called after
* <code>Runnable.run</code> has returned
* @param catchThrowables specifies whether <code>dispatch</code>
* should catch Throwable when executing the
* <code>Runnable</code>'s <code>run</code>
* method, or should instead propagate those
* Throwables to the EventDispatchThread's
* dispatch loop
* @throws IllegalArgumentException if <code>source</code> is null
*/
protected InvocationEvent(Object source, int id, Runnable runnable,
Object notifier, boolean catchThrowables) {
super(source, id);
this.runnable = runnable;
this.notifier = notifier;
this.catchExceptions = catchThrowables;
this.when = System.currentTimeMillis();
}
/** {@collect.stats}
* Executes the Runnable's <code>run()</code> method and notifies the
* notifier (if any) when <code>run()</code> returns.
*/
public void dispatch() {
if (catchExceptions) {
try {
runnable.run();
}
catch (Throwable t) {
if (t instanceof Exception) {
exception = (Exception) t;
}
throwable = t;
}
}
else {
runnable.run();
}
if (notifier != null) {
synchronized (notifier) {
notifier.notifyAll();
}
}
}
/** {@collect.stats}
* Returns any Exception caught while executing the Runnable's <code>run()
* </code> method.
*
* @return A reference to the Exception if one was thrown; null if no
* Exception was thrown or if this InvocationEvent does not
* catch exceptions
*/
public Exception getException() {
return (catchExceptions) ? exception : null;
}
/** {@collect.stats}
* Returns any Throwable caught while executing the Runnable's <code>run()
* </code> method.
*
* @return A reference to the Throwable if one was thrown; null if no
* Throwable was thrown or if this InvocationEvent does not
* catch Throwables
* @since 1.5
*/
public Throwable getThrowable() {
return (catchExceptions) ? throwable : null;
}
/** {@collect.stats}
* Returns the timestamp of when this event occurred.
*
* @return this event's timestamp
* @since 1.4
*/
public long getWhen() {
return when;
}
/** {@collect.stats}
* Returns a parameter string identifying this event.
* This method is useful for event-logging and for debugging.
*
* @return A string identifying the event and its attributes
*/
public String paramString() {
String typeStr;
switch(id) {
case INVOCATION_DEFAULT:
typeStr = "INVOCATION_DEFAULT";
break;
default:
typeStr = "unknown type";
}
return typeStr + ",runnable=" + runnable + ",notifier=" + notifier +
",catchExceptions=" + catchExceptions + ",when=" + when;
}
}
|
Java
|
/*
* Copyright (c) 1996, 2007, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code 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
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package java.awt.event;
import java.awt.Component;
import java.awt.GraphicsEnvironment;
import java.awt.Point;
import java.awt.Toolkit;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.awt.IllegalComponentStateException;
/** {@collect.stats}
* An event which indicates that a mouse action occurred in a component.
* A mouse action is considered to occur in a particular component if and only
* if the mouse cursor is over the unobscured part of the component's bounds
* when the action happens.
* For lightweight components, such as Swing's components, mouse events
* are only dispatched to the component if the mouse event type has been
* enabled on the component. A mouse event type is enabled by adding the
* appropriate mouse-based {@code EventListener} to the component
* ({@link MouseListener} or {@link MouseMotionListener}), or by invoking
* {@link Component#enableEvents(long)} with the appropriate mask parameter
* ({@code AWTEvent.MOUSE_EVENT_MASK} or {@code AWTEvent.MOUSE_MOTION_EVENT_MASK}).
* If the mouse event type has not been enabled on the component, the
* corresponding mouse events are dispatched to the first ancestor that
* has enabled the mouse event type.
*<p>
* For example, if a {@code MouseListener} has been added to a component, or
* {@code enableEvents(AWTEvent.MOUSE_EVENT_MASK)} has been invoked, then all
* the events defined by {@code MouseListener} are dispatched to the component.
* On the other hand, if a {@code MouseMotionListener} has not been added and
* {@code enableEvents} has not been invoked with
* {@code AWTEvent.MOUSE_MOTION_EVENT_MASK}, then mouse motion events are not
* dispatched to the component. Instead the mouse motion events are
* dispatched to the first ancestors that has enabled mouse motion
* events.
* <P>
* This low-level event is generated by a component object for:
* <ul>
* <li>Mouse Events
* <ul>
* <li>a mouse button is pressed
* <li>a mouse button is released
* <li>a mouse button is clicked (pressed and released)
* <li>the mouse cursor enters the unobscured part of component's geometry
* <li>the mouse cursor exits the unobscured part of component's geometry
* </ul>
* <li> Mouse Motion Events
* <ul>
* <li>the mouse is moved
* <li>the mouse is dragged
* </ul>
* </ul>
* <P>
* A <code>MouseEvent</code> object is passed to every
* <code>MouseListener</code>
* or <code>MouseAdapter</code> object which is registered to receive
* the "interesting" mouse events using the component's
* <code>addMouseListener</code> method.
* (<code>MouseAdapter</code> objects implement the
* <code>MouseListener</code> interface.) Each such listener object
* gets a <code>MouseEvent</code> containing the mouse event.
* <P>
* A <code>MouseEvent</code> object is also passed to every
* <code>MouseMotionListener</code> or
* <code>MouseMotionAdapter</code> object which is registered to receive
* mouse motion events using the component's
* <code>addMouseMotionListener</code>
* method. (<code>MouseMotionAdapter</code> objects implement the
* <code>MouseMotionListener</code> interface.) Each such listener object
* gets a <code>MouseEvent</code> containing the mouse motion event.
* <P>
* When a mouse button is clicked, events are generated and sent to the
* registered <code>MouseListener</code>s.
* The state of modal keys can be retrieved using {@link InputEvent#getModifiers}
* and {@link InputEvent#getModifiersEx}.
* The button mask returned by {@link InputEvent#getModifiers} reflects
* only the button that changed state, not the current state of all buttons.
* (Note: Due to overlap in the values of ALT_MASK/BUTTON2_MASK and
* META_MASK/BUTTON3_MASK, this is not always true for mouse events involving
* modifier keys).
* To get the state of all buttons and modifier keys, use
* {@link InputEvent#getModifiersEx}.
* The button which has changed state is returned by {@link MouseEvent#getButton}
* <P>
* For example, if the first mouse button is pressed, events are sent in the
* following order:
* <PRE>
* <b >id </b > <b >modifiers </b > <b >button </b >
* <code>MOUSE_PRESSED</code>: <code>BUTTON1_MASK</code> <code>BUTTON1</code>
* <code>MOUSE_RELEASED</code>: <code>BUTTON1_MASK</code> <code>BUTTON1</code>
* <code>MOUSE_CLICKED</code>: <code>BUTTON1_MASK</code> <code>BUTTON1</code>
* </PRE>
* When multiple mouse buttons are pressed, each press, release, and click
* results in a separate event.
* <P>
* For example, if the user presses <b>button 1</b> followed by
* <b>button 2</b>, and then releases them in the same order,
* the following sequence of events is generated:
* <PRE>
* <b >id </b > <b >modifiers </b > <b >button </b >
* <code>MOUSE_PRESSED</code>: <code>BUTTON1_MASK</code> <code>BUTTON1</code>
* <code>MOUSE_PRESSED</code>: <code>BUTTON2_MASK</code> <code>BUTTON2</code>
* <code>MOUSE_RELEASED</code>: <code>BUTTON1_MASK</code> <code>BUTTON1</code>
* <code>MOUSE_CLICKED</code>: <code>BUTTON1_MASK</code> <code>BUTTON1</code>
* <code>MOUSE_RELEASED</code>: <code>BUTTON2_MASK</code> <code>BUTTON2</code>
* <code>MOUSE_CLICKED</code>: <code>BUTTON2_MASK</code> <code>BUTTON2</code>
* </PRE>
* If <b>button 2</b> is released first, the
* <code>MOUSE_RELEASED</code>/<code>MOUSE_CLICKED</code> pair
* for <code>BUTTON2_MASK</code> arrives first,
* followed by the pair for <code>BUTTON1_MASK</code>.
* <p>
*
* <code>MOUSE_DRAGGED</code> events are delivered to the <code>Component</code>
* in which the mouse button was pressed until the mouse button is released
* (regardless of whether the mouse position is within the bounds of the
* <code>Component</code>). Due to platform-dependent Drag&Drop implementations,
* <code>MOUSE_DRAGGED</code> events may not be delivered during a native
* Drag&Drop operation.
*
* In a multi-screen environment mouse drag events are delivered to the
* <code>Component</code> even if the mouse position is outside the bounds of the
* <code>GraphicsConfiguration</code> associated with that
* <code>Component</code>. However, the reported position for mouse drag events
* in this case may differ from the actual mouse position:
* <ul>
* <li>In a multi-screen environment without a virtual device:
* <br>
* The reported coordinates for mouse drag events are clipped to fit within the
* bounds of the <code>GraphicsConfiguration</code> associated with
* the <code>Component</code>.
* <li>In a multi-screen environment with a virtual device:
* <br>
* The reported coordinates for mouse drag events are clipped to fit within the
* bounds of the virtual device associated with the <code>Component</code>.
* </ul>
*
* @author Carl Quinn
* @see MouseAdapter
* @see MouseListener
* @see MouseMotionAdapter
* @see MouseMotionListener
* @see MouseWheelListener
* @see <a href="http://java.sun.com/docs/books/tutorial/post1.0/ui/mouselistener.html">Tutorial: Writing a Mouse Listener</a>
* @see <a href="http://java.sun.com/docs/books/tutorial/post1.0/ui/mousemotionlistener.html">Tutorial: Writing a Mouse Motion Listener</a>
*
* @since 1.1
*/
public class MouseEvent extends InputEvent {
/** {@collect.stats}
* The first number in the range of ids used for mouse events.
*/
public static final int MOUSE_FIRST = 500;
/** {@collect.stats}
* The last number in the range of ids used for mouse events.
*/
public static final int MOUSE_LAST = 507;
/** {@collect.stats}
* The "mouse clicked" event. This <code>MouseEvent</code>
* occurs when a mouse button is pressed and released.
*/
public static final int MOUSE_CLICKED = MOUSE_FIRST;
/** {@collect.stats}
* The "mouse pressed" event. This <code>MouseEvent</code>
* occurs when a mouse button is pushed down.
*/
public static final int MOUSE_PRESSED = 1 + MOUSE_FIRST; //Event.MOUSE_DOWN
/** {@collect.stats}
* The "mouse released" event. This <code>MouseEvent</code>
* occurs when a mouse button is let up.
*/
public static final int MOUSE_RELEASED = 2 + MOUSE_FIRST; //Event.MOUSE_UP
/** {@collect.stats}
* The "mouse moved" event. This <code>MouseEvent</code>
* occurs when the mouse position changes.
*/
public static final int MOUSE_MOVED = 3 + MOUSE_FIRST; //Event.MOUSE_MOVE
/** {@collect.stats}
* The "mouse entered" event. This <code>MouseEvent</code>
* occurs when the mouse cursor enters the unobscured part of component's
* geometry.
*/
public static final int MOUSE_ENTERED = 4 + MOUSE_FIRST; //Event.MOUSE_ENTER
/** {@collect.stats}
* The "mouse exited" event. This <code>MouseEvent</code>
* occurs when the mouse cursor exits the unobscured part of component's
* geometry.
*/
public static final int MOUSE_EXITED = 5 + MOUSE_FIRST; //Event.MOUSE_EXIT
/** {@collect.stats}
* The "mouse dragged" event. This <code>MouseEvent</code>
* occurs when the mouse position changes while a mouse button is pressed.
*/
public static final int MOUSE_DRAGGED = 6 + MOUSE_FIRST; //Event.MOUSE_DRAG
/** {@collect.stats}
* The "mouse wheel" event. This is the only <code>MouseWheelEvent</code>.
* It occurs when a mouse equipped with a wheel has its wheel rotated.
* @since 1.4
*/
public static final int MOUSE_WHEEL = 7 + MOUSE_FIRST;
/** {@collect.stats}
* Indicates no mouse buttons; used by {@link #getButton}.
* @since 1.4
*/
public static final int NOBUTTON = 0;
/** {@collect.stats}
* Indicates mouse button #1; used by {@link #getButton}.
* @since 1.4
*/
public static final int BUTTON1 = 1;
/** {@collect.stats}
* Indicates mouse button #2; used by {@link #getButton}.
* @since 1.4
*/
public static final int BUTTON2 = 2;
/** {@collect.stats}
* Indicates mouse button #3; used by {@link #getButton}.
* @since 1.4
*/
public static final int BUTTON3 = 3;
/** {@collect.stats}
* The mouse event's x coordinate.
* The x value is relative to the component that fired the event.
*
* @serial
* @see #getX()
*/
int x;
/** {@collect.stats}
* The mouse event's y coordinate.
* The y value is relative to the component that fired the event.
*
* @serial
* @see #getY()
*/
int y;
/** {@collect.stats}
* The mouse event's x absolute coordinate.
* In a virtual device multi-screen environment in which the
* desktop area could span multiple physical screen devices,
* this coordinate is relative to the virtual coordinate system.
* Otherwise, this coordinate is relative to the coordinate system
* associated with the Component's GraphicsConfiguration.
*
* @serial
*/
private int xAbs;
/** {@collect.stats}
* The mouse event's y absolute coordinate.
* In a virtual device multi-screen environment in which the
* desktop area could span multiple physical screen devices,
* this coordinate is relative to the virtual coordinate system.
* Otherwise, this coordinate is relative to the coordinate system
* associated with the Component's GraphicsConfiguration.
*
* @serial
*/
private int yAbs;
/** {@collect.stats}
* Indicates the number of quick consecutive clicks of
* a mouse button.
* clickCount will be valid for only three mouse events :<BR>
* <code>MOUSE_CLICKED</code>,
* <code>MOUSE_PRESSED</code> and
* <code>MOUSE_RELEASED</code>.
* For the above, the <code>clickCount</code> will be at least 1.
* For all other events the count will be 0.
*
* @serial
* @see #getClickCount().
*/
int clickCount;
/** {@collect.stats}
* Indicates which, if any, of the mouse buttons has changed state.
*
* The only legal values are the following constants:
* <code>NOBUTTON</code>,
* <code>BUTTON1</code>,
* <code>BUTTON2</code> or
* <code>BUTTON3</code>.
* @serial
* @see #getButton().
*/
int button;
/** {@collect.stats}
* A property used to indicate whether a Popup Menu
* should appear with a certain gestures.
* If <code>popupTrigger</code> = <code>false</code>,
* no popup menu should appear. If it is <code>true</code>
* then a popup menu should appear.
*
* @serial
* @see java.awt.PopupMenu
* @see #isPopupTrigger()
*/
boolean popupTrigger = false;
/*
* JDK 1.1 serialVersionUID
*/
private static final long serialVersionUID = -991214153494842848L;
static {
/* ensure that the necessary native libraries are loaded */
NativeLibLoader.loadLibraries();
if (!GraphicsEnvironment.isHeadless()) {
initIDs();
}
}
/** {@collect.stats}
* Initialize JNI field and method IDs for fields that may be
accessed from C.
*/
private static native void initIDs();
/** {@collect.stats}
* Returns the absolute x, y position of the event.
* In a virtual device multi-screen environment in which the
* desktop area could span multiple physical screen devices,
* these coordinates are relative to the virtual coordinate system.
* Otherwise, these coordinates are relative to the coordinate system
* associated with the Component's GraphicsConfiguration.
*
* @return a <code>Point</code> object containing the absolute x
* and y coordinates.
*
* @see java.awt.GraphicsConfiguration
* @since 1.6
*/
public Point getLocationOnScreen(){
return new Point(xAbs, yAbs);
}
/** {@collect.stats}
* Returns the absolute horizontal x position of the event.
* In a virtual device multi-screen environment in which the
* desktop area could span multiple physical screen devices,
* this coordinate is relative to the virtual coordinate system.
* Otherwise, this coordinate is relative to the coordinate system
* associated with the Component's GraphicsConfiguration.
*
* @return x an integer indicating absolute horizontal position.
*
* @see java.awt.GraphicsConfiguration
* @since 1.6
*/
public int getXOnScreen() {
return xAbs;
}
/** {@collect.stats}
* Returns the absolute vertical y position of the event.
* In a virtual device multi-screen environment in which the
* desktop area could span multiple physical screen devices,
* this coordinate is relative to the virtual coordinate system.
* Otherwise, this coordinate is relative to the coordinate system
* associated with the Component's GraphicsConfiguration.
*
* @return y an integer indicating absolute vertical position.
*
* @see java.awt.GraphicsConfiguration
* @since 1.6
*/
public int getYOnScreen() {
return yAbs;
}
/** {@collect.stats}
* Constructs a <code>MouseEvent</code> object with the
* specified source component,
* type, modifiers, coordinates, and click count.
* <p>
* Note that passing in an invalid <code>id</code> results in
* unspecified behavior. Creating an invalid event (such
* as by using more than one of the old _MASKs, or modifier/button
* values which don't match) results in unspecified behavior.
* An invocation of the form
* <tt>MouseEvent(source, id, when, modifiers, x, y, clickCount, popupTrigger, button)</tt>
* behaves in exactly the same way as the invocation
* <tt> {@link #MouseEvent(Component, int, long, int, int, int,
* int, int, int, boolean, int) MouseEvent}(source, id, when, modifiers,
* x, y, xAbs, yAbs, clickCount, popupTrigger, button)</tt>
* where xAbs and yAbs defines as source's location on screen plus
* relative coordinates x and y.
* xAbs and yAbs are set to zero if the source is not showing.
* This method throws an
* <code>IllegalArgumentException</code> if <code>source</code>
* is <code>null</code>.
*
* @param source the <code>Component</code> that originated the event
* @param id the integer that identifies the event
* @param when a long int that gives the time the event occurred
* @param modifiers the modifier keys down during event (e.g. shift, ctrl,
* alt, meta)
* Either extended _DOWN_MASK or old _MASK modifiers
* should be used, but both models should not be mixed
* in one event. Use of the extended modifiers is
* preferred.
* @param x the horizontal x coordinate for the mouse location
* @param y the vertical y coordinate for the mouse location
* @param clickCount the number of mouse clicks associated with event
* @param popupTrigger a boolean, true if this event is a trigger for a
* popup menu
* @param button which of the mouse buttons has changed state.
* <code>NOBUTTON</code>,
* <code>BUTTON1</code>,
* <code>BUTTON2</code> or
* <code>BUTTON3</code>.
* @throws IllegalArgumentException if an invalid <code>button</code>
* value is passed in
* @throws IllegalArgumentException if <code>source</code> is null
* @since 1.4
*/
public MouseEvent(Component source, int id, long when, int modifiers,
int x, int y, int clickCount, boolean popupTrigger,
int button)
{
this(source, id, when, modifiers, x, y, 0, 0, clickCount, popupTrigger, button);
Point eventLocationOnScreen = new Point(0, 0);
try {
eventLocationOnScreen = source.getLocationOnScreen();
this.xAbs = eventLocationOnScreen.x + x;
this.yAbs = eventLocationOnScreen.y + y;
} catch (IllegalComponentStateException e){
this.xAbs = 0;
this.yAbs = 0;
}
}
/** {@collect.stats}
* Constructs a <code>MouseEvent</code> object with the
* specified source component,
* type, modifiers, coordinates, and click count.
* <p>Note that passing in an invalid <code>id</code> results in
* unspecified behavior.
* An invocation of the form
* <tt>MouseEvent(source, id, when, modifiers, x, y, clickCount, popupTrigger)</tt>
* behaves in exactly the same way as the invocation
* <tt> {@link #MouseEvent(Component, int, long, int, int, int,
* int, int, int, boolean, int) MouseEvent}(source, id, when, modifiers,
* x, y, xAbs, yAbs, clickCount, popupTrigger, MouseEvent.NOBUTTON)</tt>
* where xAbs and yAbs defines as source's location on screen plus
* relative coordinates x and y.
* xAbs and yAbs are set to zero if the source is not showing.
* This method throws an <code>IllegalArgumentException</code>
* if <code>source</code> is <code>null</code>.
*
* @param source the <code>Component</code> that originated the event
* @param id the integer that identifies the event
* @param when a long int that gives the time the event occurred
* @param modifiers the modifier keys down during event (e.g. shift, ctrl,
* alt, meta)
* Either extended _DOWN_MASK or old _MASK modifiers
* should be used, but both models should not be mixed
* in one event. Use of the extended modifiers is
* preferred.
* @param x the horizontal x coordinate for the mouse location
* @param y the vertical y coordinate for the mouse location
* @param clickCount the number of mouse clicks associated with event
* @param popupTrigger a boolean, true if this event is a trigger for a
* popup menu
* @throws IllegalArgumentException if <code>source</code> is null
*/
public MouseEvent(Component source, int id, long when, int modifiers,
int x, int y, int clickCount, boolean popupTrigger) {
this(source, id, when, modifiers, x, y, clickCount, popupTrigger, NOBUTTON);
}
/** {@collect.stats}
* Constructs a <code>MouseEvent</code> object with the
* specified source component,
* type, modifiers, coordinates, absolute coordinates, and click count.
* <p>
* Note that passing in an invalid <code>id</code> results in
* unspecified behavior. Creating an invalid event (such
* as by using more than one of the old _MASKs, or modifier/button
* values which don't match) results in unspecified behavior.
* Even if inconsistent values for relative and absolute coordinates are
* passed to the constructor, the mouse event instance is still
* created and no exception is thrown.
* This method throws an
* <code>IllegalArgumentException</code> if <code>source</code>
* is <code>null</code>.
*
* @param source the <code>Component</code> that originated the event
* @param id the integer that identifies the event
* @param when a long int that gives the time the event occurred
* @param modifiers the modifier keys down during event (e.g. shift, ctrl,
* alt, meta)
* Either extended _DOWN_MASK or old _MASK modifiers
* should be used, but both models should not be mixed
* in one event. Use of the extended modifiers is
* preferred.
* @param x the horizontal x coordinate for the mouse location
* @param y the vertical y coordinate for the mouse location
* @param xAbs the absolute horizontal x coordinate for the mouse location
* @param yAbs the absolute vertical y coordinate for the mouse location
* @param clickCount the number of mouse clicks associated with event
* @param popupTrigger a boolean, true if this event is a trigger for a
* popup menu
* @param button which of the mouse buttons has changed state.
* <code>NOBUTTON</code>,
* <code>BUTTON1</code>,
* <code>BUTTON2</code> or
* <code>BUTTON3</code>.
* @throws IllegalArgumentException if an invalid <code>button</code>
* value is passed in
* @throws IllegalArgumentException if <code>source</code> is null
* @since 1.6
*/
public MouseEvent(Component source, int id, long when, int modifiers,
int x, int y, int xAbs, int yAbs,
int clickCount, boolean popupTrigger, int button)
{
super(source, id, when, modifiers);
this.x = x;
this.y = y;
this.xAbs = xAbs;
this.yAbs = yAbs;
this.clickCount = clickCount;
this.popupTrigger = popupTrigger;
if (button < NOBUTTON || button >BUTTON3) {
throw new IllegalArgumentException("Invalid button value");
}
this.button = button;
if ((getModifiers() != 0) && (getModifiersEx() == 0)) {
setNewModifiers();
} else if ((getModifiers() == 0) &&
(getModifiersEx() != 0 || button != NOBUTTON))
{
setOldModifiers();
}
}
/** {@collect.stats}
* Returns the horizontal x position of the event relative to the
* source component.
*
* @return x an integer indicating horizontal position relative to
* the component
*/
public int getX() {
return x;
}
/** {@collect.stats}
* Returns the vertical y position of the event relative to the
* source component.
*
* @return y an integer indicating vertical position relative to
* the component
*/
public int getY() {
return y;
}
/** {@collect.stats}
* Returns the x,y position of the event relative to the source component.
*
* @return a <code>Point</code> object containing the x and y coordinates
* relative to the source component
*
*/
public Point getPoint() {
int x;
int y;
synchronized (this) {
x = this.x;
y = this.y;
}
return new Point(x, y);
}
/** {@collect.stats}
* Translates the event's coordinates to a new position
* by adding specified <code>x</code> (horizontal) and <code>y</code>
* (vertical) offsets.
*
* @param x the horizontal x value to add to the current x
* coordinate position
* @param y the vertical y value to add to the current y
coordinate position
*/
public synchronized void translatePoint(int x, int y) {
this.x += x;
this.y += y;
}
/** {@collect.stats}
* Returns the number of mouse clicks associated with this event.
*
* @return integer value for the number of clicks
*/
public int getClickCount() {
return clickCount;
}
/** {@collect.stats}
* Returns which, if any, of the mouse buttons has changed state.
*
* @return one of the following constants:
* <code>NOBUTTON</code>,
* <code>BUTTON1</code>,
* <code>BUTTON2</code> or
* <code>BUTTON3</code>.
* @since 1.4
*/
public int getButton() {
return button;
}
/** {@collect.stats}
* Returns whether or not this mouse event is the popup menu
* trigger event for the platform.
* <p><b>Note</b>: Popup menus are triggered differently
* on different systems. Therefore, <code>isPopupTrigger</code>
* should be checked in both <code>mousePressed</code>
* and <code>mouseReleased</code>
* for proper cross-platform functionality.
*
* @return boolean, true if this event is the popup menu trigger
* for this platform
*/
public boolean isPopupTrigger() {
return popupTrigger;
}
/** {@collect.stats}
* Returns a <code>String</code> describing the modifier keys and
* mouse buttons that were down during the event, such as "Shift",
* or "Ctrl+Shift". These strings can be localized by changing
* the <code>awt.properties</code> file.
* <p>
* Note that <code>InputEvent.ALT_MASK</code> and
* <code>InputEvent.BUTTON2_MASK</code> have the same value,
* so the string "Alt" is returned for both modifiers. Likewise,
* <code>InputEvent.META_MASK</code> and
* <code>InputEvent.BUTTON3_MASK</code> have the same value,
* so the string "Meta" is returned for both modifiers.
*
* @param modifiers a modifier mask describing the modifier keys and
* mouse buttons that were down during the event
* @return string a text description of the combination of modifier
* keys and mouse buttons that were down during the event
* @see InputEvent#getModifiersExText(int)
* @since 1.4
*/
public static String getMouseModifiersText(int modifiers) {
StringBuilder buf = new StringBuilder();
if ((modifiers & InputEvent.ALT_MASK) != 0) {
buf.append(Toolkit.getProperty("AWT.alt", "Alt"));
buf.append("+");
}
if ((modifiers & InputEvent.META_MASK) != 0) {
buf.append(Toolkit.getProperty("AWT.meta", "Meta"));
buf.append("+");
}
if ((modifiers & InputEvent.CTRL_MASK) != 0) {
buf.append(Toolkit.getProperty("AWT.control", "Ctrl"));
buf.append("+");
}
if ((modifiers & InputEvent.SHIFT_MASK) != 0) {
buf.append(Toolkit.getProperty("AWT.shift", "Shift"));
buf.append("+");
}
if ((modifiers & InputEvent.ALT_GRAPH_MASK) != 0) {
buf.append(Toolkit.getProperty("AWT.altGraph", "Alt Graph"));
buf.append("+");
}
if ((modifiers & InputEvent.BUTTON1_MASK) != 0) {
buf.append(Toolkit.getProperty("AWT.button1", "Button1"));
buf.append("+");
}
if ((modifiers & InputEvent.BUTTON2_MASK) != 0) {
buf.append(Toolkit.getProperty("AWT.button2", "Button2"));
buf.append("+");
}
if ((modifiers & InputEvent.BUTTON3_MASK) != 0) {
buf.append(Toolkit.getProperty("AWT.button3", "Button3"));
buf.append("+");
}
if (buf.length() > 0) {
buf.setLength(buf.length()-1); // remove trailing '+'
}
return buf.toString();
}
/** {@collect.stats}
* Returns a parameter string identifying this event.
* This method is useful for event-logging and for debugging.
*
* @return a string identifying the event and its attributes
*/
public String paramString() {
StringBuilder str = new StringBuilder(80);
switch(id) {
case MOUSE_PRESSED:
str.append("MOUSE_PRESSED");
break;
case MOUSE_RELEASED:
str.append("MOUSE_RELEASED");
break;
case MOUSE_CLICKED:
str.append("MOUSE_CLICKED");
break;
case MOUSE_ENTERED:
str.append("MOUSE_ENTERED");
break;
case MOUSE_EXITED:
str.append("MOUSE_EXITED");
break;
case MOUSE_MOVED:
str.append("MOUSE_MOVED");
break;
case MOUSE_DRAGGED:
str.append("MOUSE_DRAGGED");
break;
case MOUSE_WHEEL:
str.append("MOUSE_WHEEL");
break;
default:
str.append("unknown type");
}
// (x,y) coordinates
str.append(",(").append(x).append(",").append(y).append(")");
str.append(",absolute(").append(xAbs).append(",").append(yAbs).append(")");
str.append(",button=").append(getButton());
if (getModifiers() != 0) {
str.append(",modifiers=").append(getMouseModifiersText(modifiers));
}
if (getModifiersEx() != 0) {
str.append(",extModifiers=").append(getModifiersExText(modifiers));
}
str.append(",clickCount=").append(clickCount);
return str.toString();
}
/** {@collect.stats}
* Sets new modifiers by the old ones.
* Also sets button.
*/
private void setNewModifiers() {
if ((modifiers & BUTTON1_MASK) != 0) {
modifiers |= BUTTON1_DOWN_MASK;
}
if ((modifiers & BUTTON2_MASK) != 0) {
modifiers |= BUTTON2_DOWN_MASK;
}
if ((modifiers & BUTTON3_MASK) != 0) {
modifiers |= BUTTON3_DOWN_MASK;
}
if (id == MOUSE_PRESSED
|| id == MOUSE_RELEASED
|| id == MOUSE_CLICKED)
{
if ((modifiers & BUTTON1_MASK) != 0) {
button = BUTTON1;
modifiers &= ~BUTTON2_MASK & ~BUTTON3_MASK;
if (id != MOUSE_PRESSED) {
modifiers &= ~BUTTON1_DOWN_MASK;
}
} else if ((modifiers & BUTTON2_MASK) != 0) {
button = BUTTON2;
modifiers &= ~BUTTON1_MASK & ~BUTTON3_MASK;
if (id != MOUSE_PRESSED) {
modifiers &= ~BUTTON2_DOWN_MASK;
}
} else if ((modifiers & BUTTON3_MASK) != 0) {
button = BUTTON3;
modifiers &= ~BUTTON1_MASK & ~BUTTON2_MASK;
if (id != MOUSE_PRESSED) {
modifiers &= ~BUTTON3_DOWN_MASK;
}
}
}
if ((modifiers & InputEvent.ALT_MASK) != 0) {
modifiers |= InputEvent.ALT_DOWN_MASK;
}
if ((modifiers & InputEvent.META_MASK) != 0) {
modifiers |= InputEvent.META_DOWN_MASK;
}
if ((modifiers & InputEvent.SHIFT_MASK) != 0) {
modifiers |= InputEvent.SHIFT_DOWN_MASK;
}
if ((modifiers & InputEvent.CTRL_MASK) != 0) {
modifiers |= InputEvent.CTRL_DOWN_MASK;
}
if ((modifiers & InputEvent.ALT_GRAPH_MASK) != 0) {
modifiers |= InputEvent.ALT_GRAPH_DOWN_MASK;
}
}
/** {@collect.stats}
* Sets old modifiers by the new ones.
*/
private void setOldModifiers() {
if (id == MOUSE_PRESSED
|| id == MOUSE_RELEASED
|| id == MOUSE_CLICKED)
{
switch(button) {
case BUTTON1:
modifiers |= BUTTON1_MASK;
break;
case BUTTON2:
modifiers |= BUTTON2_MASK;
break;
case BUTTON3:
modifiers |= BUTTON3_MASK;
break;
}
} else {
if ((modifiers & BUTTON1_DOWN_MASK) != 0) {
modifiers |= BUTTON1_MASK;
}
if ((modifiers & BUTTON2_DOWN_MASK) != 0) {
modifiers |= BUTTON2_MASK;
}
if ((modifiers & BUTTON3_DOWN_MASK) != 0) {
modifiers |= BUTTON3_MASK;
}
}
if ((modifiers & ALT_DOWN_MASK) != 0) {
modifiers |= ALT_MASK;
}
if ((modifiers & META_DOWN_MASK) != 0) {
modifiers |= META_MASK;
}
if ((modifiers & SHIFT_DOWN_MASK) != 0) {
modifiers |= SHIFT_MASK;
}
if ((modifiers & CTRL_DOWN_MASK) != 0) {
modifiers |= CTRL_MASK;
}
if ((modifiers & ALT_GRAPH_DOWN_MASK) != 0) {
modifiers |= ALT_GRAPH_MASK;
}
}
/** {@collect.stats}
* Sets new modifiers by the old ones.
* @serial
*/
private void readObject(ObjectInputStream s)
throws IOException, ClassNotFoundException {
s.defaultReadObject();
if (getModifiers() != 0 && getModifiersEx() == 0) {
setNewModifiers();
}
}
}
|
Java
|
/*
* Copyright (c) 1996, 2007, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code 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
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package java.awt.event;
import java.awt.Component;
import java.awt.Rectangle;
/** {@collect.stats}
* The component-level paint event.
* This event is a special type which is used to ensure that
* paint/update method calls are serialized along with the other
* events delivered from the event queue. This event is not
* designed to be used with the Event Listener model; programs
* should continue to override paint/update methods in order
* render themselves properly.
*
* @author Amy Fowler
* @since 1.1
*/
public class PaintEvent extends ComponentEvent {
/** {@collect.stats}
* Marks the first integer id for the range of paint event ids.
*/
public static final int PAINT_FIRST = 800;
/** {@collect.stats}
* Marks the last integer id for the range of paint event ids.
*/
public static final int PAINT_LAST = 801;
/** {@collect.stats}
* The paint event type.
*/
public static final int PAINT = PAINT_FIRST;
/** {@collect.stats}
* The update event type.
*/
public static final int UPDATE = PAINT_FIRST + 1; //801
/** {@collect.stats}
* This is the rectangle that represents the area on the source
* component that requires a repaint.
* This rectangle should be non null.
*
* @serial
* @see java.awt.Rectangle
* @see #setUpdateRect(Rectangle)
* @see #getUpdateRect()
*/
Rectangle updateRect;
/*
* JDK 1.1 serialVersionUID
*/
private static final long serialVersionUID = 1267492026433337593L;
/** {@collect.stats}
* Constructs a <code>PaintEvent</code> object with the specified
* source component and type.
* <p>Note that passing in an invalid <code>id</code> results in
* unspecified behavior. This method throws an
* <code>IllegalArgumentException</code> if <code>source</code>
* is <code>null</code>.
*
* @param source the object where the event originated
* @param id the event type
* @param updateRect the rectangle area which needs to be repainted
* @throws IllegalArgumentException if <code>source</code> is null
*/
public PaintEvent(Component source, int id, Rectangle updateRect) {
super(source, id);
this.updateRect = updateRect;
}
/** {@collect.stats}
* Returns the rectangle representing the area which needs to be
* repainted in response to this event.
*/
public Rectangle getUpdateRect() {
return updateRect;
}
/** {@collect.stats}
* Sets the rectangle representing the area which needs to be
* repainted in response to this event.
* @param updateRect the rectangle area which needs to be repainted
*/
public void setUpdateRect(Rectangle updateRect) {
this.updateRect = updateRect;
}
public String paramString() {
String typeStr;
switch(id) {
case PAINT:
typeStr = "PAINT";
break;
case UPDATE:
typeStr = "UPDATE";
break;
default:
typeStr = "unknown type";
}
return typeStr + ",updateRect="+(updateRect != null ? updateRect.toString() : "null");
}
}
|
Java
|
/*
* Copyright (c) 1996, 2006, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code 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
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package java.awt.event;
/** {@collect.stats}
* An abstract adapter class for receiving mouse motion events.
* The methods in this class are empty. This class exists as
* convenience for creating listener objects.
* <P>
* Mouse motion events occur when a mouse is moved or dragged.
* (Many such events will be generated in a normal program.
* To track clicks and other mouse events, use the MouseAdapter.)
* <P>
* Extend this class to create a <code>MouseEvent</code> listener
* and override the methods for the events of interest. (If you implement the
* <code>MouseMotionListener</code> interface, you have to define all of
* the methods in it. This abstract class defines null methods for them
* all, so you can only have to define methods for events you care about.)
* <P>
* Create a listener object using the extended class and then register it with
* a component using the component's <code>addMouseMotionListener</code>
* method. When the mouse is moved or dragged, the relevant method in the
* listener object is invoked and the <code>MouseEvent</code> is passed to it.
*
* @author Amy Fowler
*
* @see MouseEvent
* @see MouseMotionListener
* @see <a href="http://java.sun.com/docs/books/tutorial/post1.0/ui/mousemotionlistener.html">Tutorial: Writing a Mouse Motion Listener</a>
*
* @since 1.1
*/
public abstract class MouseMotionAdapter implements MouseMotionListener {
/** {@collect.stats}
* Invoked when a mouse button is pressed on a component and then
* dragged. Mouse drag events will continue to be delivered to
* the component where the first originated until the mouse button is
* released (regardless of whether the mouse position is within the
* bounds of the component).
*/
public void mouseDragged(MouseEvent e) {}
/** {@collect.stats}
* Invoked when the mouse button has been moved on a component
* (with no buttons no down).
*/
public void mouseMoved(MouseEvent e) {}
}
|
Java
|
/*
* Copyright (c) 1996, 2007, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code 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
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package java.awt.event;
import java.awt.AWTEvent;
import java.awt.ItemSelectable;
/** {@collect.stats}
* A semantic event which indicates that an item was selected or deselected.
* This high-level event is generated by an ItemSelectable object (such as a
* List) when an item is selected or deselected by the user.
* The event is passed to every <code>ItemListener</code> object which
* registered to receive such events using the component's
* <code>addItemListener</code> method.
* <P>
* The object that implements the <code>ItemListener</code> interface gets
* this <code>ItemEvent</code> when the event occurs. The listener is
* spared the details of processing individual mouse movements and mouse
* clicks, and can instead process a "meaningful" (semantic) event like
* "item selected" or "item deselected".
*
* @author Carl Quinn
*
* @see java.awt.ItemSelectable
* @see ItemListener
* @see <a href="http://java.sun.com/docs/books/tutorial/post1.0/ui/itemlistener.html">Tutorial: Writing an Item Listener</a>
*
* @since 1.1
*/
public class ItemEvent extends AWTEvent {
/** {@collect.stats}
* The first number in the range of ids used for item events.
*/
public static final int ITEM_FIRST = 701;
/** {@collect.stats}
* The last number in the range of ids used for item events.
*/
public static final int ITEM_LAST = 701;
/** {@collect.stats}
* This event id indicates that an item's state changed.
*/
public static final int ITEM_STATE_CHANGED = ITEM_FIRST; //Event.LIST_SELECT
/** {@collect.stats}
* This state-change value indicates that an item was selected.
*/
public static final int SELECTED = 1;
/** {@collect.stats}
* This state-change-value indicates that a selected item was deselected.
*/
public static final int DESELECTED = 2;
/** {@collect.stats}
* The item whose selection state has changed.
*
* @serial
* @see #getItem()
*/
Object item;
/** {@collect.stats}
* <code>stateChange</code> indicates whether the <code>item</code>
* was selected or deselected.
*
* @serial
* @see #getStateChange()
*/
int stateChange;
/*
* JDK 1.1 serialVersionUID
*/
private static final long serialVersionUID = -608708132447206933L;
/** {@collect.stats}
* Constructs an <code>ItemEvent</code> object.
* <p>Note that passing in an invalid <code>id</code> results in
* unspecified behavior. This method throws an
* <code>IllegalArgumentException</code> if <code>source</code>
* is <code>null</code>.
*
* @param source the <code>ItemSelectable</code> object
* that originated the event
* @param id an integer that identifies the event type
* @param item an object -- the item affected by the event
* @param stateChange
* an integer that indicates whether the item was
* selected or deselected
* @throws IllegalArgumentException if <code>source</code> is null
*/
public ItemEvent(ItemSelectable source, int id, Object item, int stateChange) {
super(source, id);
this.item = item;
this.stateChange = stateChange;
}
/** {@collect.stats}
* Returns the originator of the event.
*
* @return the ItemSelectable object that originated the event.
*/
public ItemSelectable getItemSelectable() {
return (ItemSelectable)source;
}
/** {@collect.stats}
* Returns the item affected by the event.
*
* @return the item (object) that was affected by the event
*/
public Object getItem() {
return item;
}
/** {@collect.stats}
* Returns the type of state change (selected or deselected).
*
* @return an integer that indicates whether the item was selected
* or deselected
*
* @see #SELECTED
* @see #DESELECTED
*/
public int getStateChange() {
return stateChange;
}
/** {@collect.stats}
* Returns a parameter string identifying this item event.
* This method is useful for event-logging and for debugging.
*
* @return a string identifying the event and its attributes
*/
public String paramString() {
String typeStr;
switch(id) {
case ITEM_STATE_CHANGED:
typeStr = "ITEM_STATE_CHANGED";
break;
default:
typeStr = "unknown type";
}
String stateStr;
switch(stateChange) {
case SELECTED:
stateStr = "SELECTED";
break;
case DESELECTED:
stateStr = "DESELECTED";
break;
default:
stateStr = "unknown type";
}
return typeStr + ",item="+item + ",stateChange="+stateStr;
}
}
|
Java
|
/*
* Copyright (c) 1998, 2003, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code 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
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package java.awt.event;
import java.util.EventListener;
import java.awt.AWTEvent;
/** {@collect.stats}
* The listener interface for receiving notification of events
* dispatched to objects that are instances of Component or
* MenuComponent or their subclasses. Unlike the other EventListeners
* in this package, AWTEventListeners passively observe events
* being dispatched in the AWT, system-wide. Most applications
* should never use this class; applications which might use
* AWTEventListeners include event recorders for automated testing,
* and facilities such as the Java Accessibility package.
* <p>
* The class that is interested in monitoring AWT events
* implements this interface, and the object created with that
* class is registered with the Toolkit, using the Toolkit's
* <code>addAWTEventListener</code> method. When an event is
* dispatched anywhere in the AWT, that object's
* <code>eventDispatched</code> method is invoked.
*
* @see java.awt.AWTEvent
* @see java.awt.Toolkit#addAWTEventListener
* @see java.awt.Toolkit#removeAWTEventListener
*
* @author Fred Ecks
* @since 1.2
*/
public interface AWTEventListener extends EventListener {
/** {@collect.stats}
* Invoked when an event is dispatched in the AWT.
*/
public void eventDispatched(AWTEvent event);
}
|
Java
|
/*
* Copyright (c) 1996, 2006, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code 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
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package java.awt.event;
import java.util.EventListener;
/** {@collect.stats}
* The listener interface for receiving mouse motion events on a component.
* (For clicks and other mouse events, use the <code>MouseListener</code>.)
* <P>
* The class that is interested in processing a mouse motion event
* either implements this interface (and all the methods it
* contains) or extends the abstract <code>MouseMotionAdapter</code> class
* (overriding only the methods of interest).
* <P>
* The listener object created from that class is then registered with a
* component using the component's <code>addMouseMotionListener</code>
* method. A mouse motion event is generated when the mouse is moved
* or dragged. (Many such events will be generated). When a mouse motion event
* occurs, the relevant method in the listener object is invoked, and
* the <code>MouseEvent</code> is passed to it.
*
* @author Amy Fowler
*
* @see MouseMotionAdapter
* @see MouseEvent
* @see <a href="http://java.sun.com/docs/books/tutorial/post1.0/ui/mousemotionlistener.html">Tutorial: Writing a Mouse Motion Listener</a>
*
* @since 1.1
*/
public interface MouseMotionListener extends EventListener {
/** {@collect.stats}
* Invoked when a mouse button is pressed on a component and then
* dragged. <code>MOUSE_DRAGGED</code> events will continue to be
* delivered to the component where the drag originated until the
* mouse button is released (regardless of whether the mouse position
* is within the bounds of the component).
* <p>
* Due to platform-dependent Drag&Drop implementations,
* <code>MOUSE_DRAGGED</code> events may not be delivered during a native
* Drag&Drop operation.
*/
public void mouseDragged(MouseEvent e);
/** {@collect.stats}
* Invoked when the mouse cursor has been moved onto a component
* but no buttons have been pushed.
*/
public void mouseMoved(MouseEvent e);
}
|
Java
|
/*
* Copyright (c) 1997, 1999, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code 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
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package java.awt.event;
import java.util.EventListener;
/** {@collect.stats}
* The listener interface for receiving input method events. A text editing
* component has to install an input method event listener in order to work
* with input methods.
*
* <p>
* The text editing component also has to provide an instance of InputMethodRequests.
*
* @author JavaSoft Asia/Pacific
* @see InputMethodEvent
* @see java.awt.im.InputMethodRequests
* @since 1.2
*/
public interface InputMethodListener extends EventListener {
/** {@collect.stats}
* Invoked when the text entered through an input method has changed.
*/
void inputMethodTextChanged(InputMethodEvent event);
/** {@collect.stats}
* Invoked when the caret within composed text has changed.
*/
void caretPositionChanged(InputMethodEvent event);
}
|
Java
|
/*
* Copyright (c) 1996, 2006, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code 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
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package java.awt.event;
import java.util.EventListener;
/** {@collect.stats}
* The listener interface for receiving item events.
* The class that is interested in processing an item event
* implements this interface. The object created with that
* class is then registered with a component using the
* component's <code>addItemListener</code> method. When an
* item-selection event occurs, the listener object's
* <code>itemStateChanged</code> method is invoked.
*
* @author Amy Fowler
*
* @see java.awt.ItemSelectable
* @see ItemEvent
* @see <a href="http://java.sun.com/docs/books/tutorial/post1.0/ui/itemlistener.html">Tutorial: Writing an Item Listener</a>
*
* @since 1.1
*/
public interface ItemListener extends EventListener {
/** {@collect.stats}
* Invoked when an item has been selected or deselected by the user.
* The code written for this method performs the operations
* that need to occur when an item is selected (or deselected).
*/
void itemStateChanged(ItemEvent e);
}
|
Java
|
/*
* Copyright (c) 1998, 2002, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code 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
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package java.awt.event;
class NativeLibLoader {
/** {@collect.stats}
* This is copied from java.awt.Toolkit since we need the library
* loaded in sun.awt.image also:
*
* WARNING: This is a temporary workaround for a problem in the
* way the AWT loads native libraries. A number of classes in this
* package (sun.awt.image) have a native method, initIDs(),
* which initializes
* the JNI field and method ids used in the native portion of
* their implementation.
*
* Since the use and storage of these ids is done by the
* implementation libraries, the implementation of these method is
* provided by the particular AWT implementations (for example,
* "Toolkit"s/Peer), such as Motif, Microsoft Windows, or Tiny. The
* problem is that this means that the native libraries must be
* loaded by the java.* classes, which do not necessarily know the
* names of the libraries to load. A better way of doing this
* would be to provide a separate library which defines java.awt.*
* initIDs, and exports the relevant symbols out to the
* implementation libraries.
*
* For now, we know it's done by the implementation, and we assume
* that the name of the library is "awt". -br.
*/
static void loadLibraries() {
java.security.AccessController.doPrivileged(
new sun.security.action.LoadLibraryAction("awt"));
}
}
|
Java
|
/*
* Copyright (c) 1996, 2007, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code 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
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package java.awt.event;
import java.awt.Adjustable;
import java.awt.AWTEvent;
/** {@collect.stats}
* The adjustment event emitted by Adjustable objects.
* @see java.awt.Adjustable
* @see AdjustmentListener
*
* @author Amy Fowler
* @since 1.1
*/
public class AdjustmentEvent extends AWTEvent {
/** {@collect.stats}
* Marks the first integer id for the range of adjustment event ids.
*/
public static final int ADJUSTMENT_FIRST = 601;
/** {@collect.stats}
* Marks the last integer id for the range of adjustment event ids.
*/
public static final int ADJUSTMENT_LAST = 601;
/** {@collect.stats}
* The adjustment value changed event.
*/
public static final int ADJUSTMENT_VALUE_CHANGED = ADJUSTMENT_FIRST; //Event.SCROLL_LINE_UP
/** {@collect.stats}
* The unit increment adjustment type.
*/
public static final int UNIT_INCREMENT = 1;
/** {@collect.stats}
* The unit decrement adjustment type.
*/
public static final int UNIT_DECREMENT = 2;
/** {@collect.stats}
* The block decrement adjustment type.
*/
public static final int BLOCK_DECREMENT = 3;
/** {@collect.stats}
* The block increment adjustment type.
*/
public static final int BLOCK_INCREMENT = 4;
/** {@collect.stats}
* The absolute tracking adjustment type.
*/
public static final int TRACK = 5;
/** {@collect.stats}
* The adjustable object that fired the event.
*
* @serial
* @see #getAdjustable
*/
Adjustable adjustable;
/** {@collect.stats}
* <code>value</code> will contain the new value of the
* adjustable object. This value will always be in a
* range associated adjustable object.
*
* @serial
* @see #getValue
*/
int value;
/** {@collect.stats}
* The <code>adjustmentType</code> describes how the adjustable
* object value has changed.
* This value can be increased/decreased by a block or unit amount
* where the block is associated with page increments/decrements,
* and a unit is associated with line increments/decrements.
*
* @serial
* @see #getAdjustmentType
*/
int adjustmentType;
/** {@collect.stats}
* The <code>isAdjusting</code> is true if the event is one
* of the series of multiple adjustment events.
*
* @since 1.4
* @serial
* @see #getValueIsAdjusting
*/
boolean isAdjusting;
/*
* JDK 1.1 serialVersionUID
*/
private static final long serialVersionUID = 5700290645205279921L;
/** {@collect.stats}
* Constructs an <code>AdjustmentEvent</code> object with the
* specified <code>Adjustable</code> source, event type,
* adjustment type, and value.
* <p>Note that passing in an invalid <code>id</code> results in
* unspecified behavior. This method throws an
* <code>IllegalArgumentException</code> if <code>source</code>
* is <code>null</code>.
*
* @param source the <code>Adjustable</code> object where the
* event originated
* @param id the event type
* @param type the adjustment type
* @param value the current value of the adjustment
* @throws IllegalArgumentException if <code>source</code> is null
*/
public AdjustmentEvent(Adjustable source, int id, int type, int value) {
this(source, id, type, value, false);
}
/** {@collect.stats}
* Constructs an <code>AdjustmentEvent</code> object with the
* specified Adjustable source, event type, adjustment type, and value.
* <p>Note that passing in an invalid <code>id</code> results in
* unspecified behavior. This method throws an
* <code>IllegalArgumentException</code> if <code>source</code>
* is <code>null</code>.
*
* @param source the <code>Adjustable</code> object where the
* event originated
* @param id the event type
* @param type the adjustment type
* @param value the current value of the adjustment
* @param isAdjusting <code>true</code> if the event is one
* of a series of multiple adjusting events,
* otherwise <code>false</code>
* @throws IllegalArgumentException if <code>source</code> is null
* @since 1.4
*/
public AdjustmentEvent(Adjustable source, int id, int type, int value, boolean isAdjusting) {
super(source, id);
adjustable = source;
this.adjustmentType = type;
this.value = value;
this.isAdjusting = isAdjusting;
}
/** {@collect.stats}
* Returns the <code>Adjustable</code> object where this event originated.
*
* @return the <code>Adjustable</code> object where this event originated
*/
public Adjustable getAdjustable() {
return adjustable;
}
/** {@collect.stats}
* Returns the current value in the adjustment event.
*
* @return the current value in the adjustment event
*/
public int getValue() {
return value;
}
/** {@collect.stats}
* Returns the type of adjustment which caused the value changed
* event. It will have one of the following values:
* <ul>
* <li>{@link #UNIT_INCREMENT}
* <li>{@link #UNIT_DECREMENT}
* <li>{@link #BLOCK_INCREMENT}
* <li>{@link #BLOCK_DECREMENT}
* <li>{@link #TRACK}
* </ul>
* @return one of the adjustment values listed above
*/
public int getAdjustmentType() {
return adjustmentType;
}
/** {@collect.stats}
* Returns <code>true</code> if this is one of multiple
* adjustment events.
*
* @return <code>true</code> if this is one of multiple
* adjustment events, otherwise returns <code>false</code>
* @since 1.4
*/
public boolean getValueIsAdjusting() {
return isAdjusting;
}
public String paramString() {
String typeStr;
switch(id) {
case ADJUSTMENT_VALUE_CHANGED:
typeStr = "ADJUSTMENT_VALUE_CHANGED";
break;
default:
typeStr = "unknown type";
}
String adjTypeStr;
switch(adjustmentType) {
case UNIT_INCREMENT:
adjTypeStr = "UNIT_INCREMENT";
break;
case UNIT_DECREMENT:
adjTypeStr = "UNIT_DECREMENT";
break;
case BLOCK_INCREMENT:
adjTypeStr = "BLOCK_INCREMENT";
break;
case BLOCK_DECREMENT:
adjTypeStr = "BLOCK_DECREMENT";
break;
case TRACK:
adjTypeStr = "TRACK";
break;
default:
adjTypeStr = "unknown type";
}
return typeStr
+ ",adjType="+adjTypeStr
+ ",value="+value
+ ",isAdjusting="+isAdjusting;
}
}
|
Java
|
/*
* Copyright (c) 1996, 2003, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code 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
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package java.awt.event;
import java.util.EventListener;
/** {@collect.stats}
* The listener interface for receiving window events.
* The class that is interested in processing a window event
* either implements this interface (and all the methods it
* contains) or extends the abstract <code>WindowAdapter</code> class
* (overriding only the methods of interest).
* The listener object created from that class is then registered with a
* Window using the window's <code>addWindowListener</code>
* method. When the window's status changes by virtue of being opened,
* closed, activated or deactivated, iconified or deiconified,
* the relevant method in the listener object is invoked, and the
* <code>WindowEvent</code> is passed to it.
*
* @author Carl Quinn
*
* @see WindowAdapter
* @see WindowEvent
* @see <a href="http://java.sun.com/docs/books/tutorial/uiswing/events/windowlistener.html">Tutorial: How to Write Window Listeners</a>
*
* @since 1.1
*/
public interface WindowListener extends EventListener {
/** {@collect.stats}
* Invoked the first time a window is made visible.
*/
public void windowOpened(WindowEvent e);
/** {@collect.stats}
* Invoked when the user attempts to close the window
* from the window's system menu.
*/
public void windowClosing(WindowEvent e);
/** {@collect.stats}
* Invoked when a window has been closed as the result
* of calling dispose on the window.
*/
public void windowClosed(WindowEvent e);
/** {@collect.stats}
* Invoked when a window is changed from a normal to a
* minimized state. For many platforms, a minimized window
* is displayed as the icon specified in the window's
* iconImage property.
* @see java.awt.Frame#setIconImage
*/
public void windowIconified(WindowEvent e);
/** {@collect.stats}
* Invoked when a window is changed from a minimized
* to a normal state.
*/
public void windowDeiconified(WindowEvent e);
/** {@collect.stats}
* Invoked when the Window is set to be the active Window. Only a Frame or
* a Dialog can be the active Window. The native windowing system may
* denote the active Window or its children with special decorations, such
* as a highlighted title bar. The active Window is always either the
* focused Window, or the first Frame or Dialog that is an owner of the
* focused Window.
*/
public void windowActivated(WindowEvent e);
/** {@collect.stats}
* Invoked when a Window is no longer the active Window. Only a Frame or a
* Dialog can be the active Window. The native windowing system may denote
* the active Window or its children with special decorations, such as a
* highlighted title bar. The active Window is always either the focused
* Window, or the first Frame or Dialog that is an owner of the focused
* Window.
*/
public void windowDeactivated(WindowEvent e);
}
|
Java
|
/*
* Copyright (c) 1996, 2007, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code 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
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package java.awt.event;
import java.awt.Container;
import java.awt.Component;
/** {@collect.stats}
* A low-level event which indicates that a container's contents
* changed because a component was added or removed.
* <P>
* Container events are provided for notification purposes ONLY;
* The AWT will automatically handle changes to the containers
* contents internally so that the program works properly regardless of
* whether the program is receiving these events or not.
* <P>
* This low-level event is generated by a container object (such as a
* Panel) when a component is added to it or removed from it.
* The event is passed to every <code>ContainerListener</code>
* or <code>ContainerAdapter</code> object which registered to receive such
* events using the component's <code>addContainerListener</code> method.
* (<code>ContainerAdapter</code> objects implement the
* <code>ContainerListener</code> interface.) Each such listener object
* gets this <code>ContainerEvent</code> when the event occurs.
*
* @see ContainerAdapter
* @see ContainerListener
* @see <a href="http://java.sun.com/docs/books/tutorial/post1.0/ui/containerlistener.html">Tutorial: Writing a Container Listener</a>
*
* @author Tim Prinzing
* @author Amy Fowler
* @since 1.1
*/
public class ContainerEvent extends ComponentEvent {
/** {@collect.stats}
* The first number in the range of ids used for container events.
*/
public static final int CONTAINER_FIRST = 300;
/** {@collect.stats}
* The last number in the range of ids used for container events.
*/
public static final int CONTAINER_LAST = 301;
/** {@collect.stats}
* This event indicates that a component was added to the container.
*/
public static final int COMPONENT_ADDED = CONTAINER_FIRST;
/** {@collect.stats}
* This event indicates that a component was removed from the container.
*/
public static final int COMPONENT_REMOVED = 1 + CONTAINER_FIRST;
/** {@collect.stats}
* The non-null component that is being added or
* removed from the Container.
*
* @serial
* @see #getChild()
*/
Component child;
/*
* JDK 1.1 serialVersionUID
*/
private static final long serialVersionUID = -4114942250539772041L;
/** {@collect.stats}
* Constructs a <code>ContainerEvent</code> object.
* <p>Note that passing in an invalid <code>id</code> results in
* unspecified behavior. This method throws an
* <code>IllegalArgumentException</code> if <code>source</code>
* is <code>null</code>.
*
* @param source the <code>Component</code> object (container)
* that originated the event
* @param id an integer indicating the type of event
* @param child the component that was added or removed
* @throws IllegalArgumentException if <code>source</code> is null
*/
public ContainerEvent(Component source, int id, Component child) {
super(source, id);
this.child = child;
}
/** {@collect.stats}
* Returns the originator of the event.
*
* @return the <code>Container</code> object that originated
* the event, or <code>null</code> if the object is not a
* <code>Container</code>.
*/
public Container getContainer() {
return (source instanceof Container) ? (Container)source : null;
}
/** {@collect.stats}
* Returns the component that was affected by the event.
*
* @return the Component object that was added or removed
*/
public Component getChild() {
return child;
}
/** {@collect.stats}
* Returns a parameter string identifying this event.
* This method is useful for event-logging and for debugging.
*
* @return a string identifying the event and its attributes
*/
public String paramString() {
String typeStr;
switch(id) {
case COMPONENT_ADDED:
typeStr = "COMPONENT_ADDED";
break;
case COMPONENT_REMOVED:
typeStr = "COMPONENT_REMOVED";
break;
default:
typeStr = "unknown type";
}
return typeStr + ",child="+child.getName();
}
}
|
Java
|
/*
* Copyright (c) 1996, 2006, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code 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
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package java.awt.event;
import java.util.EventListener;
/** {@collect.stats}
* The listener interface for receiving container events.
* The class that is interested in processing a container event
* either implements this interface (and all the methods it
* contains) or extends the abstract <code>ContainerAdapter</code> class
* (overriding only the methods of interest).
* The listener object created from that class is then registered with a
* component using the component's <code>addContainerListener</code>
* method. When the container's contents change because a component
* has been added or removed, the relevant method in the listener object
* is invoked, and the <code>ContainerEvent</code> is passed to it.
* <P>
* Container events are provided for notification purposes ONLY;
* The AWT will automatically handle add and remove operations
* internally so the program works properly regardless of
* whether the program registers a <code>ComponentListener</code> or not.
*
* @see ContainerAdapter
* @see ContainerEvent
* @see <a href="http://java.sun.com/docs/books/tutorial/post1.0/ui/containerlistener.html">Tutorial: Writing a Container Listener</a>
*
* @author Tim Prinzing
* @author Amy Fowler
* @since 1.1
*/
public interface ContainerListener extends EventListener {
/** {@collect.stats}
* Invoked when a component has been added to the container.
*/
public void componentAdded(ContainerEvent e);
/** {@collect.stats}
* Invoked when a component has been removed from the container.
*/
public void componentRemoved(ContainerEvent e);
}
|
Java
|
/*
* Copyright (c) 1996, 2007, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code 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
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package java.awt.event;
import java.awt.Component;
import sun.awt.AppContext;
import sun.awt.SunToolkit;
/** {@collect.stats}
* A low-level event which indicates that a Component has gained or lost the
* input focus. This low-level event is generated by a Component (such as a
* TextField). The event is passed to every <code>FocusListener</code> or
* <code>FocusAdapter</code> object which registered to receive such events
* using the Component's <code>addFocusListener</code> method. (<code>
* FocusAdapter</code> objects implement the <code>FocusListener</code>
* interface.) Each such listener object gets this <code>FocusEvent</code> when
* the event occurs.
* <p>
* There are two levels of focus events: permanent and temporary. Permanent
* focus change events occur when focus is directly moved from one Component to
* another, such as through a call to requestFocus() or as the user uses the
* TAB key to traverse Components. Temporary focus change events occur when
* focus is temporarily lost for a Component as the indirect result of another
* operation, such as Window deactivation or a Scrollbar drag. In this case,
* the original focus state will automatically be restored once that operation
* is finished, or, for the case of Window deactivation, when the Window is
* reactivated. Both permanent and temporary focus events are delivered using
* the FOCUS_GAINED and FOCUS_LOST event ids; the level may be distinguished in
* the event using the isTemporary() method.
*
* @see FocusAdapter
* @see FocusListener
* @see <a href="http://java.sun.com/docs/books/tutorial/post1.0/ui/focuslistener.html">Tutorial: Writing a Focus Listener</a>
*
* @author Carl Quinn
* @author Amy Fowler
* @since 1.1
*/
public class FocusEvent extends ComponentEvent {
/** {@collect.stats}
* The first number in the range of ids used for focus events.
*/
public static final int FOCUS_FIRST = 1004;
/** {@collect.stats}
* The last number in the range of ids used for focus events.
*/
public static final int FOCUS_LAST = 1005;
/** {@collect.stats}
* This event indicates that the Component is now the focus owner.
*/
public static final int FOCUS_GAINED = FOCUS_FIRST; //Event.GOT_FOCUS
/** {@collect.stats}
* This event indicates that the Component is no longer the focus owner.
*/
public static final int FOCUS_LOST = 1 + FOCUS_FIRST; //Event.LOST_FOCUS
/** {@collect.stats}
* A focus event can have two different levels, permanent and temporary.
* It will be set to true if some operation takes away the focus
* temporarily and intends on getting it back once the event is completed.
* Otherwise it will be set to false.
*
* @serial
* @see #isTemporary
*/
boolean temporary;
/** {@collect.stats}
* The other Component involved in this focus change. For a FOCUS_GAINED
* event, this is the Component that lost focus. For a FOCUS_LOST event,
* this is the Component that gained focus. If this focus change occurs
* with a native application, a Java application in a different VM, or with
* no other Component, then the opposite Component is null.
*
* @see #getOppositeComponent
* @since 1.4
*/
transient Component opposite;
/*
* JDK 1.1 serialVersionUID
*/
private static final long serialVersionUID = 523753786457416396L;
/** {@collect.stats}
* Constructs a <code>FocusEvent</code> object with the
* specified temporary state and opposite <code>Component</code>.
* The opposite <code>Component</code> is the other
* <code>Component</code> involved in this focus change.
* For a <code>FOCUS_GAINED</code> event, this is the
* <code>Component</code> that lost focus. For a
* <code>FOCUS_LOST</code> event, this is the <code>Component</code>
* that gained focus. If this focus change occurs with a native
* application, with a Java application in a different VM,
* or with no other <code>Component</code>, then the opposite
* <code>Component</code> is <code>null</code>.
* <p>Note that passing in an invalid <code>id</code> results in
* unspecified behavior. This method throws an
* <code>IllegalArgumentException</code> if <code>source</code>
* is <code>null</code>.
*
* @param source the <code>Component</code> that originated the event
* @param id <code>FOCUS_GAINED</code> or <code>FOCUS_LOST</code>
* @param temporary <code>true</code> if the focus change is temporary;
* <code>false</code> otherwise
* @param opposite the other Component involved in the focus change,
* or <code>null</code>
* @throws IllegalArgumentException if <code>source</code> is null
* @since 1.4
*/
public FocusEvent(Component source, int id, boolean temporary,
Component opposite) {
super(source, id);
this.temporary = temporary;
this.opposite = opposite;
}
/** {@collect.stats}
* Constructs a <code>FocusEvent</code> object and identifies
* whether or not the change is temporary.
* <p>Note that passing in an invalid <code>id</code> results in
* unspecified behavior. This method throws an
* <code>IllegalArgumentException</code> if <code>source</code>
* is <code>null</code>.
*
* @param source the <code>Component</code> that originated the event
* @param id an integer indicating the type of event
* @param temporary <code>true</code> if the focus change is temporary;
* <code>false</code> otherwise
* @throws IllegalArgumentException if <code>source</code> is null
*/
public FocusEvent(Component source, int id, boolean temporary) {
this(source, id, temporary, null);
}
/** {@collect.stats}
* Constructs a <code>FocusEvent</code> object and identifies it
* as a permanent change in focus.
* <p>Note that passing in an invalid <code>id</code> results in
* unspecified behavior. This method throws an
* <code>IllegalArgumentException</code> if <code>source</code>
* is <code>null</code>.
*
* @param source the <code>Component</code> that originated the event
* @param id an integer indicating the type of event
* @throws IllegalArgumentException if <code>source</code> is null
*/
public FocusEvent(Component source, int id) {
this(source, id, false);
}
/** {@collect.stats}
* Identifies the focus change event as temporary or permanent.
*
* @return <code>true</code> if the focus change is temporary;
* <code>false</code> otherwise
*/
public boolean isTemporary() {
return temporary;
}
/** {@collect.stats}
* Returns the other Component involved in this focus change. For a
* FOCUS_GAINED event, this is the Component that lost focus. For a
* FOCUS_LOST event, this is the Component that gained focus. If this
* focus change occurs with a native application, with a Java application
* in a different VM or context, or with no other Component, then null is
* returned.
*
* @return the other Component involved in the focus change, or null
* @since 1.4
*/
public Component getOppositeComponent() {
if (opposite == null) {
return null;
}
return (SunToolkit.targetToAppContext(opposite) ==
AppContext.getAppContext())
? opposite
: null;
}
/** {@collect.stats}
* Returns a parameter string identifying this event.
* This method is useful for event-logging and for debugging.
*
* @return a string identifying the event and its attributes
*/
public String paramString() {
String typeStr;
switch(id) {
case FOCUS_GAINED:
typeStr = "FOCUS_GAINED";
break;
case FOCUS_LOST:
typeStr = "FOCUS_LOST";
break;
default:
typeStr = "unknown type";
}
return typeStr + (temporary ? ",temporary" : ",permanent") +
",opposite=" + getOppositeComponent();
}
}
|
Java
|
/*
* Copyright (c) 2000, 2006, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code 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
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package java.awt.event;
import java.util.EventListener;
/** {@collect.stats}
* The listener interface for receiving <code>WindowEvents</code>, including
* <code>WINDOW_GAINED_FOCUS</code> and <code>WINDOW_LOST_FOCUS</code> events.
* The class that is interested in processing a <code>WindowEvent</code>
* either implements this interface (and
* all the methods it contains) or extends the abstract
* <code>WindowAdapter</code> class (overriding only the methods of interest).
* The listener object created from that class is then registered with a
* <code>Window</code>
* using the <code>Window</code>'s <code>addWindowFocusListener</code> method.
* When the <code>Window</code>'s
* status changes by virtue of it being opened, closed, activated, deactivated,
* iconified, or deiconified, or by focus being transfered into or out of the
* <code>Window</code>, the relevant method in the listener object is invoked,
* and the <code>WindowEvent</code> is passed to it.
*
* @author David Mendenhall
*
* @see WindowAdapter
* @see WindowEvent
* @see <a href="http://java.sun.com/docs/books/tutorial/post1.0/ui/windowlistener.html">Tutorial: Writing a Window Listener</a>
*
* @since 1.4
*/
public interface WindowFocusListener extends EventListener {
/** {@collect.stats}
* Invoked when the Window is set to be the focused Window, which means
* that the Window, or one of its subcomponents, will receive keyboard
* events.
*/
public void windowGainedFocus(WindowEvent e);
/** {@collect.stats}
* Invoked when the Window is no longer the focused Window, which means
* that keyboard events will no longer be delivered to the Window or any of
* its subcomponents.
*/
public void windowLostFocus(WindowEvent e);
}
|
Java
|
/*
* Copyright (c) 1996, 2006, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code 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
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package java.awt.event;
/** {@collect.stats}
* An abstract adapter class for receiving container events.
* The methods in this class are empty. This class exists as
* convenience for creating listener objects.
* <P>
* Extend this class to create a <code>ContainerEvent</code> listener
* and override the methods for the events of interest. (If you implement the
* <code>ContainerListener</code> interface, you have to define all of
* the methods in it. This abstract class defines null methods for them
* all, so you can only have to define methods for events you care about.)
* <P>
* Create a listener object using the extended class and then register it with
* a component using the component's <code>addContainerListener</code>
* method. When the container's contents change because a component has
* been added or removed, the relevant method in the listener object is invoked,
* and the <code>ContainerEvent</code> is passed to it.
*
* @see ContainerEvent
* @see ContainerListener
* @see <a href="http://java.sun.com/docs/books/tutorial/post1.0/ui/containerlistener.html">Tutorial: Writing a Container Listener</a>
*
* @author Amy Fowler
* @since 1.1
*/
public abstract class ContainerAdapter implements ContainerListener {
/** {@collect.stats}
* Invoked when a component has been added to the container.
*/
public void componentAdded(ContainerEvent e) {}
/** {@collect.stats}
* Invoked when a component has been removed from the container.
*/
public void componentRemoved(ContainerEvent e) {}
}
|
Java
|
/*
* Copyright (c) 1999, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code 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
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package java.awt.event;
import java.util.EventListener;
/** {@collect.stats}
* The listener interface for receiving hierarchy changed events.
* The class that is interested in processing a hierarchy changed event
* should implement this interface.
* The listener object created from that class is then registered with a
* Component using the Component's <code>addHierarchyListener</code>
* method. When the hierarchy to which the Component belongs changes, the
* <code>hierarchyChanged</code> method in the listener object is invoked,
* and the <code>HierarchyEvent</code> is passed to it.
* <p>
* Hierarchy events are provided for notification purposes ONLY;
* The AWT will automatically handle changes to the hierarchy internally so
* that GUI layout, displayability, and visibility work properly regardless
* of whether a program registers a <code>HierarchyListener</code> or not.
*
* @author David Mendenhall
* @see HierarchyEvent
* @since 1.3
*/
public interface HierarchyListener extends EventListener {
/** {@collect.stats}
* Called when the hierarchy has been changed. To discern the actual
* type of change, call <code>HierarchyEvent.getChangeFlags()</code>.
*
* @see HierarchyEvent#getChangeFlags()
*/
public void hierarchyChanged(HierarchyEvent e);
}
|
Java
|
/*
* Copyright (c) 2000, 2003, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code 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
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package java.awt.event;
import java.util.EventListener;
/** {@collect.stats}
* The listener interface for receiving mouse wheel events on a component.
* (For clicks and other mouse events, use the <code>MouseListener</code>.
* For mouse movement and drags, use the <code>MouseMotionListener</code>.)
* <P>
* The class that is interested in processing a mouse wheel event
* implements this interface (and all the methods it contains).
* <P>
* The listener object created from that class is then registered with a
* component using the component's <code>addMouseWheelListener</code>
* method. A mouse wheel event is generated when the mouse wheel is rotated.
* When a mouse wheel event occurs, that object's <code>mouseWheelMoved</code>
* method is invoked.
* <p>
* For information on how mouse wheel events are dispatched, see
* the class description for {@link MouseWheelEvent}.
*
* @author Brent Christian
* @see MouseWheelEvent
* @since 1.4
*/
public interface MouseWheelListener extends EventListener {
/** {@collect.stats}
* Invoked when the mouse wheel is rotated.
* @see MouseWheelEvent
*/
public void mouseWheelMoved(MouseWheelEvent e);
}
|
Java
|
/*
* Copyright (c) 1996, 2006, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code 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
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package java.awt.event;
/** {@collect.stats}
* An abstract adapter class for receiving window events.
* The methods in this class are empty. This class exists as
* convenience for creating listener objects.
* <P>
* Extend this class to create a <code>WindowEvent</code> listener
* and override the methods for the events of interest. (If you implement the
* <code>WindowListener</code> interface, you have to define all of
* the methods in it. This abstract class defines null methods for them
* all, so you can only have to define methods for events you care about.)
* <P>
* Create a listener object using the extended class and then register it with
* a Window using the window's <code>addWindowListener</code>
* method. When the window's status changes by virtue of being opened,
* closed, activated or deactivated, iconified or deiconified,
* the relevant method in the listener
* object is invoked, and the <code>WindowEvent</code> is passed to it.
*
* @see WindowEvent
* @see WindowListener
* @see <a href="http://java.sun.com/docs/books/tutorial/post1.0/ui/windowlistener.html">Tutorial: Writing a Window Listener</a>
*
* @author Carl Quinn
* @author Amy Fowler
* @author David Mendenhall
* @since 1.1
*/
public abstract class WindowAdapter
implements WindowListener, WindowStateListener, WindowFocusListener
{
/** {@collect.stats}
* Invoked when a window has been opened.
*/
public void windowOpened(WindowEvent e) {}
/** {@collect.stats}
* Invoked when a window is in the process of being closed.
* The close operation can be overridden at this point.
*/
public void windowClosing(WindowEvent e) {}
/** {@collect.stats}
* Invoked when a window has been closed.
*/
public void windowClosed(WindowEvent e) {}
/** {@collect.stats}
* Invoked when a window is iconified.
*/
public void windowIconified(WindowEvent e) {}
/** {@collect.stats}
* Invoked when a window is de-iconified.
*/
public void windowDeiconified(WindowEvent e) {}
/** {@collect.stats}
* Invoked when a window is activated.
*/
public void windowActivated(WindowEvent e) {}
/** {@collect.stats}
* Invoked when a window is de-activated.
*/
public void windowDeactivated(WindowEvent e) {}
/** {@collect.stats}
* Invoked when a window state is changed.
* @since 1.4
*/
public void windowStateChanged(WindowEvent e) {}
/** {@collect.stats}
* Invoked when the Window is set to be the focused Window, which means
* that the Window, or one of its subcomponents, will receive keyboard
* events.
*
* @since 1.4
*/
public void windowGainedFocus(WindowEvent e) {}
/** {@collect.stats}
* Invoked when the Window is no longer the focused Window, which means
* that keyboard events will no longer be delivered to the Window or any of
* its subcomponents.
*
* @since 1.4
*/
public void windowLostFocus(WindowEvent e) {}
}
|
Java
|
/*
* Copyright (c) 1996, 2006, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code 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
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package java.awt.event;
import java.util.EventListener;
/** {@collect.stats}
* The listener interface for receiving "interesting" mouse events
* (press, release, click, enter, and exit) on a component.
* (To track mouse moves and mouse drags, use the
* <code>MouseMotionListener</code>.)
* <P>
* The class that is interested in processing a mouse event
* either implements this interface (and all the methods it
* contains) or extends the abstract <code>MouseAdapter</code> class
* (overriding only the methods of interest).
* <P>
* The listener object created from that class is then registered with a
* component using the component's <code>addMouseListener</code>
* method. A mouse event is generated when the mouse is pressed, released
* clicked (pressed and released). A mouse event is also generated when
* the mouse cursor enters or leaves a component. When a mouse event
* occurs, the relevant method in the listener object is invoked, and
* the <code>MouseEvent</code> is passed to it.
*
* @author Carl Quinn
*
* @see MouseAdapter
* @see MouseEvent
* @see <a href="http://java.sun.com/docs/books/tutorial/post1.0/ui/mouselistener.html">Tutorial: Writing a Mouse Listener</a>
*
* @since 1.1
*/
public interface MouseListener extends EventListener {
/** {@collect.stats}
* Invoked when the mouse button has been clicked (pressed
* and released) on a component.
*/
public void mouseClicked(MouseEvent e);
/** {@collect.stats}
* Invoked when a mouse button has been pressed on a component.
*/
public void mousePressed(MouseEvent e);
/** {@collect.stats}
* Invoked when a mouse button has been released on a component.
*/
public void mouseReleased(MouseEvent e);
/** {@collect.stats}
* Invoked when the mouse enters a component.
*/
public void mouseEntered(MouseEvent e);
/** {@collect.stats}
* Invoked when the mouse exits a component.
*/
public void mouseExited(MouseEvent e);
}
|
Java
|
/*
* Copyright (c) 1996, 1999, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code 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
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package java.awt.event;
import java.util.EventListener;
/** {@collect.stats}
* The listener interface for receiving adjustment events.
*
* @author Amy Fowler
* @since 1.1
*/
public interface AdjustmentListener extends EventListener {
/** {@collect.stats}
* Invoked when the value of the adjustable has changed.
*/
public void adjustmentValueChanged(AdjustmentEvent e);
}
|
Java
|
/*
* Copyright (c) 1996, 2007, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code 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
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package java.awt.event;
import java.awt.Event;
import java.awt.Component;
import java.awt.GraphicsEnvironment;
import java.awt.Toolkit;
import java.io.IOException;
import java.io.ObjectInputStream;
/** {@collect.stats}
* An event which indicates that a keystroke occurred in a component.
* <p>
* This low-level event is generated by a component object (such as a text
* field) when a key is pressed, released, or typed.
* The event is passed to every <code>KeyListener</code>
* or <code>KeyAdapter</code> object which registered to receive such
* events using the component's <code>addKeyListener</code> method.
* (<code>KeyAdapter</code> objects implement the
* <code>KeyListener</code> interface.) Each such listener object
* gets this <code>KeyEvent</code> when the event occurs.
* <p>
* <em>"Key typed" events</em> are higher-level and generally do not depend on
* the platform or keyboard layout. They are generated when a Unicode character
* is entered, and are the preferred way to find out about character input.
* In the simplest case, a key typed event is produced by a single key press
* (e.g., 'a'). Often, however, characters are produced by series of key
* presses (e.g., 'shift' + 'a'), and the mapping from key pressed events to
* key typed events may be many-to-one or many-to-many. Key releases are not
* usually necessary to generate a key typed event, but there are some cases
* where the key typed event is not generated until a key is released (e.g.,
* entering ASCII sequences via the Alt-Numpad method in Windows).
* No key typed events are generated for keys that don't generate Unicode
* characters (e.g., action keys, modifier keys, etc.).
* <p>
* The getKeyChar method always returns a valid Unicode character or
* CHAR_UNDEFINED. Character input is reported by KEY_TYPED events:
* KEY_PRESSED and KEY_RELEASED events are not necessarily associated
* with character input. Therefore, the result of the getKeyChar method
* is guaranteed to be meaningful only for KEY_TYPED events.
* <p>
* For key pressed and key released events, the getKeyCode method returns
* the event's keyCode. For key typed events, the getKeyCode method
* always returns VK_UNDEFINED.
*
* <p>
* <em>"Key pressed" and "key released" events</em> are lower-level and depend
* on the platform and keyboard layout. They are generated whenever a key is
* pressed or released, and are the only way to find out about keys that don't
* generate character input (e.g., action keys, modifier keys, etc.). The key
* being pressed or released is indicated by the getKeyCode method, which returns
* a virtual key code.
*
* <p>
* <em>Virtual key codes</em> are used to report which keyboard key has
* been pressed, rather than a character generated by the combination
* of one or more keystrokes (such as "A", which comes from shift and "a").
*
* <p>
* For example, pressing the Shift key will cause a KEY_PRESSED event
* with a VK_SHIFT keyCode, while pressing the 'a' key will result in
* a VK_A keyCode. After the 'a' key is released, a KEY_RELEASED event
* will be fired with VK_A. Separately, a KEY_TYPED event with a keyChar
* value of 'A' is generated.
*
* <p>
* Pressing and releasing a key on the keyboard results in the generating
* the following key events (in order):
* <PRE>
* {@code KEY_PRESSED}
* {@code KEY_TYPED} (is only generated if a valid Unicode character could be generated.)
* {@code KEY_RELEASED}
* </PRE>
*
* But in some cases (e.g. auto-repeat or input method is activated) the order
* could be different (and platform dependent).
*
* <p>
* Notes:
* <ul>
* <li>Key combinations which do not result in Unicode characters, such as action
* keys like F1 and the HELP key, do not generate KEY_TYPED events.
* <li>Not all keyboards or systems are capable of generating all
* virtual key codes. No attempt is made in Java to generate these keys
* artificially.
* <li>Virtual key codes do not identify a physical key: they depend on the
* platform and keyboard layout. For example, the key that generates VK_Q
* when using a U.S. keyboard layout will generate VK_A when using a French
* keyboard layout.
* <li>Not all characters have a keycode associated with them. For example,
* there is no keycode for the question mark because there is no keyboard
* for which it appears on the primary layer.
* <li>In order to support the platform-independent handling of action keys,
* the Java platform uses a few additional virtual key constants for functions
* that would otherwise have to be recognized by interpreting virtual key codes
* and modifiers. For example, for Japanese Windows keyboards, VK_ALL_CANDIDATES
* is returned instead of VK_CONVERT with the ALT modifier.
* <li>As specified in <a href="../doc-files/FocusSpec.html">Focus Specification</a>
* key events are dispatched to the focus owner by default.
* </ul>
*
* <p>
* WARNING: Aside from those keys that are defined by the Java language
* (VK_ENTER, VK_BACK_SPACE, and VK_TAB), do not rely on the values of the VK_
* constants. Sun reserves the right to change these values as needed
* to accomodate a wider range of keyboards in the future.
*
* @author Carl Quinn
* @author Amy Fowler
* @author Norbert Lindenberg
*
* @see KeyAdapter
* @see KeyListener
* @see <a href="http://java.sun.com/docs/books/tutorial/post1.0/ui/keylistener.html">Tutorial: Writing a Key Listener</a>
*
* @since 1.1
*/
public class KeyEvent extends InputEvent {
/** {@collect.stats}
* Stores the state of native event dispatching system
* - true, if when the event was created event proxying
* mechanism was active
* - false, if it was inactive
* Used in Component.dispatchEventImpl to correctly dispatch
* events when proxy is active
*/
private boolean isProxyActive = false;
/** {@collect.stats}
* The first number in the range of ids used for key events.
*/
public static final int KEY_FIRST = 400;
/** {@collect.stats}
* The last number in the range of ids used for key events.
*/
public static final int KEY_LAST = 402;
/** {@collect.stats}
* The "key typed" event. This event is generated when a character is
* entered. In the simplest case, it is produced by a single key press.
* Often, however, characters are produced by series of key presses, and
* the mapping from key pressed events to key typed events may be
* many-to-one or many-to-many.
*/
public static final int KEY_TYPED = KEY_FIRST;
/** {@collect.stats}
* The "key pressed" event. This event is generated when a key
* is pushed down.
*/
public static final int KEY_PRESSED = 1 + KEY_FIRST; //Event.KEY_PRESS
/** {@collect.stats}
* The "key released" event. This event is generated when a key
* is let up.
*/
public static final int KEY_RELEASED = 2 + KEY_FIRST; //Event.KEY_RELEASE
/* Virtual key codes. */
public static final int VK_ENTER = '\n';
public static final int VK_BACK_SPACE = '\b';
public static final int VK_TAB = '\t';
public static final int VK_CANCEL = 0x03;
public static final int VK_CLEAR = 0x0C;
public static final int VK_SHIFT = 0x10;
public static final int VK_CONTROL = 0x11;
public static final int VK_ALT = 0x12;
public static final int VK_PAUSE = 0x13;
public static final int VK_CAPS_LOCK = 0x14;
public static final int VK_ESCAPE = 0x1B;
public static final int VK_SPACE = 0x20;
public static final int VK_PAGE_UP = 0x21;
public static final int VK_PAGE_DOWN = 0x22;
public static final int VK_END = 0x23;
public static final int VK_HOME = 0x24;
/** {@collect.stats}
* Constant for the non-numpad <b>left</b> arrow key.
* @see #VK_KP_LEFT
*/
public static final int VK_LEFT = 0x25;
/** {@collect.stats}
* Constant for the non-numpad <b>up</b> arrow key.
* @see #VK_KP_UP
*/
public static final int VK_UP = 0x26;
/** {@collect.stats}
* Constant for the non-numpad <b>right</b> arrow key.
* @see #VK_KP_RIGHT
*/
public static final int VK_RIGHT = 0x27;
/** {@collect.stats}
* Constant for the non-numpad <b>down</b> arrow key.
* @see #VK_KP_DOWN
*/
public static final int VK_DOWN = 0x28;
/** {@collect.stats}
* Constant for the comma key, ","
*/
public static final int VK_COMMA = 0x2C;
/** {@collect.stats}
* Constant for the minus key, "-"
* @since 1.2
*/
public static final int VK_MINUS = 0x2D;
/** {@collect.stats}
* Constant for the period key, "."
*/
public static final int VK_PERIOD = 0x2E;
/** {@collect.stats}
* Constant for the forward slash key, "/"
*/
public static final int VK_SLASH = 0x2F;
/** {@collect.stats} VK_0 thru VK_9 are the same as ASCII '0' thru '9' (0x30 - 0x39) */
public static final int VK_0 = 0x30;
public static final int VK_1 = 0x31;
public static final int VK_2 = 0x32;
public static final int VK_3 = 0x33;
public static final int VK_4 = 0x34;
public static final int VK_5 = 0x35;
public static final int VK_6 = 0x36;
public static final int VK_7 = 0x37;
public static final int VK_8 = 0x38;
public static final int VK_9 = 0x39;
/** {@collect.stats}
* Constant for the semicolon key, ";"
*/
public static final int VK_SEMICOLON = 0x3B;
/** {@collect.stats}
* Constant for the equals key, "="
*/
public static final int VK_EQUALS = 0x3D;
/** {@collect.stats} VK_A thru VK_Z are the same as ASCII 'A' thru 'Z' (0x41 - 0x5A) */
public static final int VK_A = 0x41;
public static final int VK_B = 0x42;
public static final int VK_C = 0x43;
public static final int VK_D = 0x44;
public static final int VK_E = 0x45;
public static final int VK_F = 0x46;
public static final int VK_G = 0x47;
public static final int VK_H = 0x48;
public static final int VK_I = 0x49;
public static final int VK_J = 0x4A;
public static final int VK_K = 0x4B;
public static final int VK_L = 0x4C;
public static final int VK_M = 0x4D;
public static final int VK_N = 0x4E;
public static final int VK_O = 0x4F;
public static final int VK_P = 0x50;
public static final int VK_Q = 0x51;
public static final int VK_R = 0x52;
public static final int VK_S = 0x53;
public static final int VK_T = 0x54;
public static final int VK_U = 0x55;
public static final int VK_V = 0x56;
public static final int VK_W = 0x57;
public static final int VK_X = 0x58;
public static final int VK_Y = 0x59;
public static final int VK_Z = 0x5A;
/** {@collect.stats}
* Constant for the open bracket key, "["
*/
public static final int VK_OPEN_BRACKET = 0x5B;
/** {@collect.stats}
* Constant for the back slash key, "\"
*/
public static final int VK_BACK_SLASH = 0x5C;
/** {@collect.stats}
* Constant for the close bracket key, "]"
*/
public static final int VK_CLOSE_BRACKET = 0x5D;
public static final int VK_NUMPAD0 = 0x60;
public static final int VK_NUMPAD1 = 0x61;
public static final int VK_NUMPAD2 = 0x62;
public static final int VK_NUMPAD3 = 0x63;
public static final int VK_NUMPAD4 = 0x64;
public static final int VK_NUMPAD5 = 0x65;
public static final int VK_NUMPAD6 = 0x66;
public static final int VK_NUMPAD7 = 0x67;
public static final int VK_NUMPAD8 = 0x68;
public static final int VK_NUMPAD9 = 0x69;
public static final int VK_MULTIPLY = 0x6A;
public static final int VK_ADD = 0x6B;
/** {@collect.stats}
* This constant is obsolete, and is included only for backwards
* compatibility.
* @see #VK_SEPARATOR
*/
public static final int VK_SEPARATER = 0x6C;
/** {@collect.stats}
* Constant for the Numpad Separator key.
* @since 1.4
*/
public static final int VK_SEPARATOR = VK_SEPARATER;
public static final int VK_SUBTRACT = 0x6D;
public static final int VK_DECIMAL = 0x6E;
public static final int VK_DIVIDE = 0x6F;
public static final int VK_DELETE = 0x7F; /* ASCII DEL */
public static final int VK_NUM_LOCK = 0x90;
public static final int VK_SCROLL_LOCK = 0x91;
/** {@collect.stats} Constant for the F1 function key. */
public static final int VK_F1 = 0x70;
/** {@collect.stats} Constant for the F2 function key. */
public static final int VK_F2 = 0x71;
/** {@collect.stats} Constant for the F3 function key. */
public static final int VK_F3 = 0x72;
/** {@collect.stats} Constant for the F4 function key. */
public static final int VK_F4 = 0x73;
/** {@collect.stats} Constant for the F5 function key. */
public static final int VK_F5 = 0x74;
/** {@collect.stats} Constant for the F6 function key. */
public static final int VK_F6 = 0x75;
/** {@collect.stats} Constant for the F7 function key. */
public static final int VK_F7 = 0x76;
/** {@collect.stats} Constant for the F8 function key. */
public static final int VK_F8 = 0x77;
/** {@collect.stats} Constant for the F9 function key. */
public static final int VK_F9 = 0x78;
/** {@collect.stats} Constant for the F10 function key. */
public static final int VK_F10 = 0x79;
/** {@collect.stats} Constant for the F11 function key. */
public static final int VK_F11 = 0x7A;
/** {@collect.stats} Constant for the F12 function key. */
public static final int VK_F12 = 0x7B;
/** {@collect.stats}
* Constant for the F13 function key.
* @since 1.2
*/
/* F13 - F24 are used on IBM 3270 keyboard; use random range for constants. */
public static final int VK_F13 = 0xF000;
/** {@collect.stats}
* Constant for the F14 function key.
* @since 1.2
*/
public static final int VK_F14 = 0xF001;
/** {@collect.stats}
* Constant for the F15 function key.
* @since 1.2
*/
public static final int VK_F15 = 0xF002;
/** {@collect.stats}
* Constant for the F16 function key.
* @since 1.2
*/
public static final int VK_F16 = 0xF003;
/** {@collect.stats}
* Constant for the F17 function key.
* @since 1.2
*/
public static final int VK_F17 = 0xF004;
/** {@collect.stats}
* Constant for the F18 function key.
* @since 1.2
*/
public static final int VK_F18 = 0xF005;
/** {@collect.stats}
* Constant for the F19 function key.
* @since 1.2
*/
public static final int VK_F19 = 0xF006;
/** {@collect.stats}
* Constant for the F20 function key.
* @since 1.2
*/
public static final int VK_F20 = 0xF007;
/** {@collect.stats}
* Constant for the F21 function key.
* @since 1.2
*/
public static final int VK_F21 = 0xF008;
/** {@collect.stats}
* Constant for the F22 function key.
* @since 1.2
*/
public static final int VK_F22 = 0xF009;
/** {@collect.stats}
* Constant for the F23 function key.
* @since 1.2
*/
public static final int VK_F23 = 0xF00A;
/** {@collect.stats}
* Constant for the F24 function key.
* @since 1.2
*/
public static final int VK_F24 = 0xF00B;
public static final int VK_PRINTSCREEN = 0x9A;
public static final int VK_INSERT = 0x9B;
public static final int VK_HELP = 0x9C;
public static final int VK_META = 0x9D;
public static final int VK_BACK_QUOTE = 0xC0;
public static final int VK_QUOTE = 0xDE;
/** {@collect.stats}
* Constant for the numeric keypad <b>up</b> arrow key.
* @see #VK_UP
* @since 1.2
*/
public static final int VK_KP_UP = 0xE0;
/** {@collect.stats}
* Constant for the numeric keypad <b>down</b> arrow key.
* @see #VK_DOWN
* @since 1.2
*/
public static final int VK_KP_DOWN = 0xE1;
/** {@collect.stats}
* Constant for the numeric keypad <b>left</b> arrow key.
* @see #VK_LEFT
* @since 1.2
*/
public static final int VK_KP_LEFT = 0xE2;
/** {@collect.stats}
* Constant for the numeric keypad <b>right</b> arrow key.
* @see #VK_RIGHT
* @since 1.2
*/
public static final int VK_KP_RIGHT = 0xE3;
/* For European keyboards */
/** {@collect.stats} @since 1.2 */
public static final int VK_DEAD_GRAVE = 0x80;
/** {@collect.stats} @since 1.2 */
public static final int VK_DEAD_ACUTE = 0x81;
/** {@collect.stats} @since 1.2 */
public static final int VK_DEAD_CIRCUMFLEX = 0x82;
/** {@collect.stats} @since 1.2 */
public static final int VK_DEAD_TILDE = 0x83;
/** {@collect.stats} @since 1.2 */
public static final int VK_DEAD_MACRON = 0x84;
/** {@collect.stats} @since 1.2 */
public static final int VK_DEAD_BREVE = 0x85;
/** {@collect.stats} @since 1.2 */
public static final int VK_DEAD_ABOVEDOT = 0x86;
/** {@collect.stats} @since 1.2 */
public static final int VK_DEAD_DIAERESIS = 0x87;
/** {@collect.stats} @since 1.2 */
public static final int VK_DEAD_ABOVERING = 0x88;
/** {@collect.stats} @since 1.2 */
public static final int VK_DEAD_DOUBLEACUTE = 0x89;
/** {@collect.stats} @since 1.2 */
public static final int VK_DEAD_CARON = 0x8a;
/** {@collect.stats} @since 1.2 */
public static final int VK_DEAD_CEDILLA = 0x8b;
/** {@collect.stats} @since 1.2 */
public static final int VK_DEAD_OGONEK = 0x8c;
/** {@collect.stats} @since 1.2 */
public static final int VK_DEAD_IOTA = 0x8d;
/** {@collect.stats} @since 1.2 */
public static final int VK_DEAD_VOICED_SOUND = 0x8e;
/** {@collect.stats} @since 1.2 */
public static final int VK_DEAD_SEMIVOICED_SOUND = 0x8f;
/** {@collect.stats} @since 1.2 */
public static final int VK_AMPERSAND = 0x96;
/** {@collect.stats} @since 1.2 */
public static final int VK_ASTERISK = 0x97;
/** {@collect.stats} @since 1.2 */
public static final int VK_QUOTEDBL = 0x98;
/** {@collect.stats} @since 1.2 */
public static final int VK_LESS = 0x99;
/** {@collect.stats} @since 1.2 */
public static final int VK_GREATER = 0xa0;
/** {@collect.stats} @since 1.2 */
public static final int VK_BRACELEFT = 0xa1;
/** {@collect.stats} @since 1.2 */
public static final int VK_BRACERIGHT = 0xa2;
/** {@collect.stats}
* Constant for the "@" key.
* @since 1.2
*/
public static final int VK_AT = 0x0200;
/** {@collect.stats}
* Constant for the ":" key.
* @since 1.2
*/
public static final int VK_COLON = 0x0201;
/** {@collect.stats}
* Constant for the "^" key.
* @since 1.2
*/
public static final int VK_CIRCUMFLEX = 0x0202;
/** {@collect.stats}
* Constant for the "$" key.
* @since 1.2
*/
public static final int VK_DOLLAR = 0x0203;
/** {@collect.stats}
* Constant for the Euro currency sign key.
* @since 1.2
*/
public static final int VK_EURO_SIGN = 0x0204;
/** {@collect.stats}
* Constant for the "!" key.
* @since 1.2
*/
public static final int VK_EXCLAMATION_MARK = 0x0205;
/** {@collect.stats}
* Constant for the inverted exclamation mark key.
* @since 1.2
*/
public static final int VK_INVERTED_EXCLAMATION_MARK = 0x0206;
/** {@collect.stats}
* Constant for the "(" key.
* @since 1.2
*/
public static final int VK_LEFT_PARENTHESIS = 0x0207;
/** {@collect.stats}
* Constant for the "#" key.
* @since 1.2
*/
public static final int VK_NUMBER_SIGN = 0x0208;
/** {@collect.stats}
* Constant for the "+" key.
* @since 1.2
*/
public static final int VK_PLUS = 0x0209;
/** {@collect.stats}
* Constant for the ")" key.
* @since 1.2
*/
public static final int VK_RIGHT_PARENTHESIS = 0x020A;
/** {@collect.stats}
* Constant for the "_" key.
* @since 1.2
*/
public static final int VK_UNDERSCORE = 0x020B;
/** {@collect.stats}
* Constant for the Microsoft Windows "Windows" key.
* It is used for both the left and right version of the key.
* @see #getKeyLocation()
* @since 1.5
*/
public static final int VK_WINDOWS = 0x020C;
/** {@collect.stats}
* Constant for the Microsoft Windows Context Menu key.
* @since 1.5
*/
public static final int VK_CONTEXT_MENU = 0x020D;
/* for input method support on Asian Keyboards */
/* not clear what this means - listed in Microsoft Windows API */
public static final int VK_FINAL = 0x0018;
/** {@collect.stats} Constant for the Convert function key. */
/* Japanese PC 106 keyboard, Japanese Solaris keyboard: henkan */
public static final int VK_CONVERT = 0x001C;
/** {@collect.stats} Constant for the Don't Convert function key. */
/* Japanese PC 106 keyboard: muhenkan */
public static final int VK_NONCONVERT = 0x001D;
/** {@collect.stats} Constant for the Accept or Commit function key. */
/* Japanese Solaris keyboard: kakutei */
public static final int VK_ACCEPT = 0x001E;
/* not clear what this means - listed in Microsoft Windows API */
public static final int VK_MODECHANGE = 0x001F;
/* replaced by VK_KANA_LOCK for Microsoft Windows and Solaris;
might still be used on other platforms */
public static final int VK_KANA = 0x0015;
/* replaced by VK_INPUT_METHOD_ON_OFF for Microsoft Windows and Solaris;
might still be used for other platforms */
public static final int VK_KANJI = 0x0019;
/** {@collect.stats}
* Constant for the Alphanumeric function key.
* @since 1.2
*/
/* Japanese PC 106 keyboard: eisuu */
public static final int VK_ALPHANUMERIC = 0x00F0;
/** {@collect.stats}
* Constant for the Katakana function key.
* @since 1.2
*/
/* Japanese PC 106 keyboard: katakana */
public static final int VK_KATAKANA = 0x00F1;
/** {@collect.stats}
* Constant for the Hiragana function key.
* @since 1.2
*/
/* Japanese PC 106 keyboard: hiragana */
public static final int VK_HIRAGANA = 0x00F2;
/** {@collect.stats}
* Constant for the Full-Width Characters function key.
* @since 1.2
*/
/* Japanese PC 106 keyboard: zenkaku */
public static final int VK_FULL_WIDTH = 0x00F3;
/** {@collect.stats}
* Constant for the Half-Width Characters function key.
* @since 1.2
*/
/* Japanese PC 106 keyboard: hankaku */
public static final int VK_HALF_WIDTH = 0x00F4;
/** {@collect.stats}
* Constant for the Roman Characters function key.
* @since 1.2
*/
/* Japanese PC 106 keyboard: roumaji */
public static final int VK_ROMAN_CHARACTERS = 0x00F5;
/** {@collect.stats}
* Constant for the All Candidates function key.
* @since 1.2
*/
/* Japanese PC 106 keyboard - VK_CONVERT + ALT: zenkouho */
public static final int VK_ALL_CANDIDATES = 0x0100;
/** {@collect.stats}
* Constant for the Previous Candidate function key.
* @since 1.2
*/
/* Japanese PC 106 keyboard - VK_CONVERT + SHIFT: maekouho */
public static final int VK_PREVIOUS_CANDIDATE = 0x0101;
/** {@collect.stats}
* Constant for the Code Input function key.
* @since 1.2
*/
/* Japanese PC 106 keyboard - VK_ALPHANUMERIC + ALT: kanji bangou */
public static final int VK_CODE_INPUT = 0x0102;
/** {@collect.stats}
* Constant for the Japanese-Katakana function key.
* This key switches to a Japanese input method and selects its Katakana input mode.
* @since 1.2
*/
/* Japanese Macintosh keyboard - VK_JAPANESE_HIRAGANA + SHIFT */
public static final int VK_JAPANESE_KATAKANA = 0x0103;
/** {@collect.stats}
* Constant for the Japanese-Hiragana function key.
* This key switches to a Japanese input method and selects its Hiragana input mode.
* @since 1.2
*/
/* Japanese Macintosh keyboard */
public static final int VK_JAPANESE_HIRAGANA = 0x0104;
/** {@collect.stats}
* Constant for the Japanese-Roman function key.
* This key switches to a Japanese input method and selects its Roman-Direct input mode.
* @since 1.2
*/
/* Japanese Macintosh keyboard */
public static final int VK_JAPANESE_ROMAN = 0x0105;
/** {@collect.stats}
* Constant for the locking Kana function key.
* This key locks the keyboard into a Kana layout.
* @since 1.3
*/
/* Japanese PC 106 keyboard with special Windows driver - eisuu + Control; Japanese Solaris keyboard: kana */
public static final int VK_KANA_LOCK = 0x0106;
/** {@collect.stats}
* Constant for the input method on/off key.
* @since 1.3
*/
/* Japanese PC 106 keyboard: kanji. Japanese Solaris keyboard: nihongo */
public static final int VK_INPUT_METHOD_ON_OFF = 0x0107;
/* for Sun keyboards */
/** {@collect.stats} @since 1.2 */
public static final int VK_CUT = 0xFFD1;
/** {@collect.stats} @since 1.2 */
public static final int VK_COPY = 0xFFCD;
/** {@collect.stats} @since 1.2 */
public static final int VK_PASTE = 0xFFCF;
/** {@collect.stats} @since 1.2 */
public static final int VK_UNDO = 0xFFCB;
/** {@collect.stats} @since 1.2 */
public static final int VK_AGAIN = 0xFFC9;
/** {@collect.stats} @since 1.2 */
public static final int VK_FIND = 0xFFD0;
/** {@collect.stats} @since 1.2 */
public static final int VK_PROPS = 0xFFCA;
/** {@collect.stats} @since 1.2 */
public static final int VK_STOP = 0xFFC8;
/** {@collect.stats}
* Constant for the Compose function key.
* @since 1.2
*/
public static final int VK_COMPOSE = 0xFF20;
/** {@collect.stats}
* Constant for the AltGraph function key.
* @since 1.2
*/
public static final int VK_ALT_GRAPH = 0xFF7E;
/** {@collect.stats}
* Constant for the Begin key.
* @since 1.5
*/
public static final int VK_BEGIN = 0xFF58;
/** {@collect.stats}
* This value is used to indicate that the keyCode is unknown.
* KEY_TYPED events do not have a keyCode value; this value
* is used instead.
*/
public static final int VK_UNDEFINED = 0x0;
/** {@collect.stats}
* KEY_PRESSED and KEY_RELEASED events which do not map to a
* valid Unicode character use this for the keyChar value.
*/
public static final char CHAR_UNDEFINED = 0xFFFF;
/** {@collect.stats}
* A constant indicating that the keyLocation is indeterminate
* or not relevant.
* <code>KEY_TYPED</code> events do not have a keyLocation; this value
* is used instead.
* @since 1.4
*/
public static final int KEY_LOCATION_UNKNOWN = 0;
/** {@collect.stats}
* A constant indicating that the key pressed or released
* is not distinguished as the left or right version of a key,
* and did not originate on the numeric keypad (or did not
* originate with a virtual key corresponding to the numeric
* keypad).
* @since 1.4
*/
public static final int KEY_LOCATION_STANDARD = 1;
/** {@collect.stats}
* A constant indicating that the key pressed or released is in
* the left key location (there is more than one possible location
* for this key). Example: the left shift key.
* @since 1.4
*/
public static final int KEY_LOCATION_LEFT = 2;
/** {@collect.stats}
* A constant indicating that the key pressed or released is in
* the right key location (there is more than one possible location
* for this key). Example: the right shift key.
* @since 1.4
*/
public static final int KEY_LOCATION_RIGHT = 3;
/** {@collect.stats}
* A constant indicating that the key event originated on the
* numeric keypad or with a virtual key corresponding to the
* numeric keypad.
* @since 1.4
*/
public static final int KEY_LOCATION_NUMPAD = 4;
/** {@collect.stats}
* The unique value assigned to each of the keys on the
* keyboard. There is a common set of key codes that
* can be fired by most keyboards.
* The symbolic name for a key code should be used rather
* than the code value itself.
*
* @serial
* @see #getKeyCode()
* @see #setKeyCode(int)
*/
int keyCode;
/** {@collect.stats}
* <code>keyChar</code> is a valid unicode character
* that is fired by a key or a key combination on
* a keyboard.
*
* @serial
* @see #getKeyChar()
* @see #setKeyChar(char)
*/
char keyChar;
/** {@collect.stats}
* The location of the key on the keyboard.
*
* Some keys occur more than once on a keyboard, e.g. the left and
* right shift keys. Additionally, some keys occur on the numeric
* keypad. This variable is used to distinguish such keys.
*
* The only legal values are <code>KEY_LOCATION_UNKNOWN</code>,
* <code>KEY_LOCATION_STANDARD</code>, <code>KEY_LOCATION_LEFT</code>,
* <code>KEY_LOCATION_RIGHT</code>, and <code>KEY_LOCATION_NUMPAD</code>.
*
* @serial
* @see #getKeyLocation()
*/
int keyLocation;
/*
* JDK 1.1 serialVersionUID
*/
private static final long serialVersionUID = -2352130953028126954L;
static {
/* ensure that the necessary native libraries are loaded */
NativeLibLoader.loadLibraries();
if (!GraphicsEnvironment.isHeadless()) {
initIDs();
}
}
/** {@collect.stats}
* Initialize JNI field and method IDs for fields that may be
* accessed from C.
*/
private static native void initIDs();
/** {@collect.stats}
* Constructs a <code>KeyEvent</code> object.
* <p>Note that passing in an invalid <code>id</code> results in
* unspecified behavior. This method throws an
* <code>IllegalArgumentException</code> if <code>source</code>
* is <code>null</code>.
*
* @param source the <code>Component</code> that originated the event
* @param id an integer identifying the type of event
* @param when a long integer that specifies the time the event
* occurred
* @param modifiers the modifier keys down during event (shift, ctrl,
* alt, meta)
* Either extended _DOWN_MASK or old _MASK modifiers
* should be used, but both models should not be mixed
* in one event. Use of the extended modifiers is
* preferred.
* @param keyCode the integer code for an actual key, or VK_UNDEFINED
* (for a key-typed event)
* @param keyChar the Unicode character generated by this event, or
* CHAR_UNDEFINED (for key-pressed and key-released
* events which do not map to a valid Unicode character)
* @param keyLocation identifies the key location. The only legal
* values are <code>KEY_LOCATION_UNKNOWN</code>,
* <code>KEY_LOCATION_STANDARD</code>, <code>KEY_LOCATION_LEFT</code>,
* <code>KEY_LOCATION_RIGHT</code>, and <code>KEY_LOCATION_NUMPAD</code>.
* @throws IllegalArgumentException
* if <code>id</code> is <code>KEY_TYPED</code> and
* <code>keyChar</code> is <code>CHAR_UNDEFINED</code>;
* or if <code>id</code> is <code>KEY_TYPED</code> and
* <code>keyCode</code> is not <code>VK_UNDEFINED</code>;
* or if <code>id</code> is <code>KEY_TYPED</code> and
* <code>keyLocation</code> is not <code>KEY_LOCATION_UNKNOWN</code>;
* or if <code>keyLocation</code> is not one of the legal
* values enumerated above.
* @throws IllegalArgumentException if <code>source</code> is null
* @since 1.4
*/
private KeyEvent(Component source, int id, long when, int modifiers,
int keyCode, char keyChar, int keyLocation, boolean isProxyActive) {
this(source, id, when, modifiers, keyCode, keyChar, keyLocation);
this.isProxyActive = isProxyActive;
}
public KeyEvent(Component source, int id, long when, int modifiers,
int keyCode, char keyChar, int keyLocation) {
super(source, id, when, modifiers);
if (id == KEY_TYPED) {
if (keyChar == CHAR_UNDEFINED) {
throw new IllegalArgumentException("invalid keyChar");
}
if (keyCode != VK_UNDEFINED) {
throw new IllegalArgumentException("invalid keyCode");
}
if (keyLocation != KEY_LOCATION_UNKNOWN) {
throw new IllegalArgumentException("invalid keyLocation");
}
}
this.keyCode = keyCode;
this.keyChar = keyChar;
if ((keyLocation < KEY_LOCATION_UNKNOWN) ||
(keyLocation > KEY_LOCATION_NUMPAD)) {
throw new IllegalArgumentException("invalid keyLocation");
}
this.keyLocation = keyLocation;
if ((getModifiers() != 0) && (getModifiersEx() == 0)) {
setNewModifiers();
} else if ((getModifiers() == 0) && (getModifiersEx() != 0)) {
setOldModifiers();
}
}
/** {@collect.stats}
* Constructs a <code>KeyEvent</code> object.
* <p>Note that passing in an invalid <code>id</code> results in
* unspecified behavior. This method throws an
* <code>IllegalArgumentException</code> if <code>source</code>
* is <code>null</code>.
*
* @param source the <code>Component</code> that originated the event
* @param id an integer identifying the type of event
* @param when a long integer that specifies the time the event
* occurred
* @param modifiers the modifier keys down during event (shift, ctrl,
* alt, meta)
* Either extended _DOWN_MASK or old _MASK modifiers
* should be used, but both models should not be mixed
* in one event. Use of the extended modifiers is
* preferred.
* @param keyCode the integer code for an actual key, or VK_UNDEFINED
* (for a key-typed event)
* @param keyChar the Unicode character generated by this event, or
* CHAR_UNDEFINED (for key-pressed and key-released
* events which do not map to a valid Unicode character)
* @throws IllegalArgumentException if <code>id</code> is
* <code>KEY_TYPED</code> and <code>keyChar</code> is
* <code>CHAR_UNDEFINED</code>; or if <code>id</code> is
* <code>KEY_TYPED</code> and <code>keyCode</code> is not
* <code>VK_UNDEFINED</code>
* @throws IllegalArgumentException if <code>source</code> is null
*/
public KeyEvent(Component source, int id, long when, int modifiers,
int keyCode, char keyChar) {
this(source, id, when, modifiers, keyCode, keyChar,
KEY_LOCATION_UNKNOWN);
}
/** {@collect.stats}
* @deprecated as of JDK1.1
*/
@Deprecated
public KeyEvent(Component source, int id, long when, int modifiers,
int keyCode) {
this(source, id, when, modifiers, keyCode, (char)keyCode);
}
/** {@collect.stats}
* Returns the integer keyCode associated with the key in this event.
*
* @return the integer code for an actual key on the keyboard.
* (For <code>KEY_TYPED</code> events, the keyCode is
* <code>VK_UNDEFINED</code>.)
*/
public int getKeyCode() {
return keyCode;
}
/** {@collect.stats}
* Set the keyCode value to indicate a physical key.
*
* @param keyCode an integer corresponding to an actual key on the keyboard.
*/
public void setKeyCode(int keyCode) {
this.keyCode = keyCode;
}
/** {@collect.stats}
* Returns the character associated with the key in this event.
* For example, the <code>KEY_TYPED</code> event for shift + "a"
* returns the value for "A".
* <p>
* <code>KEY_PRESSED</code> and <code>KEY_RELEASED</code> events
* are not intended for reporting of character input. Therefore,
* the values returned by this method are guaranteed to be
* meaningful only for <code>KEY_TYPED</code> events.
*
* @return the Unicode character defined for this key event.
* If no valid Unicode character exists for this key event,
* <code>CHAR_UNDEFINED</code> is returned.
*/
public char getKeyChar() {
return keyChar;
}
/** {@collect.stats}
* Set the keyChar value to indicate a logical character.
*
* @param keyChar a char corresponding to to the combination of keystrokes
* that make up this event.
*/
public void setKeyChar(char keyChar) {
this.keyChar = keyChar;
}
/** {@collect.stats}
* Set the modifiers to indicate additional keys that were held down
* (e.g. shift, ctrl, alt, meta) defined as part of InputEvent.
* <p>
* NOTE: use of this method is not recommended, because many AWT
* implementations do not recognize modifier changes. This is
* especially true for <code>KEY_TYPED</code> events where the shift
* modifier is changed.
*
* @param modifiers an integer combination of the modifier constants.
* @see InputEvent
* @deprecated as of JDK1.1.4
*/
@Deprecated
public void setModifiers(int modifiers) {
this.modifiers = modifiers;
if ((getModifiers() != 0) && (getModifiersEx() == 0)) {
setNewModifiers();
} else if ((getModifiers() == 0) && (getModifiersEx() != 0)) {
setOldModifiers();
}
}
/** {@collect.stats}
* Returns the location of the key that originated this key event.
*
* Some keys occur more than once on a keyboard, e.g. the left and
* right shift keys. Additionally, some keys occur on the numeric
* keypad. This provides a way of distinguishing such keys.
*
* @return the location of the key that was pressed or released.
* Always returns <code>KEY_LOCATION_UNKNOWN</code> for
* <code>KEY_TYPED</code> events.
* @since 1.4
*/
public int getKeyLocation() {
return keyLocation;
}
/** {@collect.stats}
* Returns a String describing the keyCode, such as "HOME", "F1" or "A".
* These strings can be localized by changing the awt.properties file.
*
* @return a string containing a text description for a physical key,
* identified by its keyCode
*/
public static String getKeyText(int keyCode) {
if (keyCode >= VK_0 && keyCode <= VK_9 ||
keyCode >= VK_A && keyCode <= VK_Z) {
return String.valueOf((char)keyCode);
}
switch(keyCode) {
case VK_ENTER: return Toolkit.getProperty("AWT.enter", "Enter");
case VK_BACK_SPACE: return Toolkit.getProperty("AWT.backSpace", "Backspace");
case VK_TAB: return Toolkit.getProperty("AWT.tab", "Tab");
case VK_CANCEL: return Toolkit.getProperty("AWT.cancel", "Cancel");
case VK_CLEAR: return Toolkit.getProperty("AWT.clear", "Clear");
case VK_COMPOSE: return Toolkit.getProperty("AWT.compose", "Compose");
case VK_PAUSE: return Toolkit.getProperty("AWT.pause", "Pause");
case VK_CAPS_LOCK: return Toolkit.getProperty("AWT.capsLock", "Caps Lock");
case VK_ESCAPE: return Toolkit.getProperty("AWT.escape", "Escape");
case VK_SPACE: return Toolkit.getProperty("AWT.space", "Space");
case VK_PAGE_UP: return Toolkit.getProperty("AWT.pgup", "Page Up");
case VK_PAGE_DOWN: return Toolkit.getProperty("AWT.pgdn", "Page Down");
case VK_END: return Toolkit.getProperty("AWT.end", "End");
case VK_HOME: return Toolkit.getProperty("AWT.home", "Home");
case VK_LEFT: return Toolkit.getProperty("AWT.left", "Left");
case VK_UP: return Toolkit.getProperty("AWT.up", "Up");
case VK_RIGHT: return Toolkit.getProperty("AWT.right", "Right");
case VK_DOWN: return Toolkit.getProperty("AWT.down", "Down");
case VK_BEGIN: return Toolkit.getProperty("AWT.begin", "Begin");
// modifiers
case VK_SHIFT: return Toolkit.getProperty("AWT.shift", "Shift");
case VK_CONTROL: return Toolkit.getProperty("AWT.control", "Control");
case VK_ALT: return Toolkit.getProperty("AWT.alt", "Alt");
case VK_META: return Toolkit.getProperty("AWT.meta", "Meta");
case VK_ALT_GRAPH: return Toolkit.getProperty("AWT.altGraph", "Alt Graph");
// punctuation
case VK_COMMA: return Toolkit.getProperty("AWT.comma", "Comma");
case VK_PERIOD: return Toolkit.getProperty("AWT.period", "Period");
case VK_SLASH: return Toolkit.getProperty("AWT.slash", "Slash");
case VK_SEMICOLON: return Toolkit.getProperty("AWT.semicolon", "Semicolon");
case VK_EQUALS: return Toolkit.getProperty("AWT.equals", "Equals");
case VK_OPEN_BRACKET: return Toolkit.getProperty("AWT.openBracket", "Open Bracket");
case VK_BACK_SLASH: return Toolkit.getProperty("AWT.backSlash", "Back Slash");
case VK_CLOSE_BRACKET: return Toolkit.getProperty("AWT.closeBracket", "Close Bracket");
// numpad numeric keys handled below
case VK_MULTIPLY: return Toolkit.getProperty("AWT.multiply", "NumPad *");
case VK_ADD: return Toolkit.getProperty("AWT.add", "NumPad +");
case VK_SEPARATOR: return Toolkit.getProperty("AWT.separator", "NumPad ,");
case VK_SUBTRACT: return Toolkit.getProperty("AWT.subtract", "NumPad -");
case VK_DECIMAL: return Toolkit.getProperty("AWT.decimal", "NumPad .");
case VK_DIVIDE: return Toolkit.getProperty("AWT.divide", "NumPad /");
case VK_DELETE: return Toolkit.getProperty("AWT.delete", "Delete");
case VK_NUM_LOCK: return Toolkit.getProperty("AWT.numLock", "Num Lock");
case VK_SCROLL_LOCK: return Toolkit.getProperty("AWT.scrollLock", "Scroll Lock");
case VK_WINDOWS: return Toolkit.getProperty("AWT.windows", "Windows");
case VK_CONTEXT_MENU: return Toolkit.getProperty("AWT.context", "Context Menu");
case VK_F1: return Toolkit.getProperty("AWT.f1", "F1");
case VK_F2: return Toolkit.getProperty("AWT.f2", "F2");
case VK_F3: return Toolkit.getProperty("AWT.f3", "F3");
case VK_F4: return Toolkit.getProperty("AWT.f4", "F4");
case VK_F5: return Toolkit.getProperty("AWT.f5", "F5");
case VK_F6: return Toolkit.getProperty("AWT.f6", "F6");
case VK_F7: return Toolkit.getProperty("AWT.f7", "F7");
case VK_F8: return Toolkit.getProperty("AWT.f8", "F8");
case VK_F9: return Toolkit.getProperty("AWT.f9", "F9");
case VK_F10: return Toolkit.getProperty("AWT.f10", "F10");
case VK_F11: return Toolkit.getProperty("AWT.f11", "F11");
case VK_F12: return Toolkit.getProperty("AWT.f12", "F12");
case VK_F13: return Toolkit.getProperty("AWT.f13", "F13");
case VK_F14: return Toolkit.getProperty("AWT.f14", "F14");
case VK_F15: return Toolkit.getProperty("AWT.f15", "F15");
case VK_F16: return Toolkit.getProperty("AWT.f16", "F16");
case VK_F17: return Toolkit.getProperty("AWT.f17", "F17");
case VK_F18: return Toolkit.getProperty("AWT.f18", "F18");
case VK_F19: return Toolkit.getProperty("AWT.f19", "F19");
case VK_F20: return Toolkit.getProperty("AWT.f20", "F20");
case VK_F21: return Toolkit.getProperty("AWT.f21", "F21");
case VK_F22: return Toolkit.getProperty("AWT.f22", "F22");
case VK_F23: return Toolkit.getProperty("AWT.f23", "F23");
case VK_F24: return Toolkit.getProperty("AWT.f24", "F24");
case VK_PRINTSCREEN: return Toolkit.getProperty("AWT.printScreen", "Print Screen");
case VK_INSERT: return Toolkit.getProperty("AWT.insert", "Insert");
case VK_HELP: return Toolkit.getProperty("AWT.help", "Help");
case VK_BACK_QUOTE: return Toolkit.getProperty("AWT.backQuote", "Back Quote");
case VK_QUOTE: return Toolkit.getProperty("AWT.quote", "Quote");
case VK_KP_UP: return Toolkit.getProperty("AWT.up", "Up");
case VK_KP_DOWN: return Toolkit.getProperty("AWT.down", "Down");
case VK_KP_LEFT: return Toolkit.getProperty("AWT.left", "Left");
case VK_KP_RIGHT: return Toolkit.getProperty("AWT.right", "Right");
case VK_DEAD_GRAVE: return Toolkit.getProperty("AWT.deadGrave", "Dead Grave");
case VK_DEAD_ACUTE: return Toolkit.getProperty("AWT.deadAcute", "Dead Acute");
case VK_DEAD_CIRCUMFLEX: return Toolkit.getProperty("AWT.deadCircumflex", "Dead Circumflex");
case VK_DEAD_TILDE: return Toolkit.getProperty("AWT.deadTilde", "Dead Tilde");
case VK_DEAD_MACRON: return Toolkit.getProperty("AWT.deadMacron", "Dead Macron");
case VK_DEAD_BREVE: return Toolkit.getProperty("AWT.deadBreve", "Dead Breve");
case VK_DEAD_ABOVEDOT: return Toolkit.getProperty("AWT.deadAboveDot", "Dead Above Dot");
case VK_DEAD_DIAERESIS: return Toolkit.getProperty("AWT.deadDiaeresis", "Dead Diaeresis");
case VK_DEAD_ABOVERING: return Toolkit.getProperty("AWT.deadAboveRing", "Dead Above Ring");
case VK_DEAD_DOUBLEACUTE: return Toolkit.getProperty("AWT.deadDoubleAcute", "Dead Double Acute");
case VK_DEAD_CARON: return Toolkit.getProperty("AWT.deadCaron", "Dead Caron");
case VK_DEAD_CEDILLA: return Toolkit.getProperty("AWT.deadCedilla", "Dead Cedilla");
case VK_DEAD_OGONEK: return Toolkit.getProperty("AWT.deadOgonek", "Dead Ogonek");
case VK_DEAD_IOTA: return Toolkit.getProperty("AWT.deadIota", "Dead Iota");
case VK_DEAD_VOICED_SOUND: return Toolkit.getProperty("AWT.deadVoicedSound", "Dead Voiced Sound");
case VK_DEAD_SEMIVOICED_SOUND: return Toolkit.getProperty("AWT.deadSemivoicedSound", "Dead Semivoiced Sound");
case VK_AMPERSAND: return Toolkit.getProperty("AWT.ampersand", "Ampersand");
case VK_ASTERISK: return Toolkit.getProperty("AWT.asterisk", "Asterisk");
case VK_QUOTEDBL: return Toolkit.getProperty("AWT.quoteDbl", "Double Quote");
case VK_LESS: return Toolkit.getProperty("AWT.Less", "Less");
case VK_GREATER: return Toolkit.getProperty("AWT.greater", "Greater");
case VK_BRACELEFT: return Toolkit.getProperty("AWT.braceLeft", "Left Brace");
case VK_BRACERIGHT: return Toolkit.getProperty("AWT.braceRight", "Right Brace");
case VK_AT: return Toolkit.getProperty("AWT.at", "At");
case VK_COLON: return Toolkit.getProperty("AWT.colon", "Colon");
case VK_CIRCUMFLEX: return Toolkit.getProperty("AWT.circumflex", "Circumflex");
case VK_DOLLAR: return Toolkit.getProperty("AWT.dollar", "Dollar");
case VK_EURO_SIGN: return Toolkit.getProperty("AWT.euro", "Euro");
case VK_EXCLAMATION_MARK: return Toolkit.getProperty("AWT.exclamationMark", "Exclamation Mark");
case VK_INVERTED_EXCLAMATION_MARK: return Toolkit.getProperty("AWT.invertedExclamationMark", "Inverted Exclamation Mark");
case VK_LEFT_PARENTHESIS: return Toolkit.getProperty("AWT.leftParenthesis", "Left Parenthesis");
case VK_NUMBER_SIGN: return Toolkit.getProperty("AWT.numberSign", "Number Sign");
case VK_MINUS: return Toolkit.getProperty("AWT.minus", "Minus");
case VK_PLUS: return Toolkit.getProperty("AWT.plus", "Plus");
case VK_RIGHT_PARENTHESIS: return Toolkit.getProperty("AWT.rightParenthesis", "Right Parenthesis");
case VK_UNDERSCORE: return Toolkit.getProperty("AWT.underscore", "Underscore");
case VK_FINAL: return Toolkit.getProperty("AWT.final", "Final");
case VK_CONVERT: return Toolkit.getProperty("AWT.convert", "Convert");
case VK_NONCONVERT: return Toolkit.getProperty("AWT.noconvert", "No Convert");
case VK_ACCEPT: return Toolkit.getProperty("AWT.accept", "Accept");
case VK_MODECHANGE: return Toolkit.getProperty("AWT.modechange", "Mode Change");
case VK_KANA: return Toolkit.getProperty("AWT.kana", "Kana");
case VK_KANJI: return Toolkit.getProperty("AWT.kanji", "Kanji");
case VK_ALPHANUMERIC: return Toolkit.getProperty("AWT.alphanumeric", "Alphanumeric");
case VK_KATAKANA: return Toolkit.getProperty("AWT.katakana", "Katakana");
case VK_HIRAGANA: return Toolkit.getProperty("AWT.hiragana", "Hiragana");
case VK_FULL_WIDTH: return Toolkit.getProperty("AWT.fullWidth", "Full-Width");
case VK_HALF_WIDTH: return Toolkit.getProperty("AWT.halfWidth", "Half-Width");
case VK_ROMAN_CHARACTERS: return Toolkit.getProperty("AWT.romanCharacters", "Roman Characters");
case VK_ALL_CANDIDATES: return Toolkit.getProperty("AWT.allCandidates", "All Candidates");
case VK_PREVIOUS_CANDIDATE: return Toolkit.getProperty("AWT.previousCandidate", "Previous Candidate");
case VK_CODE_INPUT: return Toolkit.getProperty("AWT.codeInput", "Code Input");
case VK_JAPANESE_KATAKANA: return Toolkit.getProperty("AWT.japaneseKatakana", "Japanese Katakana");
case VK_JAPANESE_HIRAGANA: return Toolkit.getProperty("AWT.japaneseHiragana", "Japanese Hiragana");
case VK_JAPANESE_ROMAN: return Toolkit.getProperty("AWT.japaneseRoman", "Japanese Roman");
case VK_KANA_LOCK: return Toolkit.getProperty("AWT.kanaLock", "Kana Lock");
case VK_INPUT_METHOD_ON_OFF: return Toolkit.getProperty("AWT.inputMethodOnOff", "Input Method On/Off");
case VK_AGAIN: return Toolkit.getProperty("AWT.again", "Again");
case VK_UNDO: return Toolkit.getProperty("AWT.undo", "Undo");
case VK_COPY: return Toolkit.getProperty("AWT.copy", "Copy");
case VK_PASTE: return Toolkit.getProperty("AWT.paste", "Paste");
case VK_CUT: return Toolkit.getProperty("AWT.cut", "Cut");
case VK_FIND: return Toolkit.getProperty("AWT.find", "Find");
case VK_PROPS: return Toolkit.getProperty("AWT.props", "Props");
case VK_STOP: return Toolkit.getProperty("AWT.stop", "Stop");
}
if (keyCode >= VK_NUMPAD0 && keyCode <= VK_NUMPAD9) {
String numpad = Toolkit.getProperty("AWT.numpad", "NumPad");
char c = (char)(keyCode - VK_NUMPAD0 + '0');
return numpad + "-" + c;
}
String unknown = Toolkit.getProperty("AWT.unknown", "Unknown");
return unknown + " keyCode: 0x" + Integer.toString(keyCode, 16);
}
/** {@collect.stats}
* Returns a <code>String</code> describing the modifier key(s),
* such as "Shift", or "Ctrl+Shift". These strings can be
* localized by changing the <code>awt.properties</code> file.
* <p>
* Note that <code>InputEvent.ALT_MASK</code> and
* <code>InputEvent.BUTTON2_MASK</code> have the same value,
* so the string "Alt" is returned for both modifiers. Likewise,
* <code>InputEvent.META_MASK</code> and
* <code>InputEvent.BUTTON3_MASK</code> have the same value,
* so the string "Meta" is returned for both modifiers.
*
* @return string a text description of the combination of modifier
* keys that were held down during the event
* @see InputEvent#getModifiersExText(int)
*/
public static String getKeyModifiersText(int modifiers) {
StringBuilder buf = new StringBuilder();
if ((modifiers & InputEvent.META_MASK) != 0) {
buf.append(Toolkit.getProperty("AWT.meta", "Meta"));
buf.append("+");
}
if ((modifiers & InputEvent.CTRL_MASK) != 0) {
buf.append(Toolkit.getProperty("AWT.control", "Ctrl"));
buf.append("+");
}
if ((modifiers & InputEvent.ALT_MASK) != 0) {
buf.append(Toolkit.getProperty("AWT.alt", "Alt"));
buf.append("+");
}
if ((modifiers & InputEvent.SHIFT_MASK) != 0) {
buf.append(Toolkit.getProperty("AWT.shift", "Shift"));
buf.append("+");
}
if ((modifiers & InputEvent.ALT_GRAPH_MASK) != 0) {
buf.append(Toolkit.getProperty("AWT.altGraph", "Alt Graph"));
buf.append("+");
}
if ((modifiers & InputEvent.BUTTON1_MASK) != 0) {
buf.append(Toolkit.getProperty("AWT.button1", "Button1"));
buf.append("+");
}
if (buf.length() > 0) {
buf.setLength(buf.length()-1); // remove trailing '+'
}
return buf.toString();
}
/** {@collect.stats}
* Returns whether the key in this event is an "action" key.
* Typically an action key does not fire a unicode character and is
* not a modifier key.
*
* @return <code>true</code> if the key is an "action" key,
* <code>false</code> otherwise
*/
public boolean isActionKey() {
switch (keyCode) {
case VK_HOME:
case VK_END:
case VK_PAGE_UP:
case VK_PAGE_DOWN:
case VK_UP:
case VK_DOWN:
case VK_LEFT:
case VK_RIGHT:
case VK_BEGIN:
case VK_KP_LEFT:
case VK_KP_UP:
case VK_KP_RIGHT:
case VK_KP_DOWN:
case VK_F1:
case VK_F2:
case VK_F3:
case VK_F4:
case VK_F5:
case VK_F6:
case VK_F7:
case VK_F8:
case VK_F9:
case VK_F10:
case VK_F11:
case VK_F12:
case VK_F13:
case VK_F14:
case VK_F15:
case VK_F16:
case VK_F17:
case VK_F18:
case VK_F19:
case VK_F20:
case VK_F21:
case VK_F22:
case VK_F23:
case VK_F24:
case VK_PRINTSCREEN:
case VK_SCROLL_LOCK:
case VK_CAPS_LOCK:
case VK_NUM_LOCK:
case VK_PAUSE:
case VK_INSERT:
case VK_FINAL:
case VK_CONVERT:
case VK_NONCONVERT:
case VK_ACCEPT:
case VK_MODECHANGE:
case VK_KANA:
case VK_KANJI:
case VK_ALPHANUMERIC:
case VK_KATAKANA:
case VK_HIRAGANA:
case VK_FULL_WIDTH:
case VK_HALF_WIDTH:
case VK_ROMAN_CHARACTERS:
case VK_ALL_CANDIDATES:
case VK_PREVIOUS_CANDIDATE:
case VK_CODE_INPUT:
case VK_JAPANESE_KATAKANA:
case VK_JAPANESE_HIRAGANA:
case VK_JAPANESE_ROMAN:
case VK_KANA_LOCK:
case VK_INPUT_METHOD_ON_OFF:
case VK_AGAIN:
case VK_UNDO:
case VK_COPY:
case VK_PASTE:
case VK_CUT:
case VK_FIND:
case VK_PROPS:
case VK_STOP:
case VK_HELP:
case VK_WINDOWS:
case VK_CONTEXT_MENU:
return true;
}
return false;
}
/** {@collect.stats}
* Returns a parameter string identifying this event.
* This method is useful for event logging and for debugging.
*
* @return a string identifying the event and its attributes
*/
public String paramString() {
StringBuilder str = new StringBuilder(100);
switch (id) {
case KEY_PRESSED:
str.append("KEY_PRESSED");
break;
case KEY_RELEASED:
str.append("KEY_RELEASED");
break;
case KEY_TYPED:
str.append("KEY_TYPED");
break;
default:
str.append("unknown type");
break;
}
str.append(",keyCode=").append(keyCode);
str.append(",keyText=").append(getKeyText(keyCode));
/* Some keychars don't print well, e.g. escape, backspace,
* tab, return, delete, cancel. Get keyText for the keyCode
* instead of the keyChar.
*/
str.append(",keyChar=");
switch (keyChar) {
case '\b':
str.append(getKeyText(VK_BACK_SPACE));
break;
case '\t':
str.append(getKeyText(VK_TAB));
break;
case '\n':
str.append(getKeyText(VK_ENTER));
break;
case '\u0018':
str.append(getKeyText(VK_CANCEL));
break;
case '\u001b':
str.append(getKeyText(VK_ESCAPE));
break;
case '\u007f':
str.append(getKeyText(VK_DELETE));
break;
case CHAR_UNDEFINED:
str.append(Toolkit.getProperty("AWT.undefined", "Undefined"));
str.append(" keyChar");
break;
default:
str.append("'").append(keyChar).append("'");
break;
}
if (getModifiers() != 0) {
str.append(",modifiers=").append(getKeyModifiersText(modifiers));
}
if (getModifiersEx() != 0) {
str.append(",extModifiers=").append(getModifiersExText(modifiers));
}
str.append(",keyLocation=");
switch (keyLocation) {
case KEY_LOCATION_UNKNOWN:
str.append("KEY_LOCATION_UNKNOWN");
break;
case KEY_LOCATION_STANDARD:
str.append("KEY_LOCATION_STANDARD");
break;
case KEY_LOCATION_LEFT:
str.append("KEY_LOCATION_LEFT");
break;
case KEY_LOCATION_RIGHT:
str.append("KEY_LOCATION_RIGHT");
break;
case KEY_LOCATION_NUMPAD:
str.append("KEY_LOCATION_NUMPAD");
break;
default:
str.append("KEY_LOCATION_UNKNOWN");
break;
}
return str.toString();
}
/** {@collect.stats}
* Sets new modifiers by the old ones. The key modifiers
* override overlaping mouse modifiers.
*/
private void setNewModifiers() {
if ((modifiers & SHIFT_MASK) != 0) {
modifiers |= SHIFT_DOWN_MASK;
}
if ((modifiers & ALT_MASK) != 0) {
modifiers |= ALT_DOWN_MASK;
}
if ((modifiers & CTRL_MASK) != 0) {
modifiers |= CTRL_DOWN_MASK;
}
if ((modifiers & META_MASK) != 0) {
modifiers |= META_DOWN_MASK;
}
if ((modifiers & ALT_GRAPH_MASK) != 0) {
modifiers |= ALT_GRAPH_DOWN_MASK;
}
if ((modifiers & BUTTON1_MASK) != 0) {
modifiers |= BUTTON1_DOWN_MASK;
}
}
/** {@collect.stats}
* Sets old modifiers by the new ones.
*/
private void setOldModifiers() {
if ((modifiers & SHIFT_DOWN_MASK) != 0) {
modifiers |= SHIFT_MASK;
}
if ((modifiers & ALT_DOWN_MASK) != 0) {
modifiers |= ALT_MASK;
}
if ((modifiers & CTRL_DOWN_MASK) != 0) {
modifiers |= CTRL_MASK;
}
if ((modifiers & META_DOWN_MASK) != 0) {
modifiers |= META_MASK;
}
if ((modifiers & ALT_GRAPH_DOWN_MASK) != 0) {
modifiers |= ALT_GRAPH_MASK;
}
if ((modifiers & BUTTON1_DOWN_MASK) != 0) {
modifiers |= BUTTON1_MASK;
}
}
/** {@collect.stats}
* Sets new modifiers by the old ones. The key modifiers
* override overlaping mouse modifiers.
* @serial
*/
private void readObject(ObjectInputStream s)
throws IOException, ClassNotFoundException {
s.defaultReadObject();
if (getModifiers() != 0 && getModifiersEx() == 0) {
setNewModifiers();
}
}
}
|
Java
|
/*
* Copyright (c) 1996, 2006, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code 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
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package java.awt.event;
import java.util.EventListener;
/** {@collect.stats}
* The listener interface for receiving component events.
* The class that is interested in processing a component event
* either implements this interface (and all the methods it
* contains) or extends the abstract <code>ComponentAdapter</code> class
* (overriding only the methods of interest).
* The listener object created from that class is then registered with a
* component using the component's <code>addComponentListener</code>
* method. When the component's size, location, or visibility
* changes, the relevant method in the listener object is invoked,
* and the <code>ComponentEvent</code> is passed to it.
* <P>
* Component events are provided for notification purposes ONLY;
* The AWT will automatically handle component moves and resizes
* internally so that GUI layout works properly regardless of
* whether a program registers a <code>ComponentListener</code> or not.
*
* @see ComponentAdapter
* @see ComponentEvent
* @see <a href="http://java.sun.com/docs/books/tutorial/post1.0/ui/componentlistener.html">Tutorial: Writing a Component Listener</a>
*
* @author Carl Quinn
* @since 1.1
*/
public interface ComponentListener extends EventListener {
/** {@collect.stats}
* Invoked when the component's size changes.
*/
public void componentResized(ComponentEvent e);
/** {@collect.stats}
* Invoked when the component's position changes.
*/
public void componentMoved(ComponentEvent e);
/** {@collect.stats}
* Invoked when the component has been made visible.
*/
public void componentShown(ComponentEvent e);
/** {@collect.stats}
* Invoked when the component has been made invisible.
*/
public void componentHidden(ComponentEvent e);
}
|
Java
|
/*
* Copyright (c) 1996, 2006, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code 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
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package java.awt.event;
import java.util.EventListener;
/** {@collect.stats}
* The listener interface for receiving keyboard events (keystrokes).
* The class that is interested in processing a keyboard event
* either implements this interface (and all the methods it
* contains) or extends the abstract <code>KeyAdapter</code> class
* (overriding only the methods of interest).
* <P>
* The listener object created from that class is then registered with a
* component using the component's <code>addKeyListener</code>
* method. A keyboard event is generated when a key is pressed, released,
* or typed. The relevant method in the listener
* object is then invoked, and the <code>KeyEvent</code> is passed to it.
*
* @author Carl Quinn
*
* @see KeyAdapter
* @see KeyEvent
* @see <a href="http://java.sun.com/docs/books/tutorial/post1.0/ui/keylistener.html">Tutorial: Writing a Key Listener</a>
*
* @since 1.1
*/
public interface KeyListener extends EventListener {
/** {@collect.stats}
* Invoked when a key has been typed.
* See the class description for {@link KeyEvent} for a definition of
* a key typed event.
*/
public void keyTyped(KeyEvent e);
/** {@collect.stats}
* Invoked when a key has been pressed.
* See the class description for {@link KeyEvent} for a definition of
* a key pressed event.
*/
public void keyPressed(KeyEvent e);
/** {@collect.stats}
* Invoked when a key has been released.
* See the class description for {@link KeyEvent} for a definition of
* a key released event.
*/
public void keyReleased(KeyEvent e);
}
|
Java
|
/*
* Copyright (c) 1996, 2006, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code 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
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package java.awt.event;
/** {@collect.stats}
* An abstract adapter class for receiving mouse events.
* The methods in this class are empty. This class exists as
* convenience for creating listener objects.
* <P>
* Mouse events let you track when a mouse is pressed, released, clicked,
* moved, dragged, when it enters a component, when it exits and
* when a mouse wheel is moved.
* <P>
* Extend this class to create a {@code MouseEvent}
* (including drag and motion events) or/and {@code MouseWheelEvent}
* listener and override the methods for the events of interest. (If you implement the
* {@code MouseListener},
* {@code MouseMotionListener}
* interface, you have to define all of
* the methods in it. This abstract class defines null methods for them
* all, so you can only have to define methods for events you care about.)
* <P>
* Create a listener object using the extended class and then register it with
* a component using the component's {@code addMouseListener}
* {@code addMouseMotionListener}, {@code addMouseWheelListener}
* methods.
* The relevant method in the listener object is invoked and the {@code MouseEvent}
* or {@code MouseWheelEvent} is passed to it in following cases:
* <p><ul>
* <li>when a mouse button is pressed, released, or clicked (pressed and released)
* <li>when the mouse cursor enters or exits the component
* <li>when the mouse wheel rotated, or mouse moved or dragged
* </ul>
*
* @author Carl Quinn
* @author Andrei Dmitriev
*
* @see MouseEvent
* @see MouseWheelEvent
* @see MouseListener
* @see MouseMotionListener
* @see MouseWheelListener
* @see <a href="http://java.sun.com/docs/books/tutorial/post1.0/ui/mouselistener.html">Tutorial: Writing a Mouse Listener</a>
*
* @since 1.1
*/
public abstract class MouseAdapter implements MouseListener, MouseWheelListener, MouseMotionListener {
/** {@collect.stats}
* {@inheritDoc}
*/
public void mouseClicked(MouseEvent e) {}
/** {@collect.stats}
* {@inheritDoc}
*/
public void mousePressed(MouseEvent e) {}
/** {@collect.stats}
* {@inheritDoc}
*/
public void mouseReleased(MouseEvent e) {}
/** {@collect.stats}
* {@inheritDoc}
*/
public void mouseEntered(MouseEvent e) {}
/** {@collect.stats}
* {@inheritDoc}
*/
public void mouseExited(MouseEvent e) {}
/** {@collect.stats}
* {@inheritDoc}
* @since 1.6
*/
public void mouseWheelMoved(MouseWheelEvent e){}
/** {@collect.stats}
* {@inheritDoc}
* @since 1.6
*/
public void mouseDragged(MouseEvent e){}
/** {@collect.stats}
* {@inheritDoc}
* @since 1.6
*/
public void mouseMoved(MouseEvent e){}
}
|
Java
|
/*
* Copyright (c) 1996, 2006, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code 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
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package java.awt.event;
import java.awt.AWTEvent;
import java.awt.Event;
/** {@collect.stats}
* A semantic event which indicates that a component-defined action occurred.
* This high-level event is generated by a component (such as a
* <code>Button</code>) when
* the component-specific action occurs (such as being pressed).
* The event is passed to every <code>ActionListener</code> object
* that registered to receive such events using the component's
* <code>addActionListener</code> method.
* <p>
* <b>Note:</b> To invoke an <code>ActionEvent</code> on a
* <code>Button</code> using the keyboard, use the Space bar.
* <P>
* The object that implements the <code>ActionListener</code> interface
* gets this <code>ActionEvent</code> when the event occurs. The listener
* is therefore spared the details of processing individual mouse movements
* and mouse clicks, and can instead process a "meaningful" (semantic)
* event like "button pressed".
*
* @see ActionListener
* @see <a href="http://java.sun.com/docs/books/tutorial/post1.0/ui/eventmodel.html">Tutorial: Java 1.1 Event Model</a>
*
* @author Carl Quinn
* @since 1.1
*/
public class ActionEvent extends AWTEvent {
/** {@collect.stats}
* The shift modifier. An indicator that the shift key was held
* down during the event.
*/
public static final int SHIFT_MASK = Event.SHIFT_MASK;
/** {@collect.stats}
* The control modifier. An indicator that the control key was held
* down during the event.
*/
public static final int CTRL_MASK = Event.CTRL_MASK;
/** {@collect.stats}
* The meta modifier. An indicator that the meta key was held
* down during the event.
*/
public static final int META_MASK = Event.META_MASK;
/** {@collect.stats}
* The alt modifier. An indicator that the alt key was held
* down during the event.
*/
public static final int ALT_MASK = Event.ALT_MASK;
/** {@collect.stats}
* The first number in the range of ids used for action events.
*/
public static final int ACTION_FIRST = 1001;
/** {@collect.stats}
* The last number in the range of ids used for action events.
*/
public static final int ACTION_LAST = 1001;
/** {@collect.stats}
* This event id indicates that a meaningful action occured.
*/
public static final int ACTION_PERFORMED = ACTION_FIRST; //Event.ACTION_EVENT
/** {@collect.stats}
* The nonlocalized string that gives more details
* of what actually caused the event.
* This information is very specific to the component
* that fired it.
* @serial
* @see #getActionCommand
*/
String actionCommand;
/** {@collect.stats}
* Timestamp of when this event occurred. Because an ActionEvent is a high-
* level, semantic event, the timestamp is typically the same as an
* underlying InputEvent.
*
* @serial
* @see #getWhen
*/
long when;
/** {@collect.stats}
* This represents the key modifier that was selected,
* and is used to determine the state of the selected key.
* If no modifier has been selected it will default to
* zero.
*
* @serial
* @see #getModifiers
*/
int modifiers;
/*
* JDK 1.1 serialVersionUID
*/
private static final long serialVersionUID = -7671078796273832149L;
/** {@collect.stats}
* Constructs an <code>ActionEvent</code> object.
* <p>
* Note that passing in an invalid <code>id</code> results in
* unspecified behavior. This method throws an
* <code>IllegalArgumentException</code> if <code>source</code>
* is <code>null</code>.
* A <code>null</code> <code>command</code> string is legal,
* but not recommended.
*
* @param source the object that originated the event
* @param id an integer that identifies the event
* @param command a string that may specify a command (possibly one
* of several) associated with the event
* @throws IllegalArgumentException if <code>source</code> is null
*/
public ActionEvent(Object source, int id, String command) {
this(source, id, command, 0);
}
/** {@collect.stats}
* Constructs an <code>ActionEvent</code> object with modifier keys.
* <p>
* Note that passing in an invalid <code>id</code> results in
* unspecified behavior. This method throws an
* <code>IllegalArgumentException</code> if <code>source</code>
* is <code>null</code>.
* A <code>null</code> <code>command</code> string is legal,
* but not recommended.
*
* @param source the object that originated the event
* @param id an integer that identifies the event
* @param command a string that may specify a command (possibly one
* of several) associated with the event
* @param modifiers the modifier keys held down during this action
* @throws IllegalArgumentException if <code>source</code> is null
*/
public ActionEvent(Object source, int id, String command, int modifiers) {
this(source, id, command, 0, modifiers);
}
/** {@collect.stats}
* Constructs an <code>ActionEvent</code> object with the specified
* modifier keys and timestamp.
* <p>
* Note that passing in an invalid <code>id</code> results in
* unspecified behavior. This method throws an
* <code>IllegalArgumentException</code> if <code>source</code>
* is <code>null</code>.
* A <code>null</code> <code>command</code> string is legal,
* but not recommended.
*
* @param source the object that originated the event
* @param id an integer that identifies the event
* @param command a string that may specify a command (possibly one
* of several) associated with the event
* @param when the time the event occurred
* @param modifiers the modifier keys held down during this action
* @throws IllegalArgumentException if <code>source</code> is null
*
* @since 1.4
*/
public ActionEvent(Object source, int id, String command, long when,
int modifiers) {
super(source, id);
this.actionCommand = command;
this.when = when;
this.modifiers = modifiers;
}
/** {@collect.stats}
* Returns the command string associated with this action.
* This string allows a "modal" component to specify one of several
* commands, depending on its state. For example, a single button might
* toggle between "show details" and "hide details". The source object
* and the event would be the same in each case, but the command string
* would identify the intended action.
* <p>
* Note that if a <code>null</code> command string was passed
* to the constructor for this <code>ActionEvent</code>, this
* this method returns <code>null</code>.
*
* @return the string identifying the command for this event
*/
public String getActionCommand() {
return actionCommand;
}
/** {@collect.stats}
* Returns the timestamp of when this event occurred. Because an
* ActionEvent is a high-level, semantic event, the timestamp is typically
* the same as an underlying InputEvent.
*
* @return this event's timestamp
* @since 1.4
*/
public long getWhen() {
return when;
}
/** {@collect.stats}
* Returns the modifier keys held down during this action event.
*
* @return the bitwise-or of the modifier constants
*/
public int getModifiers() {
return modifiers;
}
/** {@collect.stats}
* Returns a parameter string identifying this action event.
* This method is useful for event-logging and for debugging.
*
* @return a string identifying the event and its associated command
*/
public String paramString() {
String typeStr;
switch(id) {
case ACTION_PERFORMED:
typeStr = "ACTION_PERFORMED";
break;
default:
typeStr = "unknown type";
}
return typeStr + ",cmd="+actionCommand+",when="+when+",modifiers="+
KeyEvent.getKeyModifiersText(modifiers);
}
}
|
Java
|
/*
* Copyright (c) 1996, 2007, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code 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
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package java.awt.event;
import java.awt.AWTEvent;
import java.awt.Component;
import java.awt.Rectangle;
/** {@collect.stats}
* A low-level event which indicates that a component moved, changed
* size, or changed visibility (also, the root class for the other
* component-level events).
* <P>
* Component events are provided for notification purposes ONLY;
* The AWT will automatically handle component moves and resizes
* internally so that GUI layout works properly regardless of
* whether a program is receiving these events or not.
* <P>
* In addition to serving as the base class for other component-related
* events (InputEvent, FocusEvent, WindowEvent, ContainerEvent),
* this class defines the events that indicate changes in
* a component's size, position, or visibility.
* <P>
* This low-level event is generated by a component object (such as a
* List) when the component is moved, resized, rendered invisible, or made
* visible again. The event is passed to every <code>ComponentListener</code>
* or <code>ComponentAdapter</code> object which registered to receive such
* events using the component's <code>addComponentListener</code> method.
* (<code>ComponentAdapter</code> objects implement the
* <code>ComponentListener</code> interface.) Each such listener object
* gets this <code>ComponentEvent</code> when the event occurs.
*
* @see ComponentAdapter
* @see ComponentListener
* @see <a href="http://java.sun.com/docs/books/tutorial/post1.0/ui/componentlistener.html">Tutorial: Writing a Component Listener</a>
*
* @author Carl Quinn
* @since 1.1
*/
public class ComponentEvent extends AWTEvent {
/** {@collect.stats}
* The first number in the range of ids used for component events.
*/
public static final int COMPONENT_FIRST = 100;
/** {@collect.stats}
* The last number in the range of ids used for component events.
*/
public static final int COMPONENT_LAST = 103;
/** {@collect.stats}
* This event indicates that the component's position changed.
*/
public static final int COMPONENT_MOVED = COMPONENT_FIRST;
/** {@collect.stats}
* This event indicates that the component's size changed.
*/
public static final int COMPONENT_RESIZED = 1 + COMPONENT_FIRST;
/** {@collect.stats}
* This event indicates that the component was made visible.
*/
public static final int COMPONENT_SHOWN = 2 + COMPONENT_FIRST;
/** {@collect.stats}
* This event indicates that the component was rendered invisible.
*/
public static final int COMPONENT_HIDDEN = 3 + COMPONENT_FIRST;
/*
* JDK 1.1 serialVersionUID
*/
private static final long serialVersionUID = 8101406823902992965L;
/** {@collect.stats}
* Constructs a <code>ComponentEvent</code> object.
* <p>Note that passing in an invalid <code>id</code> results in
* unspecified behavior. This method throws an
* <code>IllegalArgumentException</code> if <code>source</code>
* is <code>null</code>.
*
* @param source the <code>Component</code> that originated the event
* @param id an integer indicating the type of event
* @throws IllegalArgumentException if <code>source</code> is null
*/
public ComponentEvent(Component source, int id) {
super(source, id);
}
/** {@collect.stats}
* Returns the originator of the event.
*
* @return the <code>Component</code> object that originated
* the event, or <code>null</code> if the object is not a
* <code>Component</code>.
*/
public Component getComponent() {
return (source instanceof Component) ? (Component)source : null;
}
/** {@collect.stats}
* Returns a parameter string identifying this event.
* This method is useful for event-logging and for debugging.
*
* @return a string identifying the event and its attributes
*/
public String paramString() {
String typeStr;
Rectangle b = (source !=null
? ((Component)source).getBounds()
: null);
switch(id) {
case COMPONENT_SHOWN:
typeStr = "COMPONENT_SHOWN";
break;
case COMPONENT_HIDDEN:
typeStr = "COMPONENT_HIDDEN";
break;
case COMPONENT_MOVED:
typeStr = "COMPONENT_MOVED ("+
b.x+","+b.y+" "+b.width+"x"+b.height+")";
break;
case COMPONENT_RESIZED:
typeStr = "COMPONENT_RESIZED ("+
b.x+","+b.y+" "+b.width+"x"+b.height+")";
break;
default:
typeStr = "unknown type";
}
return typeStr;
}
}
|
Java
|
/*
* Copyright (c) 1996, 2006, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code 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
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package java.awt.event;
import java.util.EventListener;
/** {@collect.stats}
* The listener interface for receiving action events.
* The class that is interested in processing an action event
* implements this interface, and the object created with that
* class is registered with a component, using the component's
* <code>addActionListener</code> method. When the action event
* occurs, that object's <code>actionPerformed</code> method is
* invoked.
*
* @see ActionEvent
* @see <a href="http://java.sun.com/docs/books/tutorial/post1.0/ui/eventmodel.html">Tutorial: Java 1.1 Event Model</a>
*
* @author Carl Quinn
* @since 1.1
*/
public interface ActionListener extends EventListener {
/** {@collect.stats}
* Invoked when an action occurs.
*/
public void actionPerformed(ActionEvent e);
}
|
Java
|
/*
* Copyright (c) 1996, 2006, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code 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
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package java.awt.event;
/** {@collect.stats}
* An abstract adapter class for receiving component events.
* The methods in this class are empty. This class exists as
* convenience for creating listener objects.
* <P>
* Extend this class to create a <code>ComponentEvent</code> listener
* and override the methods for the events of interest. (If you implement the
* <code>ComponentListener</code> interface, you have to define all of
* the methods in it. This abstract class defines null methods for them
* all, so you can only have to define methods for events you care about.)
* <P>
* Create a listener object using your class and then register it with a
* component using the component's <code>addComponentListener</code>
* method. When the component's size, location, or visibility
* changes, the relevant method in the listener object is invoked,
* and the <code>ComponentEvent</code> is passed to it.
*
* @see ComponentEvent
* @see ComponentListener
* @see <a href="http://java.sun.com/docs/books/tutorial/post1.0/ui/componentlistener.html">Tutorial: Writing a Component Listener</a>
*
* @author Carl Quinn
* @since 1.1
*/
public abstract class ComponentAdapter implements ComponentListener {
/** {@collect.stats}
* Invoked when the component's size changes.
*/
public void componentResized(ComponentEvent e) {}
/** {@collect.stats}
* Invoked when the component's position changes.
*/
public void componentMoved(ComponentEvent e) {}
/** {@collect.stats}
* Invoked when the component has been made visible.
*/
public void componentShown(ComponentEvent e) {}
/** {@collect.stats}
* Invoked when the component has been made invisible.
*/
public void componentHidden(ComponentEvent e) {}
}
|
Java
|
/*
* Copyright (c) 1996, 2007, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code 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
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package java.awt.event;
import java.awt.AWTEvent;
/** {@collect.stats}
* A semantic event which indicates that an object's text changed.
* This high-level event is generated by an object (such as a TextComponent)
* when its text changes. The event is passed to
* every <code>TextListener</code> object which registered to receive such
* events using the component's <code>addTextListener</code> method.
* <P>
* The object that implements the <code>TextListener</code> interface gets
* this <code>TextEvent</code> when the event occurs. The listener is
* spared the details of processing individual mouse movements and key strokes
* Instead, it can process a "meaningful" (semantic) event like "text changed".
*
* @author Georges Saab
*
* @see java.awt.TextComponent
* @see TextListener
* @see <a href="http://java.sun.com/docs/books/tutorial/post1.0/ui/textlistener.html">Tutorial: Writing a Text Listener</a>
*
* @since 1.1
*/
public class TextEvent extends AWTEvent {
/** {@collect.stats}
* The first number in the range of ids used for text events.
*/
public static final int TEXT_FIRST = 900;
/** {@collect.stats}
* The last number in the range of ids used for text events.
*/
public static final int TEXT_LAST = 900;
/** {@collect.stats}
* This event id indicates that object's text changed.
*/
public static final int TEXT_VALUE_CHANGED = TEXT_FIRST;
/*
* JDK 1.1 serialVersionUID
*/
private static final long serialVersionUID = 6269902291250941179L;
/** {@collect.stats}
* Constructs a <code>TextEvent</code> object.
* <p>Note that passing in an invalid <code>id</code> results in
* unspecified behavior. This method throws an
* <code>IllegalArgumentException</code> if <code>source</code>
* is <code>null</code>.
*
* @param source the (<code>TextComponent</code>) object that
* originated the event
* @param id an integer that identifies the event type
* @throws IllegalArgumentException if <code>source</code> is null
*/
public TextEvent(Object source, int id) {
super(source, id);
}
/** {@collect.stats}
* Returns a parameter string identifying this text event.
* This method is useful for event-logging and for debugging.
*
* @return a string identifying the event and its attributes
*/
public String paramString() {
String typeStr;
switch(id) {
case TEXT_VALUE_CHANGED:
typeStr = "TEXT_VALUE_CHANGED";
break;
default:
typeStr = "unknown type";
}
return typeStr;
}
}
|
Java
|
/*
* Copyright (c) 1999, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code 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
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package java.awt.event;
/** {@collect.stats}
* An abstract adapter class for receiving ancestor moved and resized events.
* The methods in this class are empty. This class exists as a
* convenience for creating listener objects.
* <p>
* Extend this class and override the method for the event of interest. (If
* you implement the <code>HierarchyBoundsListener</code> interface, you have
* to define both methods in it. This abstract class defines null methods for
* them both, so you only have to define the method for the event you care
* about.)
* <p>
* Create a listener object using your class and then register it with a
* Component using the Component's <code>addHierarchyBoundsListener</code>
* method. When the hierarchy to which the Component belongs changes by
* resize or movement of an ancestor, the relevant method in the listener
* object is invoked, and the <code>HierarchyEvent</code> is passed to it.
*
* @author David Mendenhall
* @see HierarchyBoundsListener
* @see HierarchyEvent
* @since 1.3
*/
public abstract class HierarchyBoundsAdapter implements HierarchyBoundsListener
{
/** {@collect.stats}
* Called when an ancestor of the source is moved.
*/
public void ancestorMoved(HierarchyEvent e) {}
/** {@collect.stats}
* Called when an ancestor of the source is resized.
*/
public void ancestorResized(HierarchyEvent e) {}
}
|
Java
|
/*
* Copyright (c) 2001, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code 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
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package java.awt.event;
import java.util.EventListener;
/** {@collect.stats}
* The listener interface for receiving window state events.
* <p>
* The class that is interested in processing a window state event
* either implements this interface (and all the methods it contains)
* or extends the abstract <code>WindowAdapter</code> class
* (overriding only the methods of interest).
* <p>
* The listener object created from that class is then registered with
* a window using the <code>Window</code>'s
* <code>addWindowStateListener</code> method. When the window's
* state changes by virtue of being iconified, maximized etc., the
* <code>windowStateChanged</code> method in the listener object is
* invoked, and the <code>WindowEvent</code> is passed to it.
*
* @see java.awt.event.WindowAdapter
* @see java.awt.event.WindowEvent
*
* @since 1.4
*/
public interface WindowStateListener extends EventListener {
/** {@collect.stats}
* Invoked when window state is changed.
*/
public void windowStateChanged(WindowEvent e);
}
|
Java
|
/*
* Copyright (c) 1997, 2007, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code 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
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package java.awt.event;
import java.awt.AWTEvent;
import java.awt.Component;
import java.awt.EventQueue;
import java.awt.font.TextHitInfo;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.text.AttributedCharacterIterator;
import java.text.CharacterIterator;
/** {@collect.stats}
* Input method events contain information about text that is being
* composed using an input method. Whenever the text changes, the
* input method sends an event. If the text component that's currently
* using the input method is an active client, the event is dispatched
* to that component. Otherwise, it is dispatched to a separate
* composition window.
*
* <p>
* The text included with the input method event consists of two parts:
* committed text and composed text. Either part may be empty. The two
* parts together replace any uncommitted composed text sent in previous events,
* or the currently selected committed text.
* Committed text should be integrated into the text component's persistent
* data, it will not be sent again. Composed text may be sent repeatedly,
* with changes to reflect the user's editing operations. Committed text
* always precedes composed text.
*
* @author JavaSoft Asia/Pacific
* @since 1.2
*/
public class InputMethodEvent extends AWTEvent {
/** {@collect.stats}
* Serial Version ID.
*/
private static final long serialVersionUID = 4727190874778922661L;
/** {@collect.stats}
* Marks the first integer id for the range of input method event ids.
*/
public static final int INPUT_METHOD_FIRST = 1100;
/** {@collect.stats}
* The event type indicating changed input method text. This event is
* generated by input methods while processing input.
*/
public static final int INPUT_METHOD_TEXT_CHANGED = INPUT_METHOD_FIRST;
/** {@collect.stats}
* The event type indicating a changed insertion point in input method text.
* This event is
* generated by input methods while processing input if only the caret changed.
*/
public static final int CARET_POSITION_CHANGED = INPUT_METHOD_FIRST + 1;
/** {@collect.stats}
* Marks the last integer id for the range of input method event ids.
*/
public static final int INPUT_METHOD_LAST = INPUT_METHOD_FIRST + 1;
/** {@collect.stats}
* The time stamp that indicates when the event was created.
*
* @serial
* @see #getWhen
* @since 1.4
*/
long when;
// Text object
private transient AttributedCharacterIterator text;
private transient int committedCharacterCount;
private transient TextHitInfo caret;
private transient TextHitInfo visiblePosition;
/** {@collect.stats}
* Constructs an <code>InputMethodEvent</code> with the specified
* source component, type, time, text, caret, and visiblePosition.
* <p>
* The offsets of caret and visiblePosition are relative to the current
* composed text; that is, the composed text within <code>text</code>
* if this is an <code>INPUT_METHOD_TEXT_CHANGED</code> event,
* the composed text within the <code>text</code> of the
* preceding <code>INPUT_METHOD_TEXT_CHANGED</code> event otherwise.
* <p>Note that passing in an invalid <code>id</code> results in
* unspecified behavior. This method throws an
* <code>IllegalArgumentException</code> if <code>source</code>
* is <code>null</code>.
*
* @param source the object where the event originated
* @param id the event type
* @param when a long integer that specifies the time the event occurred
* @param text the combined committed and composed text,
* committed text first; must be <code>null</code>
* when the event type is <code>CARET_POSITION_CHANGED</code>;
* may be <code>null</code> for
* <code>INPUT_METHOD_TEXT_CHANGED</code> if there's no
* committed or composed text
* @param committedCharacterCount the number of committed
* characters in the text
* @param caret the caret (a.k.a. insertion point);
* <code>null</code> if there's no caret within current
* composed text
* @param visiblePosition the position that's most important
* to be visible; <code>null</code> if there's no
* recommendation for a visible position within current
* composed text
* @throws IllegalArgumentException if <code>id</code> is not
* in the range
* <code>INPUT_METHOD_FIRST</code>..<code>INPUT_METHOD_LAST</code>;
* or if id is <code>CARET_POSITION_CHANGED</code> and
* <code>text</code> is not <code>null</code>;
* or if <code>committedCharacterCount</code> is not in the range
* <code>0</code>..<code>(text.getEndIndex() - text.getBeginIndex())</code>
* @throws IllegalArgumentException if <code>source</code> is null
*
* @since 1.4
*/
public InputMethodEvent(Component source, int id, long when,
AttributedCharacterIterator text, int committedCharacterCount,
TextHitInfo caret, TextHitInfo visiblePosition) {
super(source, id);
if (id < INPUT_METHOD_FIRST || id > INPUT_METHOD_LAST) {
throw new IllegalArgumentException("id outside of valid range");
}
if (id == CARET_POSITION_CHANGED && text != null) {
throw new IllegalArgumentException("text must be null for CARET_POSITION_CHANGED");
}
this.when = when;
this.text = text;
int textLength = 0;
if (text != null) {
textLength = text.getEndIndex() - text.getBeginIndex();
}
if (committedCharacterCount < 0 || committedCharacterCount > textLength) {
throw new IllegalArgumentException("committedCharacterCount outside of valid range");
}
this.committedCharacterCount = committedCharacterCount;
this.caret = caret;
this.visiblePosition = visiblePosition;
}
/** {@collect.stats}
* Constructs an <code>InputMethodEvent</code> with the specified
* source component, type, text, caret, and visiblePosition.
* <p>
* The offsets of caret and visiblePosition are relative to the current
* composed text; that is, the composed text within <code>text</code>
* if this is an <code>INPUT_METHOD_TEXT_CHANGED</code> event,
* the composed text within the <code>text</code> of the
* preceding <code>INPUT_METHOD_TEXT_CHANGED</code> event otherwise.
* The time stamp for this event is initialized by invoking
* {@link java.awt.EventQueue#getMostRecentEventTime()}.
* <p>Note that passing in an invalid <code>id</code> results in
* unspecified behavior. This method throws an
* <code>IllegalArgumentException</code> if <code>source</code>
* is <code>null</code>.
*
* @param source the object where the event originated
* @param id the event type
* @param text the combined committed and composed text,
* committed text first; must be <code>null</code>
* when the event type is <code>CARET_POSITION_CHANGED</code>;
* may be <code>null</code> for
* <code>INPUT_METHOD_TEXT_CHANGED</code> if there's no
* committed or composed text
* @param committedCharacterCount the number of committed
* characters in the text
* @param caret the caret (a.k.a. insertion point);
* <code>null</code> if there's no caret within current
* composed text
* @param visiblePosition the position that's most important
* to be visible; <code>null</code> if there's no
* recommendation for a visible position within current
* composed text
* @throws IllegalArgumentException if <code>id</code> is not
* in the range
* <code>INPUT_METHOD_FIRST</code>..<code>INPUT_METHOD_LAST</code>;
* or if id is <code>CARET_POSITION_CHANGED</code> and
* <code>text</code> is not <code>null</code>;
* or if <code>committedCharacterCount</code> is not in the range
* <code>0</code>..<code>(text.getEndIndex() - text.getBeginIndex())</code>
* @throws IllegalArgumentException if <code>source</code> is null
*/
public InputMethodEvent(Component source, int id,
AttributedCharacterIterator text, int committedCharacterCount,
TextHitInfo caret, TextHitInfo visiblePosition) {
this(source, id, EventQueue.getMostRecentEventTime(), text,
committedCharacterCount, caret, visiblePosition);
}
/** {@collect.stats}
* Constructs an <code>InputMethodEvent</code> with the
* specified source component, type, caret, and visiblePosition.
* The text is set to <code>null</code>,
* <code>committedCharacterCount</code> to 0.
* <p>
* The offsets of <code>caret</code> and <code>visiblePosition</code>
* are relative to the current composed text; that is,
* the composed text within the <code>text</code> of the
* preceding <code>INPUT_METHOD_TEXT_CHANGED</code> event if the
* event being constructed as a <code>CARET_POSITION_CHANGED</code> event.
* For an <code>INPUT_METHOD_TEXT_CHANGED</code> event without text,
* <code>caret</code> and <code>visiblePosition</code> must be
* <code>null</code>.
* The time stamp for this event is initialized by invoking
* {@link java.awt.EventQueue#getMostRecentEventTime()}.
* <p>Note that passing in an invalid <code>id</code> results in
* unspecified behavior. This method throws an
* <code>IllegalArgumentException</code> if <code>source</code>
* is <code>null</code>.
*
* @param source the object where the event originated
* @param id the event type
* @param caret the caret (a.k.a. insertion point);
* <code>null</code> if there's no caret within current
* composed text
* @param visiblePosition the position that's most important
* to be visible; <code>null</code> if there's no
* recommendation for a visible position within current
* composed text
* @throws IllegalArgumentException if <code>id</code> is not
* in the range
* <code>INPUT_METHOD_FIRST</code>..<code>INPUT_METHOD_LAST</code>
* @throws IllegalArgumentException if <code>source</code> is null
*/
public InputMethodEvent(Component source, int id, TextHitInfo caret,
TextHitInfo visiblePosition) {
this(source, id, EventQueue.getMostRecentEventTime(), null,
0, caret, visiblePosition);
}
/** {@collect.stats}
* Gets the combined committed and composed text.
* Characters from index 0 to index <code>getCommittedCharacterCount() - 1</code> are committed
* text, the remaining characters are composed text.
*
* @return the text.
* Always null for CARET_POSITION_CHANGED;
* may be null for INPUT_METHOD_TEXT_CHANGED if there's no composed or committed text.
*/
public AttributedCharacterIterator getText() {
return text;
}
/** {@collect.stats}
* Gets the number of committed characters in the text.
*/
public int getCommittedCharacterCount() {
return committedCharacterCount;
}
/** {@collect.stats}
* Gets the caret.
* <p>
* The offset of the caret is relative to the current
* composed text; that is, the composed text within getText()
* if this is an <code>INPUT_METHOD_TEXT_CHANGED</code> event,
* the composed text within getText() of the
* preceding <code>INPUT_METHOD_TEXT_CHANGED</code> event otherwise.
*
* @return the caret (a.k.a. insertion point).
* Null if there's no caret within current composed text.
*/
public TextHitInfo getCaret() {
return caret;
}
/** {@collect.stats}
* Gets the position that's most important to be visible.
* <p>
* The offset of the visible position is relative to the current
* composed text; that is, the composed text within getText()
* if this is an <code>INPUT_METHOD_TEXT_CHANGED</code> event,
* the composed text within getText() of the
* preceding <code>INPUT_METHOD_TEXT_CHANGED</code> event otherwise.
*
* @return the position that's most important to be visible.
* Null if there's no recommendation for a visible position within current composed text.
*/
public TextHitInfo getVisiblePosition() {
return visiblePosition;
}
/** {@collect.stats}
* Consumes this event so that it will not be processed
* in the default manner by the source which originated it.
*/
public void consume() {
consumed = true;
}
/** {@collect.stats}
* Returns whether or not this event has been consumed.
* @see #consume
*/
public boolean isConsumed() {
return consumed;
}
/** {@collect.stats}
* Returns the time stamp of when this event occurred.
*
* @return this event's timestamp
* @since 1.4
*/
public long getWhen() {
return when;
}
/** {@collect.stats}
* Returns a parameter string identifying this event.
* This method is useful for event-logging and for debugging.
* It contains the event ID in text form, the characters of the
* committed and composed text
* separated by "+", the number of committed characters,
* the caret, and the visible position.
*
* @return a string identifying the event and its attributes
*/
public String paramString() {
String typeStr;
switch(id) {
case INPUT_METHOD_TEXT_CHANGED:
typeStr = "INPUT_METHOD_TEXT_CHANGED";
break;
case CARET_POSITION_CHANGED:
typeStr = "CARET_POSITION_CHANGED";
break;
default:
typeStr = "unknown type";
}
String textString;
if (text == null) {
textString = "no text";
} else {
StringBuilder textBuffer = new StringBuilder("\"");
int committedCharacterCount = this.committedCharacterCount;
char c = text.first();
while (committedCharacterCount-- > 0) {
textBuffer.append(c);
c = text.next();
}
textBuffer.append("\" + \"");
while (c != CharacterIterator.DONE) {
textBuffer.append(c);
c = text.next();
}
textBuffer.append("\"");
textString = textBuffer.toString();
}
String countString = committedCharacterCount + " characters committed";
String caretString;
if (caret == null) {
caretString = "no caret";
} else {
caretString = "caret: " + caret.toString();
}
String visiblePositionString;
if (visiblePosition == null) {
visiblePositionString = "no visible position";
} else {
visiblePositionString = "visible position: " + visiblePosition.toString();
}
return typeStr + ", " + textString + ", " + countString + ", " + caretString + ", " + visiblePositionString;
}
/** {@collect.stats}
* Initializes the <code>when</code> field if it is not present in the
* object input stream. In that case, the field will be initialized by
* invoking {@link java.awt.EventQueue#getMostRecentEventTime()}.
*/
private void readObject(ObjectInputStream s) throws ClassNotFoundException, IOException {
s.defaultReadObject();
if (when == 0) {
when = EventQueue.getMostRecentEventTime();
}
}
}
|
Java
|
/*
* Copyright (c) 2001, 2007, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code 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
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package java.awt.event;
import java.util.EventListenerProxy;
import java.awt.AWTEvent;
/** {@collect.stats}
* A class which extends the <code>EventListenerProxy</code>, specifically
* for adding an <code>AWTEventListener</code> for a specific event mask.
* Instances of this class can be added as <code>AWTEventListener</code>s to
* a Toolkit object.
* <p>
* The <code>getAWTEventListeners</code> method of Toolkit can
* return a mixture of <code>AWTEventListener</code> and
* <code>AWTEventListenerProxy</code> objects.
*
* @see java.awt.Toolkit
* @see java.util.EventListenerProxy
* @since 1.4
*/
public class AWTEventListenerProxy extends java.util.EventListenerProxy
implements AWTEventListener {
private long eventMask;
/** {@collect.stats}
* Constructor which binds the AWTEventListener to a specific
* event mask.
*
* @param listener The listener object
* @param eventMask The bitmap of event types to receive
*/
public AWTEventListenerProxy (long eventMask,
AWTEventListener listener) {
super(listener);
this.eventMask = eventMask;
}
/** {@collect.stats}
* Forwards the property change event to the listener delegate.
*
* @param evt the property change event
*/
public void eventDispatched(AWTEvent evt) {
((AWTEventListener)getListener()).eventDispatched(evt);
}
/** {@collect.stats}
* Returns the event mask associated with the
* listener.
*/
public long getEventMask() {
return eventMask;
}
}
|
Java
|
/*
* Copyright (c) 1996, 2006, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code 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
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package java.awt.event;
import java.util.EventListener;
/** {@collect.stats}
* The listener interface for receiving keyboard focus events on
* a component.
* The class that is interested in processing a focus event
* either implements this interface (and all the methods it
* contains) or extends the abstract <code>FocusAdapter</code> class
* (overriding only the methods of interest).
* The listener object created from that class is then registered with a
* component using the component's <code>addFocusListener</code>
* method. When the component gains or loses the keyboard focus,
* the relevant method in the listener object
* is invoked, and the <code>FocusEvent</code> is passed to it.
*
* @see FocusAdapter
* @see FocusEvent
* @see <a href="http://java.sun.com/docs/books/tutorial/post1.0/ui/focuslistener.html">Tutorial: Writing a Focus Listener</a>
*
* @author Carl Quinn
* @since 1.1
*/
public interface FocusListener extends EventListener {
/** {@collect.stats}
* Invoked when a component gains the keyboard focus.
*/
public void focusGained(FocusEvent e);
/** {@collect.stats}
* Invoked when a component loses the keyboard focus.
*/
public void focusLost(FocusEvent e);
}
|
Java
|
/*
* Copyright (c) 1996, 2007, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code 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
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package java.awt.event;
import java.awt.Event;
import java.awt.Component;
import java.awt.GraphicsEnvironment;
import java.awt.Toolkit;
import java.util.logging.Logger;
import java.util.logging.Level;
/** {@collect.stats}
* The root event class for all component-level input events.
*
* Input events are delivered to listeners before they are
* processed normally by the source where they originated.
* This allows listeners and component subclasses to "consume"
* the event so that the source will not process them in their
* default manner. For example, consuming mousePressed events
* on a Button component will prevent the Button from being
* activated.
*
* @author Carl Quinn
*
* @see KeyEvent
* @see KeyAdapter
* @see MouseEvent
* @see MouseAdapter
* @see MouseMotionAdapter
*
* @since 1.1
*/
public abstract class InputEvent extends ComponentEvent {
private static final Logger log = Logger.getLogger("java.awt.event.InputEvent");
/** {@collect.stats}
* The Shift key modifier constant.
* It is recommended that SHIFT_DOWN_MASK be used instead.
*/
public static final int SHIFT_MASK = Event.SHIFT_MASK;
/** {@collect.stats}
* The Control key modifier constant.
* It is recommended that CTRL_DOWN_MASK be used instead.
*/
public static final int CTRL_MASK = Event.CTRL_MASK;
/** {@collect.stats}
* The Meta key modifier constant.
* It is recommended that META_DOWN_MASK be used instead.
*/
public static final int META_MASK = Event.META_MASK;
/** {@collect.stats}
* The Alt key modifier constant.
* It is recommended that ALT_DOWN_MASK be used instead.
*/
public static final int ALT_MASK = Event.ALT_MASK;
/** {@collect.stats}
* The AltGraph key modifier constant.
*/
public static final int ALT_GRAPH_MASK = 1 << 5;
/** {@collect.stats}
* The Mouse Button1 modifier constant.
* It is recommended that BUTTON1_DOWN_MASK be used instead.
*/
public static final int BUTTON1_MASK = 1 << 4;
/** {@collect.stats}
* The Mouse Button2 modifier constant.
* It is recommended that BUTTON2_DOWN_MASK be used instead.
* Note that BUTTON2_MASK has the same value as ALT_MASK.
*/
public static final int BUTTON2_MASK = Event.ALT_MASK;
/** {@collect.stats}
* The Mouse Button3 modifier constant.
* It is recommended that BUTTON3_DOWN_MASK be used instead.
* Note that BUTTON3_MASK has the same value as META_MASK.
*/
public static final int BUTTON3_MASK = Event.META_MASK;
/** {@collect.stats}
* The Shift key extended modifier constant.
* @since 1.4
*/
public static final int SHIFT_DOWN_MASK = 1 << 6;
/** {@collect.stats}
* The Control key extended modifier constant.
* @since 1.4
*/
public static final int CTRL_DOWN_MASK = 1 << 7;
/** {@collect.stats}
* The Meta key extended modifier constant.
* @since 1.4
*/
public static final int META_DOWN_MASK = 1 << 8;
/** {@collect.stats}
* The Alt key extended modifier constant.
* @since 1.4
*/
public static final int ALT_DOWN_MASK = 1 << 9;
/** {@collect.stats}
* The Mouse Button1 extended modifier constant.
* @since 1.4
*/
public static final int BUTTON1_DOWN_MASK = 1 << 10;
/** {@collect.stats}
* The Mouse Button2 extended modifier constant.
* @since 1.4
*/
public static final int BUTTON2_DOWN_MASK = 1 << 11;
/** {@collect.stats}
* The Mouse Button3 extended modifier constant.
* @since 1.4
*/
public static final int BUTTON3_DOWN_MASK = 1 << 12;
/** {@collect.stats}
* The AltGraph key extended modifier constant.
* @since 1.4
*/
public static final int ALT_GRAPH_DOWN_MASK = 1 << 13;
// the constant below MUST be updated if any extra modifier
// bits are to be added!
// in fact, it is undesirable to add modifier bits
// to the same field as this may break applications
// see bug# 5066958
static final int FIRST_HIGH_BIT = 1 << 14;
static final int JDK_1_3_MODIFIERS = SHIFT_DOWN_MASK - 1;
static final int HIGH_MODIFIERS = ~( FIRST_HIGH_BIT - 1 );
/** {@collect.stats}
* The input event's Time stamp in UTC format. The time stamp
* indicates when the input event was created.
*
* @serial
* @see #getWhen()
*/
long when;
/** {@collect.stats}
* The state of the modifier mask at the time the input
* event was fired.
*
* @serial
* @see #getModifiers()
* @see #getModifiersEx()
* @see java.awt.event.KeyEvent
* @see java.awt.event.MouseEvent
*/
int modifiers;
/*
* A flag that indicates that this instance can be used to access
* the system clipboard.
*/
private transient boolean canAccessSystemClipboard;
static {
/* ensure that the necessary native libraries are loaded */
NativeLibLoader.loadLibraries();
if (!GraphicsEnvironment.isHeadless()) {
initIDs();
}
}
/** {@collect.stats}
* Initialize JNI field and method IDs for fields that may be
accessed from C.
*/
private static native void initIDs();
/** {@collect.stats}
* Constructs an InputEvent object with the specified source component,
* modifiers, and type.
* <p>Note that passing in an invalid <code>id</code> results in
* unspecified behavior. This method throws an
* <code>IllegalArgumentException</code> if <code>source</code>
* is <code>null</code>.
*
* @param source the object where the event originated
* @param id the event type
* @param when the time the event occurred
* @param modifiers represents the modifier keys and mouse buttons down
* while the event occurred
* @throws IllegalArgumentException if <code>source</code> is null
*/
InputEvent(Component source, int id, long when, int modifiers) {
super(source, id);
this.when = when;
this.modifiers = modifiers;
canAccessSystemClipboard = canAccessSystemClipboard();
}
private boolean canAccessSystemClipboard() {
boolean b = false;
if (!GraphicsEnvironment.isHeadless()) {
SecurityManager sm = System.getSecurityManager();
if (sm != null) {
try {
sm.checkSystemClipboardAccess();
b = true;
} catch (SecurityException se) {
if (log.isLoggable(Level.FINE)) {
log.log(Level.FINE, "InputEvent.canAccessSystemClipboard() got SecurityException ", se);
}
}
} else {
b = true;
}
}
return b;
}
/** {@collect.stats}
* Returns whether or not the Shift modifier is down on this event.
*/
public boolean isShiftDown() {
return (modifiers & SHIFT_MASK) != 0;
}
/** {@collect.stats}
* Returns whether or not the Control modifier is down on this event.
*/
public boolean isControlDown() {
return (modifiers & CTRL_MASK) != 0;
}
/** {@collect.stats}
* Returns whether or not the Meta modifier is down on this event.
*/
public boolean isMetaDown() {
return (modifiers & META_MASK) != 0;
}
/** {@collect.stats}
* Returns whether or not the Alt modifier is down on this event.
*/
public boolean isAltDown() {
return (modifiers & ALT_MASK) != 0;
}
/** {@collect.stats}
* Returns whether or not the AltGraph modifier is down on this event.
*/
public boolean isAltGraphDown() {
return (modifiers & ALT_GRAPH_MASK) != 0;
}
/** {@collect.stats}
* Returns the timestamp of when this event occurred.
*/
public long getWhen() {
return when;
}
/** {@collect.stats}
* Returns the modifier mask for this event.
*/
public int getModifiers() {
return modifiers & (JDK_1_3_MODIFIERS | HIGH_MODIFIERS);
}
/** {@collect.stats}
* Returns the extended modifier mask for this event.
* Extended modifiers represent the state of all modal keys,
* such as ALT, CTRL, META, and the mouse buttons just after
* the event occurred
* <P>
* For example, if the user presses <b>button 1</b> followed by
* <b>button 2</b>, and then releases them in the same order,
* the following sequence of events is generated:
* <PRE>
* <code>MOUSE_PRESSED</code>: <code>BUTTON1_DOWN_MASK</code>
* <code>MOUSE_PRESSED</code>: <code>BUTTON1_DOWN_MASK | BUTTON2_DOWN_MASK</code>
* <code>MOUSE_RELEASED</code>: <code>BUTTON2_DOWN_MASK</code>
* <code>MOUSE_CLICKED</code>: <code>BUTTON2_DOWN_MASK</code>
* <code>MOUSE_RELEASED</code>:
* <code>MOUSE_CLICKED</code>:
* </PRE>
* <P>
* It is not recommended to compare the return value of this method
* using <code>==</code> because new modifiers can be added in the future.
* For example, the appropriate way to check that SHIFT and BUTTON1 are
* down, but CTRL is up is demonstrated by the following code:
* <PRE>
* int onmask = SHIFT_DOWN_MASK | BUTTON1_DOWN_MASK;
* int offmask = CTRL_DOWN_MASK;
* if ((event.getModifiersEx() & (onmask | offmask)) == onmask) {
* ...
* }
* </PRE>
* The above code will work even if new modifiers are added.
*
* @since 1.4
*/
public int getModifiersEx() {
return modifiers & ~JDK_1_3_MODIFIERS;
}
/** {@collect.stats}
* Consumes this event so that it will not be processed
* in the default manner by the source which originated it.
*/
public void consume() {
consumed = true;
}
/** {@collect.stats}
* Returns whether or not this event has been consumed.
* @see #consume
*/
public boolean isConsumed() {
return consumed;
}
// state serialization compatibility with JDK 1.1
static final long serialVersionUID = -2482525981698309786L;
/** {@collect.stats}
* Returns a String describing the extended modifier keys and
* mouse buttons, such as "Shift", "Button1", or "Ctrl+Shift".
* These strings can be localized by changing the
* awt.properties file.
*
* @param modifiers a modifier mask describing the extended
* modifier keys and mouse buttons for the event
* @return a text description of the combination of extended
* modifier keys and mouse buttons that were held down
* during the event.
* @since 1.4
*/
public static String getModifiersExText(int modifiers) {
StringBuilder buf = new StringBuilder();
if ((modifiers & InputEvent.META_DOWN_MASK) != 0) {
buf.append(Toolkit.getProperty("AWT.meta", "Meta"));
buf.append("+");
}
if ((modifiers & InputEvent.CTRL_DOWN_MASK) != 0) {
buf.append(Toolkit.getProperty("AWT.control", "Ctrl"));
buf.append("+");
}
if ((modifiers & InputEvent.ALT_DOWN_MASK) != 0) {
buf.append(Toolkit.getProperty("AWT.alt", "Alt"));
buf.append("+");
}
if ((modifiers & InputEvent.SHIFT_DOWN_MASK) != 0) {
buf.append(Toolkit.getProperty("AWT.shift", "Shift"));
buf.append("+");
}
if ((modifiers & InputEvent.ALT_GRAPH_DOWN_MASK) != 0) {
buf.append(Toolkit.getProperty("AWT.altGraph", "Alt Graph"));
buf.append("+");
}
if ((modifiers & InputEvent.BUTTON1_DOWN_MASK) != 0) {
buf.append(Toolkit.getProperty("AWT.button1", "Button1"));
buf.append("+");
}
if ((modifiers & InputEvent.BUTTON2_DOWN_MASK) != 0) {
buf.append(Toolkit.getProperty("AWT.button2", "Button2"));
buf.append("+");
}
if ((modifiers & InputEvent.BUTTON3_DOWN_MASK) != 0) {
buf.append(Toolkit.getProperty("AWT.button3", "Button3"));
buf.append("+");
}
if (buf.length() > 0) {
buf.setLength(buf.length()-1); // remove trailing '+'
}
return buf.toString();
}
}
|
Java
|
/*
* Copyright (c) 1996, 2007, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code 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
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package java.awt.event;
import java.awt.Window;
import sun.awt.AppContext;
import sun.awt.SunToolkit;
/** {@collect.stats}
* A low-level event that indicates that a window has changed its status. This
* low-level event is generated by a Window object when it is opened, closed,
* activated, deactivated, iconified, or deiconified, or when focus is
* transfered into or out of the Window.
* <P>
* The event is passed to every <code>WindowListener</code>
* or <code>WindowAdapter</code> object which registered to receive such
* events using the window's <code>addWindowListener</code> method.
* (<code>WindowAdapter</code> objects implement the
* <code>WindowListener</code> interface.) Each such listener object
* gets this <code>WindowEvent</code> when the event occurs.
*
* @author Carl Quinn
* @author Amy Fowler
*
* @see WindowAdapter
* @see WindowListener
* @see <a href="http://java.sun.com/docs/books/tutorial/post1.0/ui/windowlistener.html">Tutorial: Writing a Window Listener</a>
*
* @since JDK1.1
*/
public class WindowEvent extends ComponentEvent {
/** {@collect.stats}
* The first number in the range of ids used for window events.
*/
public static final int WINDOW_FIRST = 200;
/** {@collect.stats}
* The window opened event. This event is delivered only
* the first time a window is made visible.
*/
public static final int WINDOW_OPENED = WINDOW_FIRST; // 200
/** {@collect.stats}
* The "window is closing" event. This event is delivered when
* the user attempts to close the window from the window's system menu.
* If the program does not explicitly hide or dispose the window
* while processing this event, the window close operation will be
* cancelled.
*/
public static final int WINDOW_CLOSING = 1 + WINDOW_FIRST; //Event.WINDOW_DESTROY
/** {@collect.stats}
* The window closed event. This event is delivered after
* the window has been closed as the result of a call to dispose.
*/
public static final int WINDOW_CLOSED = 2 + WINDOW_FIRST;
/** {@collect.stats}
* The window iconified event. This event is delivered when
* the window has been changed from a normal to a minimized state.
* For many platforms, a minimized window is displayed as
* the icon specified in the window's iconImage property.
* @see java.awt.Frame#setIconImage
*/
public static final int WINDOW_ICONIFIED = 3 + WINDOW_FIRST; //Event.WINDOW_ICONIFY
/** {@collect.stats}
* The window deiconified event type. This event is delivered when
* the window has been changed from a minimized to a normal state.
*/
public static final int WINDOW_DEICONIFIED = 4 + WINDOW_FIRST; //Event.WINDOW_DEICONIFY
/** {@collect.stats}
* The window-activated event type. This event is delivered when the Window
* becomes the active Window. Only a Frame or a Dialog can be the active
* Window. The native windowing system may denote the active Window or its
* children with special decorations, such as a highlighted title bar. The
* active Window is always either the focused Window, or the first Frame or
* Dialog that is an owner of the focused Window.
*/
public static final int WINDOW_ACTIVATED = 5 + WINDOW_FIRST;
/** {@collect.stats}
* The window-deactivated event type. This event is delivered when the
* Window is no longer the active Window. Only a Frame or a Dialog can be
* the active Window. The native windowing system may denote the active
* Window or its children with special decorations, such as a highlighted
* title bar. The active Window is always either the focused Window, or the
* first Frame or Dialog that is an owner of the focused Window.
*/
public static final int WINDOW_DEACTIVATED = 6 + WINDOW_FIRST;
/** {@collect.stats}
* The window-gained-focus event type. This event is delivered when the
* Window becomes the focused Window, which means that the Window, or one
* of its subcomponents, will receive keyboard events.
*/
public static final int WINDOW_GAINED_FOCUS = 7 + WINDOW_FIRST;
/** {@collect.stats}
* The window-lost-focus event type. This event is delivered when a Window
* is no longer the focused Window, which means keyboard events will no
* longer be delivered to the Window or any of its subcomponents.
*/
public static final int WINDOW_LOST_FOCUS = 8 + WINDOW_FIRST;
/** {@collect.stats}
* The window-state-changed event type. This event is delivered
* when a Window's state is changed by virtue of it being
* iconified, maximized etc.
* @since 1.4
*/
public static final int WINDOW_STATE_CHANGED = 9 + WINDOW_FIRST;
/** {@collect.stats}
* The last number in the range of ids used for window events.
*/
public static final int WINDOW_LAST = WINDOW_STATE_CHANGED;
/** {@collect.stats}
* The other Window involved in this focus or activation change. For a
* WINDOW_ACTIVATED or WINDOW_GAINED_FOCUS event, this is the Window that
* lost activation or focus. For a WINDOW_DEACTIVATED or WINDOW_LOST_FOCUS
* event, this is the Window that gained activation or focus. For any other
* type of WindowEvent, or if the focus or activation change occurs with a
* native application, a Java application in a different VM, or with no
* other Window, null is returned.
*
* @see #getOppositeWindow
* @since 1.4
*/
transient Window opposite;
/** {@collect.stats}
* TBS
*/
int oldState;
int newState;
/*
* JDK 1.1 serialVersionUID
*/
private static final long serialVersionUID = -1567959133147912127L;
/** {@collect.stats}
* Constructs a <code>WindowEvent</code> object.
* <p>Note that passing in an invalid <code>id</code> results in
* unspecified behavior. This method throws an
* <code>IllegalArgumentException</code> if <code>source</code>
* is <code>null</code>.
*
* @param source the <code>Window</code> object
* that originated the event
* @param id an integer indicating the type of event.
* @param opposite the other window involved in the focus or activation
* change, or <code>null</code>
* @param oldState previous state of the window for window state
* change event
* @param newState new state of the window for window state change event
* @throws IllegalArgumentException if <code>source</code> is null
* @since 1.4
*/
public WindowEvent(Window source, int id, Window opposite,
int oldState, int newState)
{
super(source, id);
this.opposite = opposite;
this.oldState = oldState;
this.newState = newState;
}
/** {@collect.stats}
* Constructs a <code>WindowEvent</code> object with the
* specified opposite <code>Window</code>. The opposite
* <code>Window</code> is the other <code>Window</code>
* involved in this focus or activation change.
* For a <code>WINDOW_ACTIVATED</code> or
* <code>WINDOW_GAINED_FOCUS</code> event, this is the
* <code>Window</code> that lost activation or focus.
* For a <code>WINDOW_DEACTIVATED</code> or
* <code>WINDOW_LOST_FOCUS</code> event, this is the
* <code>Window</code> that gained activation or focus.
* If this focus change occurs with a native application, with a
* Java application in a different VM, or with no other
* <code>Window</code>, then the opposite Window is <code>null</code>.
* <p>Note that passing in an invalid <code>id</code> results in
* unspecified behavior. This method throws an
* <code>IllegalArgumentException</code> if <code>source</code>
* is <code>null</code>.
*
* @param source the <code>Window</code> object that
* originated the event
* @param id <code>WINDOW_ACTIVATED</code>,
* <code>WINDOW_DEACTIVATED</code>,
* <code>WINDOW_GAINED_FOCUS</code>,
* or <code>WINDOW_LOST_FOCUS</code>. It is
* expected that this constructor will not be used for
* other <code>WindowEvent</code> types because the
* opposite <code>Window</code> of such events
* will always be <code>null</code>
* @param opposite the other <code>Window</code> involved in the
* focus or activation change, or <code>null</code>
* @throws IllegalArgumentException if <code>source</code> is null
* @since 1.4
*/
public WindowEvent(Window source, int id, Window opposite) {
this(source, id, opposite, 0, 0);
}
/** {@collect.stats}
* Constructs a <code>WindowEvent</code> object with the specified
* previous and new window states.
* <p>Note that passing in an invalid <code>id</code> results in
* unspecified behavior. This method throws an
* <code>IllegalArgumentException</code> if <code>source</code>
* is <code>null</code>.
*
* @param source the <code>Window</code> object
* that originated the event
* @param id <code>WINDOW_STATE_CHANGED</code> event type.
* It is expected that this constructor will not
* be used for other <code>WindowEvent</code>
* types, because the previous and new window
* states are meaningless for other event types.
* @param oldState an integer representing the previous window state
* @param newState an integer representing the new window state
* @throws IllegalArgumentException if <code>source</code> is null
* @since 1.4
*/
public WindowEvent(Window source, int id, int oldState, int newState) {
this(source, id, null, oldState, newState);
}
/** {@collect.stats}
* Constructs a <code>WindowEvent</code> object.
* <p>Note that passing in an invalid <code>id</code> results in
* unspecified behavior. This method throws an
* <code>IllegalArgumentException</code> if <code>source</code>
* is <code>null</code>.
*
* @param source the <code>Window</code> object that originated the event
* @param id an integer indicating the type of event
* @throws IllegalArgumentException if <code>source</code> is null
*/
public WindowEvent(Window source, int id) {
this(source, id, null, 0, 0);
}
/** {@collect.stats}
* Returns the originator of the event.
*
* @return the Window object that originated the event
*/
public Window getWindow() {
return (source instanceof Window) ? (Window)source : null;
}
/** {@collect.stats}
* Returns the other Window involved in this focus or activation change.
* For a WINDOW_ACTIVATED or WINDOW_GAINED_FOCUS event, this is the Window
* that lost activation or focus. For a WINDOW_DEACTIVATED or
* WINDOW_LOST_FOCUS event, this is the Window that gained activation or
* focus. For any other type of WindowEvent, or if the focus or activation
* change occurs with a native application, with a Java application in a
* different VM or context, or with no other Window, null is returned.
*
* @return the other Window involved in the focus or activation change, or
* null
* @since 1.4
*/
public Window getOppositeWindow() {
if (opposite == null) {
return null;
}
return (SunToolkit.targetToAppContext(opposite) ==
AppContext.getAppContext())
? opposite
: null;
}
/** {@collect.stats}
* For <code>WINDOW_STATE_CHANGED</code> events returns the
* previous state of the window. The state is
* represented as a bitwise mask.
* <ul>
* <li><code>NORMAL</code>
* <br>Indicates that no state bits are set.
* <li><code>ICONIFIED</code>
* <li><code>MAXIMIZED_HORIZ</code>
* <li><code>MAXIMIZED_VERT</code>
* <li><code>MAXIMIZED_BOTH</code>
* <br>Concatenates <code>MAXIMIZED_HORIZ</code>
* and <code>MAXIMIZED_VERT</code>.
* </ul>
*
* @return a bitwise mask of the previous window state
* @see java.awt.Frame#getExtendedState()
* @since 1.4
*/
public int getOldState() {
return oldState;
}
/** {@collect.stats}
* For <code>WINDOW_STATE_CHANGED</code> events returns the
* new state of the window. The state is
* represented as a bitwise mask.
* <ul>
* <li><code>NORMAL</code>
* <br>Indicates that no state bits are set.
* <li><code>ICONIFIED</code>
* <li><code>MAXIMIZED_HORIZ</code>
* <li><code>MAXIMIZED_VERT</code>
* <li><code>MAXIMIZED_BOTH</code>
* <br>Concatenates <code>MAXIMIZED_HORIZ</code>
* and <code>MAXIMIZED_VERT</code>.
* </ul>
*
* @return a bitwise mask of the new window state
* @see java.awt.Frame#getExtendedState()
* @since 1.4
*/
public int getNewState() {
return newState;
}
/** {@collect.stats}
* Returns a parameter string identifying this event.
* This method is useful for event-logging and for debugging.
*
* @return a string identifying the event and its attributes
*/
public String paramString() {
String typeStr;
switch(id) {
case WINDOW_OPENED:
typeStr = "WINDOW_OPENED";
break;
case WINDOW_CLOSING:
typeStr = "WINDOW_CLOSING";
break;
case WINDOW_CLOSED:
typeStr = "WINDOW_CLOSED";
break;
case WINDOW_ICONIFIED:
typeStr = "WINDOW_ICONIFIED";
break;
case WINDOW_DEICONIFIED:
typeStr = "WINDOW_DEICONIFIED";
break;
case WINDOW_ACTIVATED:
typeStr = "WINDOW_ACTIVATED";
break;
case WINDOW_DEACTIVATED:
typeStr = "WINDOW_DEACTIVATED";
break;
case WINDOW_GAINED_FOCUS:
typeStr = "WINDOW_GAINED_FOCUS";
break;
case WINDOW_LOST_FOCUS:
typeStr = "WINDOW_LOST_FOCUS";
break;
case WINDOW_STATE_CHANGED:
typeStr = "WINDOW_STATE_CHANGED";
break;
default:
typeStr = "unknown type";
}
typeStr += ",opposite=" + getOppositeWindow()
+ ",oldState=" + oldState + ",newState=" + newState;
return typeStr;
}
}
|
Java
|
/*
* Copyright (c) 1999, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code 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
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package java.awt.event;
import java.util.EventListener;
/** {@collect.stats}
* The listener interface for receiving ancestor moved and resized events.
* The class that is interested in processing these events either implements
* this interface (and all the methods it contains) or extends the abstract
* <code>HierarchyBoundsAdapter</code> class (overriding only the method of
* interest).
* The listener object created from that class is then registered with a
* Component using the Component's <code>addHierarchyBoundsListener</code>
* method. When the hierarchy to which the Component belongs changes by
* the resizing or movement of an ancestor, the relevant method in the listener
* object is invoked, and the <code>HierarchyEvent</code> is passed to it.
* <p>
* Hierarchy events are provided for notification purposes ONLY;
* The AWT will automatically handle changes to the hierarchy internally so
* that GUI layout works properly regardless of whether a
* program registers an <code>HierarchyBoundsListener</code> or not.
*
* @author David Mendenhall
* @see HierarchyBoundsAdapter
* @see HierarchyEvent
* @since 1.3
*/
public interface HierarchyBoundsListener extends EventListener {
/** {@collect.stats}
* Called when an ancestor of the source is moved.
*/
public void ancestorMoved(HierarchyEvent e);
/** {@collect.stats}
* Called when an ancestor of the source is resized.
*/
public void ancestorResized(HierarchyEvent e);
}
|
Java
|
/*
* Copyright (c) 1996, 2006, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code 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
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package java.awt.event;
/** {@collect.stats}
* An abstract adapter class for receiving keyboard focus events.
* The methods in this class are empty. This class exists as
* convenience for creating listener objects.
* <P>
* Extend this class to create a <code>FocusEvent</code> listener
* and override the methods for the events of interest. (If you implement the
* <code>FocusListener</code> interface, you have to define all of
* the methods in it. This abstract class defines null methods for them
* all, so you can only have to define methods for events you care about.)
* <P>
* Create a listener object using the extended class and then register it with
* a component using the component's <code>addFocusListener</code>
* method. When the component gains or loses the keyboard focus,
* the relevant method in the listener object is invoked,
* and the <code>FocusEvent</code> is passed to it.
*
* @see FocusEvent
* @see FocusListener
* @see <a href="http://java.sun.com/docs/books/tutorial/post1.0/ui/focuslistener.html">Tutorial: Writing a Focus Listener</a>
*
* @author Carl Quinn
* @since 1.1
*/
public abstract class FocusAdapter implements FocusListener {
/** {@collect.stats}
* Invoked when a component gains the keyboard focus.
*/
public void focusGained(FocusEvent e) {}
/** {@collect.stats}
* Invoked when a component loses the keyboard focus.
*/
public void focusLost(FocusEvent e) {}
}
|
Java
|
/*
* Copyright (c) 1996, 2006, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code 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
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package java.awt.event;
import java.util.EventListener;
/** {@collect.stats}
* The listener interface for receiving text events.
*
* The class that is interested in processing a text event
* implements this interface. The object created with that
* class is then registered with a component using the
* component's <code>addTextListener</code> method. When the
* component's text changes, the listener object's
* <code>textValueChanged</code> method is invoked.
*
* @author Georges Saab
*
* @see TextEvent
* @see <a href="http://java.sun.com/docs/books/tutorial/post1.0/ui/textlistener.html">Tutorial: Writing a Text Listener</a>
*
* @since 1.1
*/
public interface TextListener extends EventListener {
/** {@collect.stats}
* Invoked when the value of the text has changed.
* The code written for this method performs the operations
* that need to occur when text changes.
*/
public void textValueChanged(TextEvent e);
}
|
Java
|
/*
* Copyright (c) 2000, 2006, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code 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
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package java.awt.event;
import java.awt.Component;
/** {@collect.stats}
* An event which indicates that the mouse wheel was rotated in a component.
* <P>
* A wheel mouse is a mouse which has a wheel in place of the middle button.
* This wheel can be rotated towards or away from the user. Mouse wheels are
* most often used for scrolling, though other uses are possible.
* <P>
* A MouseWheelEvent object is passed to every <code>MouseWheelListener</code>
* object which registered to receive the "interesting" mouse events using the
* component's <code>addMouseWheelListener</code> method. Each such listener
* object gets a <code>MouseEvent</code> containing the mouse event.
* <P>
* Due to the mouse wheel's special relationship to scrolling Components,
* MouseWheelEvents are delivered somewhat differently than other MouseEvents.
* This is because while other MouseEvents usually affect a change on
* the Component directly under the mouse
* cursor (for instance, when clicking a button), MouseWheelEvents often have
* an effect away from the mouse cursor (moving the wheel while
* over a Component inside a ScrollPane should scroll one of the
* Scrollbars on the ScrollPane).
* <P>
* MouseWheelEvents start delivery from the Component underneath the
* mouse cursor. If MouseWheelEvents are not enabled on the
* Component, the event is delivered to the first ancestor
* Container with MouseWheelEvents enabled. This will usually be
* a ScrollPane with wheel scrolling enabled. The source
* Component and x,y coordinates will be relative to the event's
* final destination (the ScrollPane). This allows a complex
* GUI to be installed without modification into a ScrollPane, and
* for all MouseWheelEvents to be delivered to the ScrollPane for
* scrolling.
* <P>
* Some AWT Components are implemented using native widgets which
* display their own scrollbars and handle their own scrolling.
* The particular Components for which this is true will vary from
* platform to platform. When the mouse wheel is
* moved over one of these Components, the event is delivered straight to
* the native widget, and not propagated to ancestors.
* <P>
* Platforms offer customization of the amount of scrolling that
* should take place when the mouse wheel is moved. The two most
* common settings are to scroll a certain number of "units"
* (commonly lines of text in a text-based component) or an entire "block"
* (similar to page-up/page-down). The MouseWheelEvent offers
* methods for conforming to the underlying platform settings. These
* platform settings can be changed at any time by the user. MouseWheelEvents
* reflect the most recent settings.
*
* @author Brent Christian
* @see MouseWheelListener
* @see java.awt.ScrollPane
* @see java.awt.ScrollPane#setWheelScrollingEnabled(boolean)
* @see javax.swing.JScrollPane
* @see javax.swing.JScrollPane#setWheelScrollingEnabled(boolean)
* @since 1.4
*/
public class MouseWheelEvent extends MouseEvent {
/** {@collect.stats}
* Constant representing scrolling by "units" (like scrolling with the
* arrow keys)
*
* @see #getScrollType
*/
public static final int WHEEL_UNIT_SCROLL = 0;
/** {@collect.stats}
* Constant representing scrolling by a "block" (like scrolling
* with page-up, page-down keys)
*
* @see #getScrollType
*/
public static final int WHEEL_BLOCK_SCROLL = 1;
/** {@collect.stats}
* Indicates what sort of scrolling should take place in response to this
* event, based on platform settings. Legal values are:
* <ul>
* <li> WHEEL_UNIT_SCROLL
* <li> WHEEL_BLOCK_SCROLL
* </ul>
*
* @see #getScrollType
*/
int scrollType;
/** {@collect.stats}
* Only valid for scrollType WHEEL_UNIT_SCROLL.
* Indicates number of units that should be scrolled per
* click of mouse wheel rotation, based on platform settings.
*
* @see #getScrollAmount
* @see #getScrollType
*/
int scrollAmount;
/** {@collect.stats}
* Indicates how far the mouse wheel was rotated.
*
* @see #getWheelRotation
*/
int wheelRotation;
/*
* serialVersionUID
*/
private static final long serialVersionUID = 6459879390515399677L;
/** {@collect.stats}
* Constructs a <code>MouseWheelEvent</code> object with the
* specified source component, type, modifiers, coordinates,
* scroll type, scroll amount, and wheel rotation.
* <p>Absolute coordinates xAbs and yAbs are set to source's location on screen plus
* relative coordinates x and y. xAbs and yAbs are set to zero if the source is not showing.
* <p>Note that passing in an invalid <code>id</code> results in
* unspecified behavior. This method throws an
* <code>IllegalArgumentException</code> if <code>source</code>
* is <code>null</code>.
*
* @param source the <code>Component</code> that originated
* the event
* @param id the integer that identifies the event
* @param when a long that gives the time the event occurred
* @param modifiers the modifier keys down during event
* (shift, ctrl, alt, meta)
* @param x the horizontal x coordinate for the mouse location
* @param y the vertical y coordinate for the mouse location
* @param clickCount the number of mouse clicks associated with event
* @param popupTrigger a boolean, true if this event is a trigger for a
* popup-menu
* @param scrollType the type of scrolling which should take place in
* response to this event; valid values are
* <code>WHEEL_UNIT_SCROLL</code> and
* <code>WHEEL_BLOCK_SCROLL</code>
* @param scrollAmount for scrollType <code>WHEEL_UNIT_SCROLL</code>,
* the number of units to be scrolled
* @param wheelRotation the amount that the mouse wheel was rotated (the
* number of "clicks")
*
* @throws IllegalArgumentException if <code>source</code> is null
* @see MouseEvent#MouseEvent(java.awt.Component, int, long, int, int, int, int, boolean)
* @see MouseEvent#MouseEvent(java.awt.Component, int, long, int, int, int, int, int, int, boolean, int)
*/
public MouseWheelEvent (Component source, int id, long when, int modifiers,
int x, int y, int clickCount, boolean popupTrigger,
int scrollType, int scrollAmount, int wheelRotation) {
this(source, id, when, modifiers, x, y, 0, 0, clickCount,
popupTrigger, scrollType, scrollAmount, wheelRotation);
}
/** {@collect.stats}
* Constructs a <code>MouseWheelEvent</code> object with the
* specified source component, type, modifiers, coordinates,
* absolute coordinates, scroll type, scroll amount, and wheel rotation.
* <p>Note that passing in an invalid <code>id</code> results in
* unspecified behavior. This method throws an
* <code>IllegalArgumentException</code> if <code>source</code>
* is <code>null</code>.<p>
* Even if inconsistent values for relative and absolute coordinates are
* passed to the constructor, the MouseWheelEvent instance is still
* created and no exception is thrown.
*
* @param source the <code>Component</code> that originated
* the event
* @param id the integer that identifies the event
* @param when a long that gives the time the event occurred
* @param modifiers the modifier keys down during event
* (shift, ctrl, alt, meta)
* @param x the horizontal x coordinate for the mouse location
* @param y the vertical y coordinate for the mouse location
* @param xAbs the absolute horizontal x coordinate for the mouse location
* @param yAbs the absolute vertical y coordinate for the mouse location
* @param clickCount the number of mouse clicks associated with event
* @param popupTrigger a boolean, true if this event is a trigger for a
* popup-menu
* @param scrollType the type of scrolling which should take place in
* response to this event; valid values are
* <code>WHEEL_UNIT_SCROLL</code> and
* <code>WHEEL_BLOCK_SCROLL</code>
* @param scrollAmount for scrollType <code>WHEEL_UNIT_SCROLL</code>,
* the number of units to be scrolled
* @param wheelRotation the amount that the mouse wheel was rotated (the
* number of "clicks")
*
* @throws IllegalArgumentException if <code>source</code> is null
* @see MouseEvent#MouseEvent(java.awt.Component, int, long, int, int, int, int, boolean)
* @see MouseEvent#MouseEvent(java.awt.Component, int, long, int, int, int, int, int, int, boolean, int)
* @since 1.6
*/
public MouseWheelEvent (Component source, int id, long when, int modifiers,
int x, int y, int xAbs, int yAbs, int clickCount, boolean popupTrigger,
int scrollType, int scrollAmount, int wheelRotation) {
super(source, id, when, modifiers, x, y, xAbs, yAbs, clickCount,
popupTrigger, MouseEvent.NOBUTTON);
this.scrollType = scrollType;
this.scrollAmount = scrollAmount;
this.wheelRotation = wheelRotation;
}
/** {@collect.stats}
* Returns the type of scrolling that should take place in response to this
* event. This is determined by the native platform. Legal values are:
* <ul>
* <li> MouseWheelEvent.WHEEL_UNIT_SCROLL
* <li> MouseWheelEvent.WHEEL_BLOCK_SCROLL
* </ul>
*
* @return either MouseWheelEvent.WHEEL_UNIT_SCROLL or
* MouseWheelEvent.WHEEL_BLOCK_SCROLL, depending on the configuration of
* the native platform.
* @see java.awt.Adjustable#getUnitIncrement
* @see java.awt.Adjustable#getBlockIncrement
* @see javax.swing.Scrollable#getScrollableUnitIncrement
* @see javax.swing.Scrollable#getScrollableBlockIncrement
*/
public int getScrollType() {
return scrollType;
}
/** {@collect.stats}
* Returns the number of units that should be scrolled per
* click of mouse wheel rotation.
* Only valid if <code>getScrollType</code> returns
* <code>MouseWheelEvent.WHEEL_UNIT_SCROLL</code>
*
* @return number of units to scroll, or an undefined value if
* <code>getScrollType</code> returns
* <code>MouseWheelEvent.WHEEL_BLOCK_SCROLL</code>
* @see #getScrollType
*/
public int getScrollAmount() {
return scrollAmount;
}
/** {@collect.stats}
* Returns the number of "clicks" the mouse wheel was rotated.
*
* @return negative values if the mouse wheel was rotated up/away from
* the user, and positive values if the mouse wheel was rotated down/
* towards the user
*/
public int getWheelRotation() {
return wheelRotation;
}
/** {@collect.stats}
* This is a convenience method to aid in the implementation of
* the common-case MouseWheelListener - to scroll a ScrollPane or
* JScrollPane by an amount which conforms to the platform settings.
* (Note, however, that <code>ScrollPane</code> and
* <code>JScrollPane</code> already have this functionality built in.)
* <P>
* This method returns the number of units to scroll when scroll type is
* MouseWheelEvent.WHEEL_UNIT_SCROLL, and should only be called if
* <code>getScrollType</code> returns MouseWheelEvent.WHEEL_UNIT_SCROLL.
* <P>
* Direction of scroll, amount of wheel movement,
* and platform settings for wheel scrolling are all accounted for.
* This method does not and cannot take into account value of the
* Adjustable/Scrollable unit increment, as this will vary among
* scrolling components.
* <P>
* A simplified example of how this method might be used in a
* listener:
* <pre>
* mouseWheelMoved(MouseWheelEvent event) {
* ScrollPane sp = getScrollPaneFromSomewhere();
* Adjustable adj = sp.getVAdjustable()
* if (MouseWheelEvent.getScrollType() == WHEEL_UNIT_SCROLL) {
* int totalScrollAmount =
* event.getUnitsToScroll() *
* adj.getUnitIncrement();
* adj.setValue(adj.getValue() + totalScrollAmount);
* }
* }
* </pre>
*
* @return the number of units to scroll based on the direction and amount
* of mouse wheel rotation, and on the wheel scrolling settings of the
* native platform
* @see #getScrollType
* @see #getScrollAmount
* @see MouseWheelListener
* @see java.awt.Adjustable
* @see java.awt.Adjustable#getUnitIncrement
* @see javax.swing.Scrollable
* @see javax.swing.Scrollable#getScrollableUnitIncrement
* @see java.awt.ScrollPane
* @see java.awt.ScrollPane#setWheelScrollingEnabled
* @see javax.swing.JScrollPane
* @see javax.swing.JScrollPane#setWheelScrollingEnabled
*/
public int getUnitsToScroll() {
return scrollAmount * wheelRotation;
}
/** {@collect.stats}
* Returns a parameter string identifying this event.
* This method is useful for event-logging and for debugging.
*
* @return a string identifying the event and its attributes
*/
public String paramString() {
String scrollTypeStr = null;
if (getScrollType() == WHEEL_UNIT_SCROLL) {
scrollTypeStr = "WHEEL_UNIT_SCROLL";
}
else if (getScrollType() == WHEEL_BLOCK_SCROLL) {
scrollTypeStr = "WHEEL_BLOCK_SCROLL";
}
else {
scrollTypeStr = "unknown scroll type";
}
return super.paramString()+",scrollType="+scrollTypeStr+
",scrollAmount="+getScrollAmount()+",wheelRotation="+
getWheelRotation();
}
}
|
Java
|
/*
* Copyright (c) 1999, 2004, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code 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
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package java.awt.event;
import java.awt.AWTEvent;
import java.awt.Component;
import java.awt.Container;
/** {@collect.stats}
* An event which indicates a change to the <code>Component</code>
* hierarchy to which a <code>Component</code> belongs.
* <ul>
* <li>Hierarchy Change Events (HierarchyListener)
* <ul>
* <li> addition of an ancestor
* <li> removal of an ancestor
* <li> hierarchy made displayable
* <li> hierarchy made undisplayable
* <li> hierarchy shown on the screen (both visible and displayable)
* <li> hierarchy hidden on the screen (either invisible or undisplayable)
* </ul>
* <li>Ancestor Reshape Events (HierarchyBoundsListener)
* <ul>
* <li> an ancestor was resized
* <li> an ancestor was moved
* </ul>
* </ul>
* <p>
* Hierarchy events are provided for notification purposes ONLY.
* The AWT will automatically handle changes to the hierarchy internally so
* that GUI layout and displayability works properly regardless of whether a
* program is receiving these events or not.
* <p>
* This event is generated by a Container object (such as a Panel) when the
* Container is added, removed, moved, or resized, and passed down the
* hierarchy. It is also generated by a Component object when that object's
* <code>addNotify</code>, <code>removeNotify</code>, <code>show</code>, or
* <code>hide</code> method is called. ANCESTOR_MOVED and ANCESTOR_RESIZED
* events are dispatched to every <code>HierarchyBoundsListener</code> or
* <code>HierarchyBoundsAdapter</code> object which registered to receive
* such events using the Component's <code>addHierarchyBoundsListener</code>
* method. (<code>HierarchyBoundsAdapter</code> objects implement the <code>
* HierarchyBoundsListener</code> interface.) HIERARCHY_CHANGED events are
* dispatched to every <code>HierarchyListener</code> object which registered
* to receive such events using the Component's <code>addHierarchyListener
* </code> method. Each such listener object gets this <code>HierarchyEvent
* </code> when the event occurs.
*
* @author David Mendenhall
* @see HierarchyListener
* @see HierarchyBoundsAdapter
* @see HierarchyBoundsListener
* @since 1.3
*/
public class HierarchyEvent extends AWTEvent {
/*
* serialVersionUID
*/
private static final long serialVersionUID = -5337576970038043990L;
/** {@collect.stats}
* Marks the first integer id for the range of hierarchy event ids.
*/
public static final int HIERARCHY_FIRST = 1400; // 1300 used by sun.awt.windows.ModalityEvent
/** {@collect.stats}
* The event id indicating that modification was made to the
* entire hierarchy tree.
*/
public static final int HIERARCHY_CHANGED = HIERARCHY_FIRST;
/** {@collect.stats}
* The event id indicating an ancestor-Container was moved.
*/
public static final int ANCESTOR_MOVED = 1 + HIERARCHY_FIRST;
/** {@collect.stats}
* The event id indicating an ancestor-Container was resized.
*/
public static final int ANCESTOR_RESIZED = 2 + HIERARCHY_FIRST;
/** {@collect.stats}
* Marks the last integer id for the range of ancestor event ids.
*/
public static final int HIERARCHY_LAST = ANCESTOR_RESIZED;
/** {@collect.stats}
* Indicates that the <code>HIERARCHY_CHANGED</code> event
* was generated by a reparenting operation.
*/
public static final int PARENT_CHANGED = 0x1;
/** {@collect.stats}
* Indicates that the <code>HIERARCHY_CHANGED</code> event
* was generated due to a change in the displayability
* of the hierarchy. To discern the
* current displayability of the hierarchy, call
* <code>Component.isDisplayable</code>. Displayability changes occur
* in response to explicit or implicit calls to
* <code>Component.addNotify</code> and
* <code>Component.removeNotify</code>.
*
* @see java.awt.Component#isDisplayable()
* @see java.awt.Component#addNotify()
* @see java.awt.Component#removeNotify()
*/
public static final int DISPLAYABILITY_CHANGED = 0x2;
/** {@collect.stats}
* Indicates that the <code>HIERARCHY_CHANGED</code> event
* was generated due to a change in the showing state
* of the hierarchy. To discern the
* current showing state of the hierarchy, call
* <code>Component.isShowing</code>. Showing state changes occur
* when either the displayability or visibility of the
* hierarchy occurs. Visibility changes occur in response to explicit
* or implicit calls to <code>Component.show</code> and
* <code>Component.hide</code>.
*
* @see java.awt.Component#isShowing()
* @see java.awt.Component#addNotify()
* @see java.awt.Component#removeNotify()
* @see java.awt.Component#show()
* @see java.awt.Component#hide()
*/
public static final int SHOWING_CHANGED = 0x4;
Component changed;
Container changedParent;
long changeFlags;
/** {@collect.stats}
* Constructs an <code>HierarchyEvent</code> object to identify a
* change in the <code>Component</code> hierarchy.
* <p>Note that passing in an invalid <code>id</code> results in
* unspecified behavior. This method throws an
* <code>IllegalArgumentException</code> if <code>source</code>
* is <code>null</code>.
*
* @param source the <code>Component</code> object that
* originated the event
* @param id an integer indicating the type of event
* @param changed the <code>Component</code> at the top of
* the hierarchy which was changed
* @param changedParent the parent of <code>changed</code>; this
* may be the parent before or after the
* change, depending on the type of change
* @throws IllegalArgumentException if <code>source</code> is null
*/
public HierarchyEvent(Component source, int id, Component changed,
Container changedParent) {
super(source, id);
this.changed = changed;
this.changedParent = changedParent;
}
/** {@collect.stats}
* Constructs an <code>HierarchyEvent</code> object to identify
* a change in the <code>Component</code> hierarchy.
* <p>Note that passing in an invalid <code>id</code> results in
* unspecified behavior. This method throws an
* <code>IllegalArgumentException</code> if <code>source</code>
* is <code>null</code>.
*
* @param source the <code>Component</code> object that
* originated the event
* @param id an integer indicating the type of event
* @param changed the <code>Component</code> at the top
* of the hierarchy which was changed
* @param changedParent the parent of <code>changed</code>; this
* may be the parent before or after the
* change, depending on the type of change
* @param changeFlags a bitmask which indicates the type(s) of
* <code>HIERARCHY_CHANGED</code> events
* represented in this event object
* @throws IllegalArgumentException if <code>source</code> is null
*/
public HierarchyEvent(Component source, int id, Component changed,
Container changedParent, long changeFlags) {
super(source, id);
this.changed = changed;
this.changedParent = changedParent;
this.changeFlags = changeFlags;
}
/** {@collect.stats}
* Returns the originator of the event.
*
* @return the <code>Component</code> object that originated
* the event, or <code>null</code> if the object is not a
* <code>Component</code>.
*/
public Component getComponent() {
return (source instanceof Component) ? (Component)source : null;
}
/** {@collect.stats}
* Returns the Component at the top of the hierarchy which was
* changed.
*
* @return the changed Component
*/
public Component getChanged() {
return changed;
}
/** {@collect.stats}
* Returns the parent of the Component returned by <code>
* getChanged()</code>. For a HIERARCHY_CHANGED event where the
* change was of type PARENT_CHANGED via a call to <code>
* Container.add</code>, the parent returned is the parent
* after the add operation. For a HIERARCHY_CHANGED event where
* the change was of type PARENT_CHANGED via a call to <code>
* Container.remove</code>, the parent returned is the parent
* before the remove operation. For all other events and types,
* the parent returned is the parent during the operation.
*
* @return the parent of the changed Component
*/
public Container getChangedParent() {
return changedParent;
}
/** {@collect.stats}
* Returns a bitmask which indicates the type(s) of
* HIERARCHY_CHANGED events represented in this event object.
* The bits have been bitwise-ored together.
*
* @return the bitmask, or 0 if this is not an HIERARCHY_CHANGED
* event
*/
public long getChangeFlags() {
return changeFlags;
}
/** {@collect.stats}
* Returns a parameter string identifying this event.
* This method is useful for event-logging and for debugging.
*
* @return a string identifying the event and its attributes
*/
public String paramString() {
String typeStr;
switch(id) {
case ANCESTOR_MOVED:
typeStr = "ANCESTOR_MOVED ("+changed+","+changedParent+")";
break;
case ANCESTOR_RESIZED:
typeStr = "ANCESTOR_RESIZED ("+changed+","+changedParent+")";
break;
case HIERARCHY_CHANGED: {
typeStr = "HIERARCHY_CHANGED (";
boolean first = true;
if ((changeFlags & PARENT_CHANGED) != 0) {
first = false;
typeStr += "PARENT_CHANGED";
}
if ((changeFlags & DISPLAYABILITY_CHANGED) != 0) {
if (first) {
first = false;
} else {
typeStr += ",";
}
typeStr += "DISPLAYABILITY_CHANGED";
}
if ((changeFlags & SHOWING_CHANGED) != 0) {
if (first) {
first = false;
} else {
typeStr += ",";
}
typeStr += "SHOWING_CHANGED";
}
if (!first) {
typeStr += ",";
}
typeStr += changed + "," + changedParent + ")";
break;
}
default:
typeStr = "unknown type";
}
return typeStr;
}
}
|
Java
|
/*
* Copyright (c) 1996, 2006, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code 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
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package java.awt.event;
/** {@collect.stats}
* An abstract adapter class for receiving keyboard events.
* The methods in this class are empty. This class exists as
* convenience for creating listener objects.
* <P>
* Extend this class to create a <code>KeyEvent</code> listener
* and override the methods for the events of interest. (If you implement the
* <code>KeyListener</code> interface, you have to define all of
* the methods in it. This abstract class defines null methods for them
* all, so you can only have to define methods for events you care about.)
* <P>
* Create a listener object using the extended class and then register it with
* a component using the component's <code>addKeyListener</code>
* method. When a key is pressed, released, or typed,
* the relevant method in the listener object is invoked,
* and the <code>KeyEvent</code> is passed to it.
*
* @author Carl Quinn
*
* @see KeyEvent
* @see KeyListener
* @see <a href="http://java.sun.com/docs/books/tutorial/post1.0/ui/keylistener.html">Tutorial: Writing a Key Listener</a>
*
* @since 1.1
*/
public abstract class KeyAdapter implements KeyListener {
/** {@collect.stats}
* Invoked when a key has been typed.
* This event occurs when a key press is followed by a key release.
*/
public void keyTyped(KeyEvent e) {}
/** {@collect.stats}
* Invoked when a key has been pressed.
*/
public void keyPressed(KeyEvent e) {}
/** {@collect.stats}
* Invoked when a key has been released.
*/
public void keyReleased(KeyEvent e) {}
}
|
Java
|
/*
* Copyright (c) 1995, 2006, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code 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
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package java.awt;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.util.Vector;
import java.util.Enumeration;
import java.awt.peer.MenuPeer;
import java.awt.event.KeyEvent;
import javax.accessibility.*;
/** {@collect.stats}
* A <code>Menu</code> object is a pull-down menu component
* that is deployed from a menu bar.
* <p>
* A menu can optionally be a <i>tear-off</i> menu. A tear-off menu
* can be opened and dragged away from its parent menu bar or menu.
* It remains on the screen after the mouse button has been released.
* The mechanism for tearing off a menu is platform dependent, since
* the look and feel of the tear-off menu is determined by its peer.
* On platforms that do not support tear-off menus, the tear-off
* property is ignored.
* <p>
* Each item in a menu must belong to the <code>MenuItem</code>
* class. It can be an instance of <code>MenuItem</code>, a submenu
* (an instance of <code>Menu</code>), or a check box (an instance of
* <code>CheckboxMenuItem</code>).
*
* @author Sami Shaio
* @see java.awt.MenuItem
* @see java.awt.CheckboxMenuItem
* @since JDK1.0
*/
public class Menu extends MenuItem implements MenuContainer, Accessible {
static {
/* ensure that the necessary native libraries are loaded */
Toolkit.loadLibraries();
if (!GraphicsEnvironment.isHeadless()) {
initIDs();
}
}
/** {@collect.stats}
* A vector of the items that will be part of the Menu.
*
* @serial
* @see #countItems()
*/
Vector items = new Vector();
/** {@collect.stats}
* This field indicates whether the menu has the
* tear of property or not. It will be set to
* <code>true</code> if the menu has the tear off
* property and it will be set to <code>false</code>
* if it does not.
* A torn off menu can be deleted by a user when
* it is no longer needed.
*
* @serial
* @see #isTearOff()
*/
boolean tearOff;
/** {@collect.stats}
* This field will be set to <code>true</code>
* if the Menu in question is actually a help
* menu. Otherwise it will be set to <code>
* false</code>.
*
* @serial
*/
boolean isHelpMenu;
private static final String base = "menu";
private static int nameCounter = 0;
/*
* JDK 1.1 serialVersionUID
*/
private static final long serialVersionUID = -8809584163345499784L;
/** {@collect.stats}
* Constructs a new menu with an empty label. This menu is not
* a tear-off menu.
* @exception HeadlessException if GraphicsEnvironment.isHeadless()
* returns true.
* @see java.awt.GraphicsEnvironment#isHeadless
* @since JDK1.1
*/
public Menu() throws HeadlessException {
this("", false);
}
/** {@collect.stats}
* Constructs a new menu with the specified label. This menu is not
* a tear-off menu.
* @param label the menu's label in the menu bar, or in
* another menu of which this menu is a submenu.
* @exception HeadlessException if GraphicsEnvironment.isHeadless()
* returns true.
* @see java.awt.GraphicsEnvironment#isHeadless
*/
public Menu(String label) throws HeadlessException {
this(label, false);
}
/** {@collect.stats}
* Constructs a new menu with the specified label,
* indicating whether the menu can be torn off.
* <p>
* Tear-off functionality may not be supported by all
* implementations of AWT. If a particular implementation doesn't
* support tear-off menus, this value is silently ignored.
* @param label the menu's label in the menu bar, or in
* another menu of which this menu is a submenu.
* @param tearOff if <code>true</code>, the menu
* is a tear-off menu.
* @exception HeadlessException if GraphicsEnvironment.isHeadless()
* returns true.
* @see java.awt.GraphicsEnvironment#isHeadless
* @since JDK1.0.
*/
public Menu(String label, boolean tearOff) throws HeadlessException {
super(label);
this.tearOff = tearOff;
}
/** {@collect.stats}
* Construct a name for this MenuComponent. Called by getName() when
* the name is null.
*/
String constructComponentName() {
synchronized (Menu.class) {
return base + nameCounter++;
}
}
/** {@collect.stats}
* Creates the menu's peer. The peer allows us to modify the
* appearance of the menu without changing its functionality.
*/
public void addNotify() {
synchronized (getTreeLock()) {
if (peer == null)
peer = Toolkit.getDefaultToolkit().createMenu(this);
int nitems = getItemCount();
for (int i = 0 ; i < nitems ; i++) {
MenuItem mi = getItem(i);
mi.parent = this;
mi.addNotify();
}
}
}
/** {@collect.stats}
* Removes the menu's peer. The peer allows us to modify the appearance
* of the menu without changing its functionality.
*/
public void removeNotify() {
synchronized (getTreeLock()) {
int nitems = getItemCount();
for (int i = 0 ; i < nitems ; i++) {
getItem(i).removeNotify();
}
super.removeNotify();
}
}
/** {@collect.stats}
* Indicates whether this menu is a tear-off menu.
* <p>
* Tear-off functionality may not be supported by all
* implementations of AWT. If a particular implementation doesn't
* support tear-off menus, this value is silently ignored.
* @return <code>true</code> if this is a tear-off menu;
* <code>false</code> otherwise.
*/
public boolean isTearOff() {
return tearOff;
}
/** {@collect.stats}
* Get the number of items in this menu.
* @return the number of items in this menu.
* @since JDK1.1
*/
public int getItemCount() {
return countItems();
}
/** {@collect.stats}
* @deprecated As of JDK version 1.1,
* replaced by <code>getItemCount()</code>.
*/
@Deprecated
public int countItems() {
return countItemsImpl();
}
/*
* This is called by the native code, so client code can't
* be called on the toolkit thread.
*/
final int countItemsImpl() {
return items.size();
}
/** {@collect.stats}
* Gets the item located at the specified index of this menu.
* @param index the position of the item to be returned.
* @return the item located at the specified index.
*/
public MenuItem getItem(int index) {
return getItemImpl(index);
}
/*
* This is called by the native code, so client code can't
* be called on the toolkit thread.
*/
final MenuItem getItemImpl(int index) {
return (MenuItem)items.elementAt(index);
}
/** {@collect.stats}
* Adds the specified menu item to this menu. If the
* menu item has been part of another menu, removes it
* from that menu.
*
* @param mi the menu item to be added
* @return the menu item added
* @see java.awt.Menu#insert(java.lang.String, int)
* @see java.awt.Menu#insert(java.awt.MenuItem, int)
*/
public MenuItem add(MenuItem mi) {
synchronized (getTreeLock()) {
if (mi.parent != null) {
mi.parent.remove(mi);
}
items.addElement(mi);
mi.parent = this;
MenuPeer peer = (MenuPeer)this.peer;
if (peer != null) {
mi.addNotify();
peer.addItem(mi);
}
return mi;
}
}
/** {@collect.stats}
* Adds an item with the specified label to this menu.
*
* @param label the text on the item
* @see java.awt.Menu#insert(java.lang.String, int)
* @see java.awt.Menu#insert(java.awt.MenuItem, int)
*/
public void add(String label) {
add(new MenuItem(label));
}
/** {@collect.stats}
* Inserts a menu item into this menu
* at the specified position.
*
* @param menuitem the menu item to be inserted.
* @param index the position at which the menu
* item should be inserted.
* @see java.awt.Menu#add(java.lang.String)
* @see java.awt.Menu#add(java.awt.MenuItem)
* @exception IllegalArgumentException if the value of
* <code>index</code> is less than zero
* @since JDK1.1
*/
public void insert(MenuItem menuitem, int index) {
synchronized (getTreeLock()) {
if (index < 0) {
throw new IllegalArgumentException("index less than zero.");
}
int nitems = getItemCount();
Vector tempItems = new Vector();
/* Remove the item at index, nitems-index times
storing them in a temporary vector in the
order they appear on the menu.
*/
for (int i = index ; i < nitems; i++) {
tempItems.addElement(getItem(index));
remove(index);
}
add(menuitem);
/* Add the removed items back to the menu, they are
already in the correct order in the temp vector.
*/
for (int i = 0; i < tempItems.size() ; i++) {
add((MenuItem)tempItems.elementAt(i));
}
}
}
/** {@collect.stats}
* Inserts a menu item with the specified label into this menu
* at the specified position. This is a convenience method for
* <code>insert(menuItem, index)</code>.
*
* @param label the text on the item
* @param index the position at which the menu item
* should be inserted
* @see java.awt.Menu#add(java.lang.String)
* @see java.awt.Menu#add(java.awt.MenuItem)
* @exception IllegalArgumentException if the value of
* <code>index</code> is less than zero
* @since JDK1.1
*/
public void insert(String label, int index) {
insert(new MenuItem(label), index);
}
/** {@collect.stats}
* Adds a separator line, or a hypen, to the menu at the current position.
* @see java.awt.Menu#insertSeparator(int)
*/
public void addSeparator() {
add("-");
}
/** {@collect.stats}
* Inserts a separator at the specified position.
* @param index the position at which the
* menu separator should be inserted.
* @exception IllegalArgumentException if the value of
* <code>index</code> is less than 0.
* @see java.awt.Menu#addSeparator
* @since JDK1.1
*/
public void insertSeparator(int index) {
synchronized (getTreeLock()) {
if (index < 0) {
throw new IllegalArgumentException("index less than zero.");
}
int nitems = getItemCount();
Vector tempItems = new Vector();
/* Remove the item at index, nitems-index times
storing them in a temporary vector in the
order they appear on the menu.
*/
for (int i = index ; i < nitems; i++) {
tempItems.addElement(getItem(index));
remove(index);
}
addSeparator();
/* Add the removed items back to the menu, they are
already in the correct order in the temp vector.
*/
for (int i = 0; i < tempItems.size() ; i++) {
add((MenuItem)tempItems.elementAt(i));
}
}
}
/** {@collect.stats}
* Removes the menu item at the specified index from this menu.
* @param index the position of the item to be removed.
*/
public void remove(int index) {
synchronized (getTreeLock()) {
MenuItem mi = getItem(index);
items.removeElementAt(index);
MenuPeer peer = (MenuPeer)this.peer;
if (peer != null) {
mi.removeNotify();
mi.parent = null;
peer.delItem(index);
}
}
}
/** {@collect.stats}
* Removes the specified menu item from this menu.
* @param item the item to be removed from the menu.
* If <code>item</code> is <code>null</code>
* or is not in this menu, this method does
* nothing.
*/
public void remove(MenuComponent item) {
synchronized (getTreeLock()) {
int index = items.indexOf(item);
if (index >= 0) {
remove(index);
}
}
}
/** {@collect.stats}
* Removes all items from this menu.
* @since JDK1.0.
*/
public void removeAll() {
synchronized (getTreeLock()) {
int nitems = getItemCount();
for (int i = nitems-1 ; i >= 0 ; i--) {
remove(i);
}
}
}
/*
* Post an ActionEvent to the target of the MenuPeer
* associated with the specified keyboard event (on
* keydown). Returns true if there is an associated
* keyboard event.
*/
boolean handleShortcut(KeyEvent e) {
int nitems = getItemCount();
for (int i = 0 ; i < nitems ; i++) {
MenuItem mi = getItem(i);
if (mi.handleShortcut(e)) {
return true;
}
}
return false;
}
MenuItem getShortcutMenuItem(MenuShortcut s) {
int nitems = getItemCount();
for (int i = 0 ; i < nitems ; i++) {
MenuItem mi = getItem(i).getShortcutMenuItem(s);
if (mi != null) {
return mi;
}
}
return null;
}
synchronized Enumeration shortcuts() {
Vector shortcuts = new Vector();
int nitems = getItemCount();
for (int i = 0 ; i < nitems ; i++) {
MenuItem mi = getItem(i);
if (mi instanceof Menu) {
Enumeration e = ((Menu)mi).shortcuts();
while (e.hasMoreElements()) {
shortcuts.addElement(e.nextElement());
}
} else {
MenuShortcut ms = mi.getShortcut();
if (ms != null) {
shortcuts.addElement(ms);
}
}
}
return shortcuts.elements();
}
void deleteShortcut(MenuShortcut s) {
int nitems = getItemCount();
for (int i = 0 ; i < nitems ; i++) {
getItem(i).deleteShortcut(s);
}
}
/* Serialization support. A MenuContainer is responsible for
* restoring the parent fields of its children.
*/
/** {@collect.stats}
* The menu serialized Data Version.
*
* @serial
*/
private int menuSerializedDataVersion = 1;
/** {@collect.stats}
* Writes default serializable fields to stream.
*
* @param s the <code>ObjectOutputStream</code> to write
* @see AWTEventMulticaster#save(ObjectOutputStream, String, EventListener)
* @see #readObject(ObjectInputStream)
*/
private void writeObject(java.io.ObjectOutputStream s)
throws java.io.IOException
{
s.defaultWriteObject();
}
/** {@collect.stats}
* Reads the <code>ObjectInputStream</code>.
* Unrecognized keys or values will be ignored.
*
* @param s the <code>ObjectInputStream</code> to read
* @exception HeadlessException if
* <code>GraphicsEnvironment.isHeadless</code> returns
* <code>true</code>
* @see java.awt.GraphicsEnvironment#isHeadless
* @see #writeObject(ObjectOutputStream)
*/
private void readObject(ObjectInputStream s)
throws IOException, ClassNotFoundException, HeadlessException
{
// HeadlessException will be thrown from MenuComponent's readObject
s.defaultReadObject();
for(int i = 0; i < items.size(); i++) {
MenuItem item = (MenuItem)items.elementAt(i);
item.parent = this;
}
}
/** {@collect.stats}
* Returns a string representing the state of this <code>Menu</code>.
* This method is intended to be used only for debugging purposes, and the
* content and format of the returned string may vary between
* implementations. The returned string may be empty but may not be
* <code>null</code>.
*
* @return the parameter string of this menu
*/
public String paramString() {
String str = ",tearOff=" + tearOff+",isHelpMenu=" + isHelpMenu;
return super.paramString() + str;
}
/** {@collect.stats}
* Initialize JNI field and method IDs
*/
private static native void initIDs();
/////////////////
// Accessibility support
////////////////
/** {@collect.stats}
* Gets the AccessibleContext associated with this Menu.
* For menus, the AccessibleContext takes the form of an
* AccessibleAWTMenu.
* A new AccessibleAWTMenu instance is created if necessary.
*
* @return an AccessibleAWTMenu that serves as the
* AccessibleContext of this Menu
* @since 1.3
*/
public AccessibleContext getAccessibleContext() {
if (accessibleContext == null) {
accessibleContext = new AccessibleAWTMenu();
}
return accessibleContext;
}
/** {@collect.stats}
* Defined in MenuComponent. Overridden here.
*/
int getAccessibleChildIndex(MenuComponent child) {
return items.indexOf(child);
}
/** {@collect.stats}
* Inner class of Menu used to provide default support for
* accessibility. This class is not meant to be used directly by
* application developers, but is instead meant only to be
* subclassed by menu component developers.
* <p>
* This class implements accessibility support for the
* <code>Menu</code> class. It provides an implementation of the
* Java Accessibility API appropriate to menu user-interface elements.
* @since 1.3
*/
protected class AccessibleAWTMenu extends AccessibleAWTMenuItem
{
/*
* JDK 1.3 serialVersionUID
*/
private static final long serialVersionUID = 5228160894980069094L;
/** {@collect.stats}
* Get the role of this object.
*
* @return an instance of AccessibleRole describing the role of the
* object
*/
public AccessibleRole getAccessibleRole() {
return AccessibleRole.MENU;
}
} // class AccessibleAWTMenu
}
|
Java
|
/*
* Copyright (c) 1998, 2006, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code 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
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
/*
* (C) Copyright IBM Corp. 1998 - All Rights Reserved
*
* The original version of this source code and documentation is copyrighted
* and owned by IBM, Inc. These materials are provided under terms of a
* License Agreement between IBM and Sun. This technology is protected by
* multiple US and International patents. This notice and attribution to IBM
* may not be removed.
*
*/
package java.awt;
import java.util.Locale;
import java.util.ResourceBundle;
/** {@collect.stats}
* The ComponentOrientation class encapsulates the language-sensitive
* orientation that is to be used to order the elements of a component
* or of text. It is used to reflect the differences in this ordering
* between Western alphabets, Middle Eastern (such as Hebrew), and Far
* Eastern (such as Japanese).
* <p>
* Fundamentally, this governs items (such as characters) which are laid out
* in lines, with the lines then laid out in a block. This also applies
* to items in a widget: for example, in a check box where the box is
* positioned relative to the text.
* <p>
* There are four different orientations used in modern languages
* as in the following table.<br>
* <pre>
* LT RT TL TR
* A B C C B A A D G G D A
* D E F F E D B E H H E B
* G H I I H G C F I I F C
* </pre><br>
* (In the header, the two-letter abbreviation represents the item direction
* in the first letter, and the line direction in the second. For example,
* LT means "items left-to-right, lines top-to-bottom",
* TL means "items top-to-bottom, lines left-to-right", and so on.)
* <p>
* The orientations are:
* <ul>
* <li>LT - Western Europe (optional for Japanese, Chinese, Korean)
* <li>RT - Middle East (Arabic, Hebrew)
* <li>TR - Japanese, Chinese, Korean
* <li>TL - Mongolian
* </ul>
* Components whose view and controller code depends on orientation
* should use the <code>isLeftToRight()</code> and
* <code>isHorizontal()</code> methods to
* determine their behavior. They should not include switch-like
* code that keys off of the constants, such as:
* <pre>
* if (orientation == LEFT_TO_RIGHT) {
* ...
* } else if (orientation == RIGHT_TO_LEFT) {
* ...
* } else {
* // Oops
* }
* </pre>
* This is unsafe, since more constants may be added in the future and
* since it is not guaranteed that orientation objects will be unique.
*/
public final class ComponentOrientation implements java.io.Serializable
{
/*
* serialVersionUID
*/
private static final long serialVersionUID = -4113291392143563828L;
// Internal constants used in the implementation
private static final int UNK_BIT = 1;
private static final int HORIZ_BIT = 2;
private static final int LTR_BIT = 4;
/** {@collect.stats}
* Items run left to right and lines flow top to bottom
* Examples: English, French.
*/
public static final ComponentOrientation LEFT_TO_RIGHT =
new ComponentOrientation(HORIZ_BIT|LTR_BIT);
/** {@collect.stats}
* Items run right to left and lines flow top to bottom
* Examples: Arabic, Hebrew.
*/
public static final ComponentOrientation RIGHT_TO_LEFT =
new ComponentOrientation(HORIZ_BIT);
/** {@collect.stats}
* Indicates that a component's orientation has not been set.
* To preserve the behavior of existing applications,
* isLeftToRight will return true for this value.
*/
public static final ComponentOrientation UNKNOWN =
new ComponentOrientation(HORIZ_BIT|LTR_BIT|UNK_BIT);
/** {@collect.stats}
* Are lines horizontal?
* This will return true for horizontal, left-to-right writing
* systems such as Roman.
*/
public boolean isHorizontal() {
return (orientation & HORIZ_BIT) != 0;
}
/** {@collect.stats}
* HorizontalLines: Do items run left-to-right?<br>
* Vertical Lines: Do lines run left-to-right?<br>
* This will return true for horizontal, left-to-right writing
* systems such as Roman.
*/
public boolean isLeftToRight() {
return (orientation & LTR_BIT) != 0;
}
/** {@collect.stats}
* Returns the orientation that is appropriate for the given locale.
* @param locale the specified locale
*/
public static ComponentOrientation getOrientation(Locale locale) {
// A more flexible implementation would consult a ResourceBundle
// to find the appropriate orientation. Until pluggable locales
// are introduced however, the flexiblity isn't really needed.
// So we choose efficiency instead.
String lang = locale.getLanguage();
if( "iw".equals(lang) || "ar".equals(lang)
|| "fa".equals(lang) || "ur".equals(lang) )
{
return RIGHT_TO_LEFT;
} else {
return LEFT_TO_RIGHT;
}
}
/** {@collect.stats}
* Returns the orientation appropriate for the given ResourceBundle's
* localization. Three approaches are tried, in the following order:
* <ol>
* <li>Retrieve a ComponentOrientation object from the ResourceBundle
* using the string "Orientation" as the key.
* <li>Use the ResourceBundle.getLocale to determine the bundle's
* locale, then return the orientation for that locale.
* <li>Return the default locale's orientation.
* </ol>
*
* @deprecated As of J2SE 1.4, use {@link #getOrientation(java.util.Locale)}.
*/
@Deprecated
public static ComponentOrientation getOrientation(ResourceBundle bdl)
{
ComponentOrientation result = null;
try {
result = (ComponentOrientation)bdl.getObject("Orientation");
}
catch (Exception e) {
}
if (result == null) {
result = getOrientation(bdl.getLocale());
}
if (result == null) {
result = getOrientation(Locale.getDefault());
}
return result;
}
private int orientation;
private ComponentOrientation(int value)
{
orientation = value;
}
}
|
Java
|
/*
* Copyright (c) 1997, 2007, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code 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
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package java.awt;
import java.io.*;
/** {@collect.stats}
* The <code>GraphicsConfigTemplate</code> class is used to obtain a valid
* {@link GraphicsConfiguration}. A user instantiates one of these
* objects and then sets all non-default attributes as desired. The
* {@link GraphicsDevice#getBestConfiguration} method found in the
* {@link GraphicsDevice} class is then called with this
* <code>GraphicsConfigTemplate</code>. A valid
* <code>GraphicsConfiguration</code> is returned that meets or exceeds
* what was requested in the <code>GraphicsConfigTemplate</code>.
* @see GraphicsDevice
* @see GraphicsConfiguration
*
* @since 1.2
*/
public abstract class GraphicsConfigTemplate implements Serializable {
/*
* serialVersionUID
*/
private static final long serialVersionUID = -8061369279557787079L;
/** {@collect.stats}
* This class is an abstract class so only subclasses can be
* instantiated.
*/
public GraphicsConfigTemplate() {
}
/** {@collect.stats}
* Value used for "Enum" (Integer) type. States that this
* feature is required for the <code>GraphicsConfiguration</code>
* object. If this feature is not available, do not select the
* <code>GraphicsConfiguration</code> object.
*/
public static final int REQUIRED = 1;
/** {@collect.stats}
* Value used for "Enum" (Integer) type. States that this
* feature is desired for the <code>GraphicsConfiguration</code>
* object. A selection with this feature is preferred over a
* selection that does not include this feature, although both
* selections can be considered valid matches.
*/
public static final int PREFERRED = 2;
/** {@collect.stats}
* Value used for "Enum" (Integer) type. States that this
* feature is not necessary for the selection of the
* <code>GraphicsConfiguration</code> object. A selection
* without this feature is preferred over a selection that
* includes this feature since it is not used.
*/
public static final int UNNECESSARY = 3;
/** {@collect.stats}
* Returns the "best" configuration possible that passes the
* criteria defined in the <code>GraphicsConfigTemplate</code>.
* @param gc the array of <code>GraphicsConfiguration</code>
* objects to choose from.
* @return a <code>GraphicsConfiguration</code> object that is
* the best configuration possible.
* @see GraphicsConfiguration
*/
public abstract GraphicsConfiguration
getBestConfiguration(GraphicsConfiguration[] gc);
/** {@collect.stats}
* Returns a <code>boolean</code> indicating whether or
* not the specified <code>GraphicsConfiguration</code> can be
* used to create a drawing surface that supports the indicated
* features.
* @param gc the <code>GraphicsConfiguration</code> object to test
* @return <code>true</code> if this
* <code>GraphicsConfiguration</code> object can be used to create
* surfaces that support the indicated features;
* <code>false</code> if the <code>GraphicsConfiguration</code> can
* not be used to create a drawing surface usable by this Java(tm)
* API.
*/
public abstract boolean
isGraphicsConfigSupported(GraphicsConfiguration gc);
}
|
Java
|
/*
* Copyright (c) 1996, 2007, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code 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
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package java.awt;
import java.awt.AWTException;
import java.awt.Point;
import java.awt.Toolkit;
import java.io.File;
import java.io.FileInputStream;
import java.util.Hashtable;
import java.util.Properties;
import java.util.StringTokenizer;
import java.util.logging.*;
import java.security.AccessController;
/** {@collect.stats}
* A class to encapsulate the bitmap representation of the mouse cursor.
*
* @see Component#setCursor
* @author Amy Fowler
*/
public class Cursor implements java.io.Serializable {
/** {@collect.stats}
* The default cursor type (gets set if no cursor is defined).
*/
public static final int DEFAULT_CURSOR = 0;
/** {@collect.stats}
* The crosshair cursor type.
*/
public static final int CROSSHAIR_CURSOR = 1;
/** {@collect.stats}
* The text cursor type.
*/
public static final int TEXT_CURSOR = 2;
/** {@collect.stats}
* The wait cursor type.
*/
public static final int WAIT_CURSOR = 3;
/** {@collect.stats}
* The south-west-resize cursor type.
*/
public static final int SW_RESIZE_CURSOR = 4;
/** {@collect.stats}
* The south-east-resize cursor type.
*/
public static final int SE_RESIZE_CURSOR = 5;
/** {@collect.stats}
* The north-west-resize cursor type.
*/
public static final int NW_RESIZE_CURSOR = 6;
/** {@collect.stats}
* The north-east-resize cursor type.
*/
public static final int NE_RESIZE_CURSOR = 7;
/** {@collect.stats}
* The north-resize cursor type.
*/
public static final int N_RESIZE_CURSOR = 8;
/** {@collect.stats}
* The south-resize cursor type.
*/
public static final int S_RESIZE_CURSOR = 9;
/** {@collect.stats}
* The west-resize cursor type.
*/
public static final int W_RESIZE_CURSOR = 10;
/** {@collect.stats}
* The east-resize cursor type.
*/
public static final int E_RESIZE_CURSOR = 11;
/** {@collect.stats}
* The hand cursor type.
*/
public static final int HAND_CURSOR = 12;
/** {@collect.stats}
* The move cursor type.
*/
public static final int MOVE_CURSOR = 13;
protected static Cursor predefined[] = new Cursor[14];
/** {@collect.stats}
* This field is a private replacement for 'predefined' array.
*/
private final static Cursor[] predefinedPrivate = new Cursor[14];
/* Localization names and default values */
static final String[][] cursorProperties = {
{ "AWT.DefaultCursor", "Default Cursor" },
{ "AWT.CrosshairCursor", "Crosshair Cursor" },
{ "AWT.TextCursor", "Text Cursor" },
{ "AWT.WaitCursor", "Wait Cursor" },
{ "AWT.SWResizeCursor", "Southwest Resize Cursor" },
{ "AWT.SEResizeCursor", "Southeast Resize Cursor" },
{ "AWT.NWResizeCursor", "Northwest Resize Cursor" },
{ "AWT.NEResizeCursor", "Northeast Resize Cursor" },
{ "AWT.NResizeCursor", "North Resize Cursor" },
{ "AWT.SResizeCursor", "South Resize Cursor" },
{ "AWT.WResizeCursor", "West Resize Cursor" },
{ "AWT.EResizeCursor", "East Resize Cursor" },
{ "AWT.HandCursor", "Hand Cursor" },
{ "AWT.MoveCursor", "Move Cursor" },
};
/** {@collect.stats}
* The chosen cursor type initially set to
* the <code>DEFAULT_CURSOR</code>.
*
* @serial
* @see #getType()
*/
int type = DEFAULT_CURSOR;
/** {@collect.stats}
* The type associated with all custom cursors.
*/
public static final int CUSTOM_CURSOR = -1;
/*
* hashtable, filesystem dir prefix, filename, and properties for custom cursors support
*/
private static final Hashtable systemCustomCursors = new Hashtable(1);
private static final String systemCustomCursorDirPrefix = initCursorDir();
private static String initCursorDir() {
String jhome = (String) java.security.AccessController.doPrivileged(
new sun.security.action.GetPropertyAction("java.home"));
return jhome +
File.separator + "lib" + File.separator + "images" +
File.separator + "cursors" + File.separator;
}
private static final String systemCustomCursorPropertiesFile = systemCustomCursorDirPrefix + "cursors.properties";
private static Properties systemCustomCursorProperties = null;
private static final String CursorDotPrefix = "Cursor.";
private static final String DotFileSuffix = ".File";
private static final String DotHotspotSuffix = ".HotSpot";
private static final String DotNameSuffix = ".Name";
/*
* JDK 1.1 serialVersionUID
*/
private static final long serialVersionUID = 8028237497568985504L;
private static final Logger log = Logger.getLogger("java.awt.Cursor");
static {
/* ensure that the necessary native libraries are loaded */
Toolkit.loadLibraries();
if (!GraphicsEnvironment.isHeadless()) {
initIDs();
}
}
/** {@collect.stats}
* Initialize JNI field and method IDs for fields that may be
* accessed from C.
*/
private static native void initIDs();
/** {@collect.stats}
* Hook into native data.
*/
private transient long pData;
private transient Object anchor = new Object();
static class CursorDisposer implements sun.java2d.DisposerRecord {
volatile long pData;
public CursorDisposer(long pData) {
this.pData = pData;
}
public void dispose() {
if (pData != 0) {
finalizeImpl(pData);
}
}
}
transient CursorDisposer disposer;
private void setPData(long pData) {
this.pData = pData;
if (GraphicsEnvironment.isHeadless()) {
return;
}
if (disposer == null) {
disposer = new CursorDisposer(pData);
// anchor is null after deserialization
if (anchor == null) {
anchor = new Object();
}
sun.java2d.Disposer.addRecord(anchor, disposer);
} else {
disposer.pData = pData;
}
}
/** {@collect.stats}
* The user-visible name of the cursor.
*
* @serial
* @see #getName()
*/
protected String name;
/** {@collect.stats}
* Returns a cursor object with the specified predefined type.
*
* @param type the type of predefined cursor
* @return the specified predefined cursor
* @throws IllegalArgumentException if the specified cursor type is
* invalid
*/
static public Cursor getPredefinedCursor(int type) {
if (type < Cursor.DEFAULT_CURSOR || type > Cursor.MOVE_CURSOR) {
throw new IllegalArgumentException("illegal cursor type");
}
Cursor c = predefinedPrivate[type];
if (c == null) {
predefinedPrivate[type] = c = new Cursor(type);
}
// fill 'predefined' array for backwards compatibility.
if (predefined[type] == null) {
predefined[type] = c;
}
return c;
}
/** {@collect.stats}
* Returns a system-specific custom cursor object matching the
* specified name. Cursor names are, for example: "Invalid.16x16"
*
* @param name a string describing the desired system-specific custom cursor
* @return the system specific custom cursor named
* @exception HeadlessException if
* <code>GraphicsEnvironment.isHeadless</code> returns true
*/
static public Cursor getSystemCustomCursor(final String name)
throws AWTException, HeadlessException {
GraphicsEnvironment.checkHeadless();
Cursor cursor = (Cursor)systemCustomCursors.get(name);
if (cursor == null) {
synchronized(systemCustomCursors) {
if (systemCustomCursorProperties == null)
loadSystemCustomCursorProperties();
}
String prefix = CursorDotPrefix + name;
String key = prefix + DotFileSuffix;
if (!systemCustomCursorProperties.containsKey(key)) {
if (log.isLoggable(Level.FINER)) {
log.log(Level.FINER, "Cursor.getSystemCustomCursor(" + name + ") returned null");
}
return null;
}
final String fileName =
systemCustomCursorProperties.getProperty(key);
String localized = (String)systemCustomCursorProperties.getProperty(prefix + DotNameSuffix);
if (localized == null) localized = name;
String hotspot = (String)systemCustomCursorProperties.getProperty(prefix + DotHotspotSuffix);
if (hotspot == null)
throw new AWTException("no hotspot property defined for cursor: " + name);
StringTokenizer st = new StringTokenizer(hotspot, ",");
if (st.countTokens() != 2)
throw new AWTException("failed to parse hotspot property for cursor: " + name);
int x = 0;
int y = 0;
try {
x = Integer.parseInt(st.nextToken());
y = Integer.parseInt(st.nextToken());
} catch (NumberFormatException nfe) {
throw new AWTException("failed to parse hotspot property for cursor: " + name);
}
try {
final int fx = x;
final int fy = y;
final String flocalized = localized;
cursor = (Cursor) java.security.AccessController.doPrivileged(
new java.security.PrivilegedExceptionAction() {
public Object run() throws Exception {
Toolkit toolkit = Toolkit.getDefaultToolkit();
Image image = toolkit.getImage(
systemCustomCursorDirPrefix + fileName);
return toolkit.createCustomCursor(
image, new Point(fx,fy), flocalized);
}
});
} catch (Exception e) {
throw new AWTException(
"Exception: " + e.getClass() + " " + e.getMessage() +
" occurred while creating cursor " + name);
}
if (cursor == null) {
if (log.isLoggable(Level.FINER)) {
log.log(Level.FINER, "Cursor.getSystemCustomCursor(" + name + ") returned null");
}
} else {
systemCustomCursors.put(name, cursor);
}
}
return cursor;
}
/** {@collect.stats}
* Return the system default cursor.
*/
static public Cursor getDefaultCursor() {
return getPredefinedCursor(Cursor.DEFAULT_CURSOR);
}
/** {@collect.stats}
* Creates a new cursor object with the specified type.
* @param type the type of cursor
* @throws IllegalArgumentException if the specified cursor type
* is invalid
*/
public Cursor(int type) {
if (type < Cursor.DEFAULT_CURSOR || type > Cursor.MOVE_CURSOR) {
throw new IllegalArgumentException("illegal cursor type");
}
this.type = type;
// Lookup localized name.
name = Toolkit.getProperty(cursorProperties[type][0],
cursorProperties[type][1]);
}
/** {@collect.stats}
* Creates a new custom cursor object with the specified name.<p>
* Note: this constructor should only be used by AWT implementations
* as part of their support for custom cursors. Applications should
* use Toolkit.createCustomCursor().
* @param name the user-visible name of the cursor.
* @see java.awt.Toolkit#createCustomCursor
*/
protected Cursor(String name) {
this.type = Cursor.CUSTOM_CURSOR;
this.name = name;
}
/** {@collect.stats}
* Returns the type for this cursor.
*/
public int getType() {
return type;
}
/** {@collect.stats}
* Returns the name of this cursor.
* @return a localized description of this cursor.
* @since 1.2
*/
public String getName() {
return name;
}
/** {@collect.stats}
* Returns a string representation of this cursor.
* @return a string representation of this cursor.
* @since 1.2
*/
public String toString() {
return getClass().getName() + "[" + getName() + "]";
}
/*
* load the cursor.properties file
*/
private static void loadSystemCustomCursorProperties() throws AWTException {
synchronized(systemCustomCursors) {
systemCustomCursorProperties = new Properties();
try {
AccessController.doPrivileged(
new java.security.PrivilegedExceptionAction() {
public Object run() throws Exception {
FileInputStream fis = null;
try {
fis = new FileInputStream(
systemCustomCursorPropertiesFile);
systemCustomCursorProperties.load(fis);
} finally {
if (fis != null)
fis.close();
}
return null;
}
});
} catch (Exception e) {
systemCustomCursorProperties = null;
throw new AWTException("Exception: " + e.getClass() + " " +
e.getMessage() + " occurred while loading: " +
systemCustomCursorPropertiesFile);
}
}
}
private native static void finalizeImpl(long pData);
}
|
Java
|
/*
* Copyright (c) 1996, 1997, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code 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
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package java.awt;
/** {@collect.stats}
* An abstract class which provides a print graphics context for a page.
*
* @author Amy Fowler
*/
public interface PrintGraphics {
/** {@collect.stats}
* Returns the PrintJob object from which this PrintGraphics
* object originated.
*/
public PrintJob getPrintJob();
}
|
Java
|
/*
* Copyright (c) 1995, 2006, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code 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
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package java.awt;
import java.util.Hashtable;
/** {@collect.stats}
* A border layout lays out a container, arranging and resizing
* its components to fit in five regions:
* north, south, east, west, and center.
* Each region may contain no more than one component, and
* is identified by a corresponding constant:
* <code>NORTH</code>, <code>SOUTH</code>, <code>EAST</code>,
* <code>WEST</code>, and <code>CENTER</code>. When adding a
* component to a container with a border layout, use one of these
* five constants, for example:
* <pre>
* Panel p = new Panel();
* p.setLayout(new BorderLayout());
* p.add(new Button("Okay"), BorderLayout.SOUTH);
* </pre>
* As a convenience, <code>BorderLayout</code> interprets the
* absence of a string specification the same as the constant
* <code>CENTER</code>:
* <pre>
* Panel p2 = new Panel();
* p2.setLayout(new BorderLayout());
* p2.add(new TextArea()); // Same as p.add(new TextArea(), BorderLayout.CENTER);
* </pre>
* <p>
* In addition, <code>BorderLayout</code> supports the relative
* positioning constants, <code>PAGE_START</code>, <code>PAGE_END</code>,
* <code>LINE_START</code>, and <code>LINE_END</code>.
* In a container whose <code>ComponentOrientation</code> is set to
* <code>ComponentOrientation.LEFT_TO_RIGHT</code>, these constants map to
* <code>NORTH</code>, <code>SOUTH</code>, <code>WEST</code>, and
* <code>EAST</code>, respectively.
* <p>
* For compatibility with previous releases, <code>BorderLayout</code>
* also includes the relative positioning constants <code>BEFORE_FIRST_LINE</code>,
* <code>AFTER_LAST_LINE</code>, <code>BEFORE_LINE_BEGINS</code> and
* <code>AFTER_LINE_ENDS</code>. These are equivalent to
* <code>PAGE_START</code>, <code>PAGE_END</code>, <code>LINE_START</code>
* and <code>LINE_END</code> respectively. For
* consistency with the relative positioning constants used by other
* components, the latter constants are preferred.
* <p>
* Mixing both absolute and relative positioning constants can lead to
* unpredicable results. If
* you use both types, the relative constants will take precedence.
* For example, if you add components using both the <code>NORTH</code>
* and <code>PAGE_START</code> constants in a container whose
* orientation is <code>LEFT_TO_RIGHT</code>, only the
* <code>PAGE_START</code> will be layed out.
* <p>
* NOTE: Currently (in the Java 2 platform v1.2),
* <code>BorderLayout</code> does not support vertical
* orientations. The <code>isVertical</code> setting on the container's
* <code>ComponentOrientation</code> is not respected.
* <p>
* The components are laid out according to their
* preferred sizes and the constraints of the container's size.
* The <code>NORTH</code> and <code>SOUTH</code> components may
* be stretched horizontally; the <code>EAST</code> and
* <code>WEST</code> components may be stretched vertically;
* the <code>CENTER</code> component may stretch both horizontally
* and vertically to fill any space left over.
* <p>
* Here is an example of five buttons in an applet laid out using
* the <code>BorderLayout</code> layout manager:
* <p>
* <img src="doc-files/BorderLayout-1.gif"
* alt="Diagram of an applet demonstrating BorderLayout.
* Each section of the BorderLayout contains a Button corresponding to its position in the layout, one of:
* North, West, Center, East, or South."
* ALIGN=center HSPACE=10 VSPACE=7>
* <p>
* The code for this applet is as follows:
* <p>
* <hr><blockquote><pre>
* import java.awt.*;
* import java.applet.Applet;
*
* public class buttonDir extends Applet {
* public void init() {
* setLayout(new BorderLayout());
* add(new Button("North"), BorderLayout.NORTH);
* add(new Button("South"), BorderLayout.SOUTH);
* add(new Button("East"), BorderLayout.EAST);
* add(new Button("West"), BorderLayout.WEST);
* add(new Button("Center"), BorderLayout.CENTER);
* }
* }
* </pre></blockquote><hr>
* <p>
* @author Arthur van Hoff
* @see java.awt.Container#add(String, Component)
* @see java.awt.ComponentOrientation
* @since JDK1.0
*/
public class BorderLayout implements LayoutManager2,
java.io.Serializable {
/** {@collect.stats}
* Constructs a border layout with the horizontal gaps
* between components.
* The horizontal gap is specified by <code>hgap</code>.
*
* @see #getHgap()
* @see #setHgap(int)
*
* @serial
*/
int hgap;
/** {@collect.stats}
* Constructs a border layout with the vertical gaps
* between components.
* The vertical gap is specified by <code>vgap</code>.
*
* @see #getVgap()
* @see #setVgap(int)
* @serial
*/
int vgap;
/** {@collect.stats}
* Constant to specify components location to be the
* north portion of the border layout.
* @serial
* @see #getChild(String, boolean)
* @see #addLayoutComponent
* @see #getLayoutAlignmentX
* @see #getLayoutAlignmentY
* @see #removeLayoutComponent
*/
Component north;
/** {@collect.stats}
* Constant to specify components location to be the
* west portion of the border layout.
* @serial
* @see #getChild(String, boolean)
* @see #addLayoutComponent
* @see #getLayoutAlignmentX
* @see #getLayoutAlignmentY
* @see #removeLayoutComponent
*/
Component west;
/** {@collect.stats}
* Constant to specify components location to be the
* east portion of the border layout.
* @serial
* @see #getChild(String, boolean)
* @see #addLayoutComponent
* @see #getLayoutAlignmentX
* @see #getLayoutAlignmentY
* @see #removeLayoutComponent
*/
Component east;
/** {@collect.stats}
* Constant to specify components location to be the
* south portion of the border layout.
* @serial
* @see #getChild(String, boolean)
* @see #addLayoutComponent
* @see #getLayoutAlignmentX
* @see #getLayoutAlignmentY
* @see #removeLayoutComponent
*/
Component south;
/** {@collect.stats}
* Constant to specify components location to be the
* center portion of the border layout.
* @serial
* @see #getChild(String, boolean)
* @see #addLayoutComponent
* @see #getLayoutAlignmentX
* @see #getLayoutAlignmentY
* @see #removeLayoutComponent
*/
Component center;
/** {@collect.stats}
*
* A relative positioning constant, that can be used instead of
* north, south, east, west or center.
* mixing the two types of constants can lead to unpredicable results. If
* you use both types, the relative constants will take precedence.
* For example, if you add components using both the <code>NORTH</code>
* and <code>BEFORE_FIRST_LINE</code> constants in a container whose
* orientation is <code>LEFT_TO_RIGHT</code>, only the
* <code>BEFORE_FIRST_LINE</code> will be layed out.
* This will be the same for lastLine, firstItem, lastItem.
* @serial
*/
Component firstLine;
/** {@collect.stats}
* A relative positioning constant, that can be used instead of
* north, south, east, west or center.
* Please read Description for firstLine.
* @serial
*/
Component lastLine;
/** {@collect.stats}
* A relative positioning constant, that can be used instead of
* north, south, east, west or center.
* Please read Description for firstLine.
* @serial
*/
Component firstItem;
/** {@collect.stats}
* A relative positioning constant, that can be used instead of
* north, south, east, west or center.
* Please read Description for firstLine.
* @serial
*/
Component lastItem;
/** {@collect.stats}
* The north layout constraint (top of container).
*/
public static final String NORTH = "North";
/** {@collect.stats}
* The south layout constraint (bottom of container).
*/
public static final String SOUTH = "South";
/** {@collect.stats}
* The east layout constraint (right side of container).
*/
public static final String EAST = "East";
/** {@collect.stats}
* The west layout constraint (left side of container).
*/
public static final String WEST = "West";
/** {@collect.stats}
* The center layout constraint (middle of container).
*/
public static final String CENTER = "Center";
/** {@collect.stats}
* Synonym for PAGE_START. Exists for compatibility with previous
* versions. PAGE_START is preferred.
*
* @see #PAGE_START
* @since 1.2
*/
public static final String BEFORE_FIRST_LINE = "First";
/** {@collect.stats}
* Synonym for PAGE_END. Exists for compatibility with previous
* versions. PAGE_END is preferred.
*
* @see #PAGE_END
* @since 1.2
*/
public static final String AFTER_LAST_LINE = "Last";
/** {@collect.stats}
* Synonym for LINE_START. Exists for compatibility with previous
* versions. LINE_START is preferred.
*
* @see #LINE_START
* @since 1.2
*/
public static final String BEFORE_LINE_BEGINS = "Before";
/** {@collect.stats}
* Synonym for LINE_END. Exists for compatibility with previous
* versions. LINE_END is preferred.
*
* @see #LINE_END
* @since 1.2
*/
public static final String AFTER_LINE_ENDS = "After";
/** {@collect.stats}
* The component comes before the first line of the layout's content.
* For Western, left-to-right and top-to-bottom orientations, this is
* equivalent to NORTH.
*
* @see java.awt.Component#getComponentOrientation
* @since 1.4
*/
public static final String PAGE_START = BEFORE_FIRST_LINE;
/** {@collect.stats}
* The component comes after the last line of the layout's content.
* For Western, left-to-right and top-to-bottom orientations, this is
* equivalent to SOUTH.
*
* @see java.awt.Component#getComponentOrientation
* @since 1.4
*/
public static final String PAGE_END = AFTER_LAST_LINE;
/** {@collect.stats}
* The component goes at the beginning of the line direction for the
* layout. For Western, left-to-right and top-to-bottom orientations,
* this is equivalent to WEST.
*
* @see java.awt.Component#getComponentOrientation
* @since 1.4
*/
public static final String LINE_START = BEFORE_LINE_BEGINS;
/** {@collect.stats}
* The component goes at the end of the line direction for the
* layout. For Western, left-to-right and top-to-bottom orientations,
* this is equivalent to EAST.
*
* @see java.awt.Component#getComponentOrientation
* @since 1.4
*/
public static final String LINE_END = AFTER_LINE_ENDS;
/*
* JDK 1.1 serialVersionUID
*/
private static final long serialVersionUID = -8658291919501921765L;
/** {@collect.stats}
* Constructs a new border layout with
* no gaps between components.
*/
public BorderLayout() {
this(0, 0);
}
/** {@collect.stats}
* Constructs a border layout with the specified gaps
* between components.
* The horizontal gap is specified by <code>hgap</code>
* and the vertical gap is specified by <code>vgap</code>.
* @param hgap the horizontal gap.
* @param vgap the vertical gap.
*/
public BorderLayout(int hgap, int vgap) {
this.hgap = hgap;
this.vgap = vgap;
}
/** {@collect.stats}
* Returns the horizontal gap between components.
* @since JDK1.1
*/
public int getHgap() {
return hgap;
}
/** {@collect.stats}
* Sets the horizontal gap between components.
* @param hgap the horizontal gap between components
* @since JDK1.1
*/
public void setHgap(int hgap) {
this.hgap = hgap;
}
/** {@collect.stats}
* Returns the vertical gap between components.
* @since JDK1.1
*/
public int getVgap() {
return vgap;
}
/** {@collect.stats}
* Sets the vertical gap between components.
* @param vgap the vertical gap between components
* @since JDK1.1
*/
public void setVgap(int vgap) {
this.vgap = vgap;
}
/** {@collect.stats}
* Adds the specified component to the layout, using the specified
* constraint object. For border layouts, the constraint must be
* one of the following constants: <code>NORTH</code>,
* <code>SOUTH</code>, <code>EAST</code>,
* <code>WEST</code>, or <code>CENTER</code>.
* <p>
* Most applications do not call this method directly. This method
* is called when a component is added to a container using the
* <code>Container.add</code> method with the same argument types.
* @param comp the component to be added.
* @param constraints an object that specifies how and where
* the component is added to the layout.
* @see java.awt.Container#add(java.awt.Component, java.lang.Object)
* @exception IllegalArgumentException if the constraint object is not
* a string, or if it not one of the five specified
* constants.
* @since JDK1.1
*/
public void addLayoutComponent(Component comp, Object constraints) {
synchronized (comp.getTreeLock()) {
if ((constraints == null) || (constraints instanceof String)) {
addLayoutComponent((String)constraints, comp);
} else {
throw new IllegalArgumentException("cannot add to layout: constraint must be a string (or null)");
}
}
}
/** {@collect.stats}
* @deprecated replaced by <code>addLayoutComponent(Component, Object)</code>.
*/
@Deprecated
public void addLayoutComponent(String name, Component comp) {
synchronized (comp.getTreeLock()) {
/* Special case: treat null the same as "Center". */
if (name == null) {
name = "Center";
}
/* Assign the component to one of the known regions of the layout.
*/
if ("Center".equals(name)) {
center = comp;
} else if ("North".equals(name)) {
north = comp;
} else if ("South".equals(name)) {
south = comp;
} else if ("East".equals(name)) {
east = comp;
} else if ("West".equals(name)) {
west = comp;
} else if (BEFORE_FIRST_LINE.equals(name)) {
firstLine = comp;
} else if (AFTER_LAST_LINE.equals(name)) {
lastLine = comp;
} else if (BEFORE_LINE_BEGINS.equals(name)) {
firstItem = comp;
} else if (AFTER_LINE_ENDS.equals(name)) {
lastItem = comp;
} else {
throw new IllegalArgumentException("cannot add to layout: unknown constraint: " + name);
}
}
}
/** {@collect.stats}
* Removes the specified component from this border layout. This
* method is called when a container calls its <code>remove</code> or
* <code>removeAll</code> methods. Most applications do not call this
* method directly.
* @param comp the component to be removed.
* @see java.awt.Container#remove(java.awt.Component)
* @see java.awt.Container#removeAll()
*/
public void removeLayoutComponent(Component comp) {
synchronized (comp.getTreeLock()) {
if (comp == center) {
center = null;
} else if (comp == north) {
north = null;
} else if (comp == south) {
south = null;
} else if (comp == east) {
east = null;
} else if (comp == west) {
west = null;
}
if (comp == firstLine) {
firstLine = null;
} else if (comp == lastLine) {
lastLine = null;
} else if (comp == firstItem) {
firstItem = null;
} else if (comp == lastItem) {
lastItem = null;
}
}
}
/** {@collect.stats}
* Gets the component that was added using the given constraint
*
* @param constraints the desired constraint, one of <code>CENTER</code>,
* <code>NORTH</code>, <code>SOUTH</code>,
* <code>WEST</code>, <code>EAST</code>,
* <code>PAGE_START</code>, <code>PAGE_END</code>,
* <code>LINE_START</code>, <code>LINE_END</code>
* @return the component at the given location, or <code>null</code> if
* the location is empty
* @exception IllegalArgumentException if the constraint object is
* not one of the nine specified constants
* @see #addLayoutComponent(java.awt.Component, java.lang.Object)
* @since 1.5
*/
public Component getLayoutComponent(Object constraints) {
if (CENTER.equals(constraints)) {
return center;
} else if (NORTH.equals(constraints)) {
return north;
} else if (SOUTH.equals(constraints)) {
return south;
} else if (WEST.equals(constraints)) {
return west;
} else if (EAST.equals(constraints)) {
return east;
} else if (PAGE_START.equals(constraints)) {
return firstLine;
} else if (PAGE_END.equals(constraints)) {
return lastLine;
} else if (LINE_START.equals(constraints)) {
return firstItem;
} else if (LINE_END.equals(constraints)) {
return lastItem;
} else {
throw new IllegalArgumentException("cannot get component: unknown constraint: " + constraints);
}
}
/** {@collect.stats}
* Returns the component that corresponds to the given constraint location
* based on the target <code>Container</code>'s component orientation.
* Components added with the relative constraints <code>PAGE_START</code>,
* <code>PAGE_END</code>, <code>LINE_START</code>, and <code>LINE_END</code>
* take precedence over components added with the explicit constraints
* <code>NORTH</code>, <code>SOUTH</code>, <code>WEST</code>, and <code>EAST</code>.
* The <code>Container</code>'s component orientation is used to determine the location of components
* added with <code>LINE_START</code> and <code>LINE_END</code>.
*
* @param constraints the desired absolute position, one of <code>CENTER</code>,
* <code>NORTH</code>, <code>SOUTH</code>,
* <code>EAST</code>, <code>WEST</code>
* @param target the {@code Container} used to obtain
* the constraint location based on the target
* {@code Container}'s component orientation.
* @return the component at the given location, or <code>null</code> if
* the location is empty
* @exception IllegalArgumentException if the constraint object is
* not one of the five specified constants
* @exception NullPointerException if the target parameter is null
* @see #addLayoutComponent(java.awt.Component, java.lang.Object)
* @since 1.5
*/
public Component getLayoutComponent(Container target, Object constraints) {
boolean ltr = target.getComponentOrientation().isLeftToRight();
Component result = null;
if (NORTH.equals(constraints)) {
result = (firstLine != null) ? firstLine : north;
} else if (SOUTH.equals(constraints)) {
result = (lastLine != null) ? lastLine : south;
} else if (WEST.equals(constraints)) {
result = ltr ? firstItem : lastItem;
if (result == null) {
result = west;
}
} else if (EAST.equals(constraints)) {
result = ltr ? lastItem : firstItem;
if (result == null) {
result = east;
}
} else if (CENTER.equals(constraints)) {
result = center;
} else {
throw new IllegalArgumentException("cannot get component: invalid constraint: " + constraints);
}
return result;
}
/** {@collect.stats}
* Gets the constraints for the specified component
*
* @param comp the component to be queried
* @return the constraint for the specified component,
* or null if component is null or is not present
* in this layout
* @see #addLayoutComponent(java.awt.Component, java.lang.Object)
* @since 1.5
*/
public Object getConstraints(Component comp) {
//fix for 6242148 : API method java.awt.BorderLayout.getConstraints(null) should return null
if (comp == null){
return null;
}
if (comp == center) {
return CENTER;
} else if (comp == north) {
return NORTH;
} else if (comp == south) {
return SOUTH;
} else if (comp == west) {
return WEST;
} else if (comp == east) {
return EAST;
} else if (comp == firstLine) {
return PAGE_START;
} else if (comp == lastLine) {
return PAGE_END;
} else if (comp == firstItem) {
return LINE_START;
} else if (comp == lastItem) {
return LINE_END;
}
return null;
}
/** {@collect.stats}
* Determines the minimum size of the <code>target</code> container
* using this layout manager.
* <p>
* This method is called when a container calls its
* <code>getMinimumSize</code> method. Most applications do not call
* this method directly.
* @param target the container in which to do the layout.
* @return the minimum dimensions needed to lay out the subcomponents
* of the specified container.
* @see java.awt.Container
* @see java.awt.BorderLayout#preferredLayoutSize
* @see java.awt.Container#getMinimumSize()
*/
public Dimension minimumLayoutSize(Container target) {
synchronized (target.getTreeLock()) {
Dimension dim = new Dimension(0, 0);
boolean ltr = target.getComponentOrientation().isLeftToRight();
Component c = null;
if ((c=getChild(EAST,ltr)) != null) {
Dimension d = c.getMinimumSize();
dim.width += d.width + hgap;
dim.height = Math.max(d.height, dim.height);
}
if ((c=getChild(WEST,ltr)) != null) {
Dimension d = c.getMinimumSize();
dim.width += d.width + hgap;
dim.height = Math.max(d.height, dim.height);
}
if ((c=getChild(CENTER,ltr)) != null) {
Dimension d = c.getMinimumSize();
dim.width += d.width;
dim.height = Math.max(d.height, dim.height);
}
if ((c=getChild(NORTH,ltr)) != null) {
Dimension d = c.getMinimumSize();
dim.width = Math.max(d.width, dim.width);
dim.height += d.height + vgap;
}
if ((c=getChild(SOUTH,ltr)) != null) {
Dimension d = c.getMinimumSize();
dim.width = Math.max(d.width, dim.width);
dim.height += d.height + vgap;
}
Insets insets = target.getInsets();
dim.width += insets.left + insets.right;
dim.height += insets.top + insets.bottom;
return dim;
}
}
/** {@collect.stats}
* Determines the preferred size of the <code>target</code>
* container using this layout manager, based on the components
* in the container.
* <p>
* Most applications do not call this method directly. This method
* is called when a container calls its <code>getPreferredSize</code>
* method.
* @param target the container in which to do the layout.
* @return the preferred dimensions to lay out the subcomponents
* of the specified container.
* @see java.awt.Container
* @see java.awt.BorderLayout#minimumLayoutSize
* @see java.awt.Container#getPreferredSize()
*/
public Dimension preferredLayoutSize(Container target) {
synchronized (target.getTreeLock()) {
Dimension dim = new Dimension(0, 0);
boolean ltr = target.getComponentOrientation().isLeftToRight();
Component c = null;
if ((c=getChild(EAST,ltr)) != null) {
Dimension d = c.getPreferredSize();
dim.width += d.width + hgap;
dim.height = Math.max(d.height, dim.height);
}
if ((c=getChild(WEST,ltr)) != null) {
Dimension d = c.getPreferredSize();
dim.width += d.width + hgap;
dim.height = Math.max(d.height, dim.height);
}
if ((c=getChild(CENTER,ltr)) != null) {
Dimension d = c.getPreferredSize();
dim.width += d.width;
dim.height = Math.max(d.height, dim.height);
}
if ((c=getChild(NORTH,ltr)) != null) {
Dimension d = c.getPreferredSize();
dim.width = Math.max(d.width, dim.width);
dim.height += d.height + vgap;
}
if ((c=getChild(SOUTH,ltr)) != null) {
Dimension d = c.getPreferredSize();
dim.width = Math.max(d.width, dim.width);
dim.height += d.height + vgap;
}
Insets insets = target.getInsets();
dim.width += insets.left + insets.right;
dim.height += insets.top + insets.bottom;
return dim;
}
}
/** {@collect.stats}
* Returns the maximum dimensions for this layout given the components
* in the specified target container.
* @param target the component which needs to be laid out
* @see Container
* @see #minimumLayoutSize
* @see #preferredLayoutSize
*/
public Dimension maximumLayoutSize(Container target) {
return new Dimension(Integer.MAX_VALUE, Integer.MAX_VALUE);
}
/** {@collect.stats}
* Returns the alignment along the x axis. This specifies how
* the component would like to be aligned relative to other
* components. The value should be a number between 0 and 1
* where 0 represents alignment along the origin, 1 is aligned
* the furthest away from the origin, 0.5 is centered, etc.
*/
public float getLayoutAlignmentX(Container parent) {
return 0.5f;
}
/** {@collect.stats}
* Returns the alignment along the y axis. This specifies how
* the component would like to be aligned relative to other
* components. The value should be a number between 0 and 1
* where 0 represents alignment along the origin, 1 is aligned
* the furthest away from the origin, 0.5 is centered, etc.
*/
public float getLayoutAlignmentY(Container parent) {
return 0.5f;
}
/** {@collect.stats}
* Invalidates the layout, indicating that if the layout manager
* has cached information it should be discarded.
*/
public void invalidateLayout(Container target) {
}
/** {@collect.stats}
* Lays out the container argument using this border layout.
* <p>
* This method actually reshapes the components in the specified
* container in order to satisfy the constraints of this
* <code>BorderLayout</code> object. The <code>NORTH</code>
* and <code>SOUTH</code> components, if any, are placed at
* the top and bottom of the container, respectively. The
* <code>WEST</code> and <code>EAST</code> components are
* then placed on the left and right, respectively. Finally,
* the <code>CENTER</code> object is placed in any remaining
* space in the middle.
* <p>
* Most applications do not call this method directly. This method
* is called when a container calls its <code>doLayout</code> method.
* @param target the container in which to do the layout.
* @see java.awt.Container
* @see java.awt.Container#doLayout()
*/
public void layoutContainer(Container target) {
synchronized (target.getTreeLock()) {
Insets insets = target.getInsets();
int top = insets.top;
int bottom = target.height - insets.bottom;
int left = insets.left;
int right = target.width - insets.right;
boolean ltr = target.getComponentOrientation().isLeftToRight();
Component c = null;
if ((c=getChild(NORTH,ltr)) != null) {
c.setSize(right - left, c.height);
Dimension d = c.getPreferredSize();
c.setBounds(left, top, right - left, d.height);
top += d.height + vgap;
}
if ((c=getChild(SOUTH,ltr)) != null) {
c.setSize(right - left, c.height);
Dimension d = c.getPreferredSize();
c.setBounds(left, bottom - d.height, right - left, d.height);
bottom -= d.height + vgap;
}
if ((c=getChild(EAST,ltr)) != null) {
c.setSize(c.width, bottom - top);
Dimension d = c.getPreferredSize();
c.setBounds(right - d.width, top, d.width, bottom - top);
right -= d.width + hgap;
}
if ((c=getChild(WEST,ltr)) != null) {
c.setSize(c.width, bottom - top);
Dimension d = c.getPreferredSize();
c.setBounds(left, top, d.width, bottom - top);
left += d.width + hgap;
}
if ((c=getChild(CENTER,ltr)) != null) {
c.setBounds(left, top, right - left, bottom - top);
}
}
}
/** {@collect.stats}
* Get the component that corresponds to the given constraint location
*
* @param key The desired absolute position,
* either NORTH, SOUTH, EAST, or WEST.
* @param ltr Is the component line direction left-to-right?
*/
private Component getChild(String key, boolean ltr) {
Component result = null;
if (key == NORTH) {
result = (firstLine != null) ? firstLine : north;
}
else if (key == SOUTH) {
result = (lastLine != null) ? lastLine : south;
}
else if (key == WEST) {
result = ltr ? firstItem : lastItem;
if (result == null) {
result = west;
}
}
else if (key == EAST) {
result = ltr ? lastItem : firstItem;
if (result == null) {
result = east;
}
}
else if (key == CENTER) {
result = center;
}
if (result != null && !result.visible) {
result = null;
}
return result;
}
/** {@collect.stats}
* Returns a string representation of the state of this border layout.
* @return a string representation of this border layout.
*/
public String toString() {
return getClass().getName() + "[hgap=" + hgap + ",vgap=" + vgap + "]";
}
}
|
Java
|
/*
* Copyright (c) 1995, 2006, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code 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
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package java.awt;
import java.awt.peer.FileDialogPeer;
import java.io.FilenameFilter;
import java.io.IOException;
import java.io.ObjectInputStream;
/** {@collect.stats}
* The <code>FileDialog</code> class displays a dialog window
* from which the user can select a file.
* <p>
* Since it is a modal dialog, when the application calls
* its <code>show</code> method to display the dialog,
* it blocks the rest of the application until the user has
* chosen a file.
*
* @see Window#show
*
* @author Sami Shaio
* @author Arthur van Hoff
* @since JDK1.0
*/
public class FileDialog extends Dialog {
/** {@collect.stats}
* This constant value indicates that the purpose of the file
* dialog window is to locate a file from which to read.
*/
public static final int LOAD = 0;
/** {@collect.stats}
* This constant value indicates that the purpose of the file
* dialog window is to locate a file to which to write.
*/
public static final int SAVE = 1;
/*
* There are two <code>FileDialog</code> modes: <code>LOAD</code> and
* <code>SAVE</code>.
* This integer will represent one or the other.
* If the mode is not specified it will default to <code>LOAD</code>.
*
* @serial
* @see getMode()
* @see setMode()
* @see java.awt.FileDialog#LOAD
* @see java.awt.FileDialog#SAVE
*/
int mode;
/*
* The string specifying the directory to display
* in the file dialog. This variable may be <code>null</code>.
*
* @serial
* @see getDirectory()
* @see setDirectory()
*/
String dir;
/*
* The string specifying the initial value of the
* filename text field in the file dialog.
* This variable may be <code>null</code>.
*
* @serial
* @see getFile()
* @see setFile()
*/
String file;
/*
* The filter used as the file dialog's filename filter.
* The file dialog will only be displaying files whose
* names are accepted by this filter.
* This variable may be <code>null</code>.
*
* @serial
* @see #getFilenameFilter()
* @see #setFilenameFilter()
* @see FileNameFilter
*/
FilenameFilter filter;
private static final String base = "filedlg";
private static int nameCounter = 0;
/*
* JDK 1.1 serialVersionUID
*/
private static final long serialVersionUID = 5035145889651310422L;
static {
/* ensure that the necessary native libraries are loaded */
Toolkit.loadLibraries();
if (!GraphicsEnvironment.isHeadless()) {
initIDs();
}
}
/** {@collect.stats}
* Initialize JNI field and method IDs for fields that may be
accessed from C.
*/
private static native void initIDs();
/** {@collect.stats}
* Creates a file dialog for loading a file. The title of the
* file dialog is initially empty. This is a convenience method for
* <code>FileDialog(parent, "", LOAD)</code>.
*
* @param parent the owner of the dialog
* @since JDK1.1
*/
public FileDialog(Frame parent) {
this(parent, "", LOAD);
}
/** {@collect.stats}
* Creates a file dialog window with the specified title for loading
* a file. The files shown are those in the current directory.
* This is a convenience method for
* <code>FileDialog(parent, title, LOAD)</code>.
*
* @param parent the owner of the dialog
* @param title the title of the dialog
*/
public FileDialog(Frame parent, String title) {
this(parent, title, LOAD);
}
/** {@collect.stats}
* Creates a file dialog window with the specified title for loading
* or saving a file.
* <p>
* If the value of <code>mode</code> is <code>LOAD</code>, then the
* file dialog is finding a file to read, and the files shown are those
* in the current directory. If the value of
* <code>mode</code> is <code>SAVE</code>, the file dialog is finding
* a place to write a file.
*
* @param parent the owner of the dialog
* @param title the title of the dialog
* @param mode the mode of the dialog; either
* <code>FileDialog.LOAD</code> or <code>FileDialog.SAVE</code>
* @exception IllegalArgumentException if an illegal file
* dialog mode is supplied
* @see java.awt.FileDialog#LOAD
* @see java.awt.FileDialog#SAVE
*/
public FileDialog(Frame parent, String title, int mode) {
super(parent, title, true);
this.setMode(mode);
setLayout(null);
}
/** {@collect.stats}
* Creates a file dialog for loading a file. The title of the
* file dialog is initially empty. This is a convenience method for
* <code>FileDialog(parent, "", LOAD)</code>.
*
* @param parent the owner of the dialog
* @exception java.lang.IllegalArgumentException if the <code>parent</code>'s
* <code>GraphicsConfiguration</code>
* is not from a screen device;
* @exception java.lang.IllegalArgumentException if <code>parent</code>
* is <code>null</code>; this exception is always thrown when
* <code>GraphicsEnvironment.isHeadless</code>
* returns <code>true</code>
* @see java.awt.GraphicsEnvironment#isHeadless
* @since 1.5
*/
public FileDialog(Dialog parent) {
this(parent, "", LOAD);
}
/** {@collect.stats}
* Creates a file dialog window with the specified title for loading
* a file. The files shown are those in the current directory.
* This is a convenience method for
* <code>FileDialog(parent, title, LOAD)</code>.
*
* @param parent the owner of the dialog
* @param title the title of the dialog; a <code>null</code> value
* will be accepted without causing a
* <code>NullPointerException</code> to be thrown
* @exception java.lang.IllegalArgumentException if the <code>parent</code>'s
* <code>GraphicsConfiguration</code>
* is not from a screen device;
* @exception java.lang.IllegalArgumentException if <code>parent</code>
* is <code>null</code>; this exception is always thrown when
* <code>GraphicsEnvironment.isHeadless</code>
* returns <code>true</code>
* @see java.awt.GraphicsEnvironment#isHeadless
* @since 1.5
*/
public FileDialog(Dialog parent, String title) {
this(parent, title, LOAD);
}
/** {@collect.stats}
* Creates a file dialog window with the specified title for loading
* or saving a file.
* <p>
* If the value of <code>mode</code> is <code>LOAD</code>, then the
* file dialog is finding a file to read, and the files shown are those
* in the current directory. If the value of
* <code>mode</code> is <code>SAVE</code>, the file dialog is finding
* a place to write a file.
*
* @param parent the owner of the dialog
* @param title the title of the dialog; a <code>null</code> value
* will be accepted without causing a
* <code>NullPointerException</code> to be thrown
* @param mode the mode of the dialog; either
* <code>FileDialog.LOAD</code> or <code>FileDialog.SAVE</code>
* @exception java.lang.IllegalArgumentException if an illegal
* file dialog mode is supplied;
* @exception java.lang.IllegalArgumentException if the <code>parent</code>'s
* <code>GraphicsConfiguration</code>
* is not from a screen device;
* @exception java.lang.IllegalArgumentException if <code>parent</code>
* is <code>null</code>; this exception is always thrown when
* <code>GraphicsEnvironment.isHeadless</code>
* returns <code>true</code>
* @see java.awt.GraphicsEnvironment#isHeadless
* @see java.awt.FileDialog#LOAD
* @see java.awt.FileDialog#SAVE
* @since 1.5
*/
public FileDialog(Dialog parent, String title, int mode) {
super(parent, title, true);
this.setMode(mode);
setLayout(null);
}
/** {@collect.stats}
* Constructs a name for this component. Called by <code>getName()</code>
* when the name is <code>null</code>.
*/
String constructComponentName() {
synchronized (FileDialog.class) {
return base + nameCounter++;
}
}
/** {@collect.stats}
* Creates the file dialog's peer. The peer allows us to change the look
* of the file dialog without changing its functionality.
*/
public void addNotify() {
synchronized(getTreeLock()) {
if (parent != null && parent.getPeer() == null) {
parent.addNotify();
}
if (peer == null)
peer = getToolkit().createFileDialog(this);
super.addNotify();
}
}
/** {@collect.stats}
* Indicates whether this file dialog box is for loading from a file
* or for saving to a file.
*
* @return the mode of this file dialog window, either
* <code>FileDialog.LOAD</code> or
* <code>FileDialog.SAVE</code>
* @see java.awt.FileDialog#LOAD
* @see java.awt.FileDialog#SAVE
* @see java.awt.FileDialog#setMode
*/
public int getMode() {
return mode;
}
/** {@collect.stats}
* Sets the mode of the file dialog. If <code>mode</code> is not
* a legal value, an exception will be thrown and <code>mode</code>
* will not be set.
*
* @param mode the mode for this file dialog, either
* <code>FileDialog.LOAD</code> or
* <code>FileDialog.SAVE</code>
* @see java.awt.FileDialog#LOAD
* @see java.awt.FileDialog#SAVE
* @see java.awt.FileDialog#getMode
* @exception IllegalArgumentException if an illegal file
* dialog mode is supplied
* @since JDK1.1
*/
public void setMode(int mode) {
switch (mode) {
case LOAD:
case SAVE:
this.mode = mode;
break;
default:
throw new IllegalArgumentException("illegal file dialog mode");
}
}
/** {@collect.stats}
* Gets the directory of this file dialog.
*
* @return the (potentially <code>null</code> or invalid)
* directory of this <code>FileDialog</code>
* @see java.awt.FileDialog#setDirectory
*/
public String getDirectory() {
return dir;
}
/** {@collect.stats}
* Sets the directory of this file dialog window to be the
* specified directory. Specifying a <code>null</code> or an
* invalid directory implies an implementation-defined default.
* This default will not be realized, however, until the user
* has selected a file. Until this point, <code>getDirectory()</code>
* will return the value passed into this method.
* <p>
* Specifying "" as the directory is exactly equivalent to
* specifying <code>null</code> as the directory.
*
* @param dir the specified directory
* @see java.awt.FileDialog#getDirectory
*/
public void setDirectory(String dir) {
this.dir = (dir != null && dir.equals("")) ? null : dir;
FileDialogPeer peer = (FileDialogPeer)this.peer;
if (peer != null) {
peer.setDirectory(this.dir);
}
}
/** {@collect.stats}
* Gets the selected file of this file dialog. If the user
* selected <code>CANCEL</code>, the returned file is <code>null</code>.
*
* @return the currently selected file of this file dialog window,
* or <code>null</code> if none is selected
* @see java.awt.FileDialog#setFile
*/
public String getFile() {
return file;
}
/** {@collect.stats}
* Sets the selected file for this file dialog window to be the
* specified file. This file becomes the default file if it is set
* before the file dialog window is first shown.
* <p>
* Specifying "" as the file is exactly equivalent to specifying
* <code>null</code>
* as the file.
*
* @param file the file being set
* @see java.awt.FileDialog#getFile
*/
public void setFile(String file) {
this.file = (file != null && file.equals("")) ? null : file;
FileDialogPeer peer = (FileDialogPeer)this.peer;
if (peer != null) {
peer.setFile(this.file);
}
}
/** {@collect.stats}
* Determines this file dialog's filename filter. A filename filter
* allows the user to specify which files appear in the file dialog
* window. Filename filters do not function in Sun's reference
* implementation for Microsoft Windows.
*
* @return this file dialog's filename filter
* @see java.io.FilenameFilter
* @see java.awt.FileDialog#setFilenameFilter
*/
public FilenameFilter getFilenameFilter() {
return filter;
}
/** {@collect.stats}
* Sets the filename filter for this file dialog window to the
* specified filter.
* Filename filters do not function in Sun's reference
* implementation for Microsoft Windows.
*
* @param filter the specified filter
* @see java.io.FilenameFilter
* @see java.awt.FileDialog#getFilenameFilter
*/
public synchronized void setFilenameFilter(FilenameFilter filter) {
this.filter = filter;
FileDialogPeer peer = (FileDialogPeer)this.peer;
if (peer != null) {
peer.setFilenameFilter(filter);
}
}
/** {@collect.stats}
* Reads the <code>ObjectInputStream</code> and performs
* a backwards compatibility check by converting
* either a <code>dir</code> or a <code>file</code>
* equal to an empty string to <code>null</code>.
*
* @param s the <code>ObjectInputStream</code> to read
*/
private void readObject(ObjectInputStream s)
throws ClassNotFoundException, IOException
{
s.defaultReadObject();
// 1.1 Compatibility: "" is not converted to null in 1.1
if (dir != null && dir.equals("")) {
dir = null;
}
if (file != null && file.equals("")) {
file = null;
}
}
/** {@collect.stats}
* Returns a string representing the state of this <code>FileDialog</code>
* window. This method is intended to be used only for debugging purposes,
* and the content and format of the returned string may vary between
* implementations. The returned string may be empty but may not be
* <code>null</code>.
*
* @return the parameter string of this file dialog window
*/
protected String paramString() {
String str = super.paramString();
str += ",dir= " + dir;
str += ",file= " + file;
return str + ((mode == LOAD) ? ",load" : ",save");
}
boolean postsOldMouseEvents() {
return false;
}
}
|
Java
|
/*
* Copyright (c) 2000, 2007, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code 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
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package java.awt;
import sun.awt.AppContext;
import sun.awt.SunToolkit;
/** {@collect.stats}
* A wrapping tag for a nested AWTEvent which indicates that the event was
* sent from another AppContext. The destination AppContext should handle the
* event even if it is currently blocked waiting for a SequencedEvent or
* another SentEvent to be handled.
*
* @author David Mendenhall
*/
class SentEvent extends AWTEvent implements ActiveEvent {
/*
* serialVersionUID
*/
private static final long serialVersionUID = -383615247028828931L;
static final int ID =
java.awt.event.FocusEvent.FOCUS_LAST + 2;
boolean dispatched;
private AWTEvent nested;
private AppContext toNotify;
SentEvent() {
this(null);
}
SentEvent(AWTEvent nested) {
this(nested, null);
}
SentEvent(AWTEvent nested, AppContext toNotify) {
super((nested != null)
? nested.getSource()
: Toolkit.getDefaultToolkit(),
ID);
this.nested = nested;
this.toNotify = toNotify;
}
public void dispatch() {
try {
if (nested != null) {
Toolkit.getEventQueue().dispatchEvent(nested);
}
} finally {
dispatched = true;
if (toNotify != null) {
SunToolkit.postEvent(toNotify, new SentEvent());
}
synchronized (this) {
notifyAll();
}
}
}
final void dispose() {
dispatched = true;
if (toNotify != null) {
SunToolkit.postEvent(toNotify, new SentEvent());
}
synchronized (this) {
notifyAll();
}
}
}
|
Java
|
/*
* Copyright (c) 1995, 2007, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code 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
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package java.awt;
import java.awt.Component;
import java.awt.Image;
import java.awt.image.ImageObserver;
/** {@collect.stats}
* The <code>MediaTracker</code> class is a utility class to track
* the status of a number of media objects. Media objects could
* include audio clips as well as images, though currently only
* images are supported.
* <p>
* To use a media tracker, create an instance of
* <code>MediaTracker</code> and call its <code>addImage</code>
* method for each image to be tracked. In addition, each image can
* be assigned a unique identifier. This identifier controls the
* priority order in which the images are fetched. It can also be used
* to identify unique subsets of the images that can be waited on
* independently. Images with a lower ID are loaded in preference to
* those with a higher ID number.
*
* <p>
*
* Tracking an animated image
* might not always be useful
* due to the multi-part nature of animated image
* loading and painting,
* but it is supported.
* <code>MediaTracker</code> treats an animated image
* as completely loaded
* when the first frame is completely loaded.
* At that point, the <code>MediaTracker</code>
* signals any waiters
* that the image is completely loaded.
* If no <code>ImageObserver</code>s are observing the image
* when the first frame has finished loading,
* the image might flush itself
* to conserve resources
* (see {@link Image#flush()}).
*
* <p>
* Here is an example of using <code>MediaTracker</code>:
* <p>
* <hr><blockquote><pre>
* import java.applet.Applet;
* import java.awt.Color;
* import java.awt.Image;
* import java.awt.Graphics;
* import java.awt.MediaTracker;
*
* public class ImageBlaster extends Applet implements Runnable {
* MediaTracker tracker;
* Image bg;
* Image anim[] = new Image[5];
* int index;
* Thread animator;
*
* // Get the images for the background (id == 0)
* // and the animation frames (id == 1)
* // and add them to the MediaTracker
* public void init() {
* tracker = new MediaTracker(this);
* bg = getImage(getDocumentBase(),
* "images/background.gif");
* tracker.addImage(bg, 0);
* for (int i = 0; i < 5; i++) {
* anim[i] = getImage(getDocumentBase(),
* "images/anim"+i+".gif");
* tracker.addImage(anim[i], 1);
* }
* }
*
* // Start the animation thread.
* public void start() {
* animator = new Thread(this);
* animator.start();
* }
*
* // Stop the animation thread.
* public void stop() {
* animator = null;
* }
*
* // Run the animation thread.
* // First wait for the background image to fully load
* // and paint. Then wait for all of the animation
* // frames to finish loading. Finally, loop and
* // increment the animation frame index.
* public void run() {
* try {
* tracker.waitForID(0);
* tracker.waitForID(1);
* } catch (InterruptedException e) {
* return;
* }
* Thread me = Thread.currentThread();
* while (animator == me) {
* try {
* Thread.sleep(100);
* } catch (InterruptedException e) {
* break;
* }
* synchronized (this) {
* index++;
* if (index >= anim.length) {
* index = 0;
* }
* }
* repaint();
* }
* }
*
* // The background image fills the frame so we
* // don't need to clear the applet on repaints.
* // Just call the paint method.
* public void update(Graphics g) {
* paint(g);
* }
*
* // Paint a large red rectangle if there are any errors
* // loading the images. Otherwise always paint the
* // background so that it appears incrementally as it
* // is loading. Finally, only paint the current animation
* // frame if all of the frames (id == 1) are done loading,
* // so that we don't get partial animations.
* public void paint(Graphics g) {
* if ((tracker.statusAll(false) & MediaTracker.ERRORED) != 0) {
* g.setColor(Color.red);
* g.fillRect(0, 0, size().width, size().height);
* return;
* }
* g.drawImage(bg, 0, 0, this);
* if (tracker.statusID(1, false) == MediaTracker.COMPLETE) {
* g.drawImage(anim[index], 10, 10, this);
* }
* }
* }
* </pre></blockquote><hr>
*
* @author Jim Graham
* @since JDK1.0
*/
public class MediaTracker implements java.io.Serializable {
/** {@collect.stats}
* A given <code>Component</code> that will be
* tracked by a media tracker where the image will
* eventually be drawn.
*
* @serial
* @see #MediaTracker(Component)
*/
Component target;
/** {@collect.stats}
* The head of the list of <code>Images</code> that is being
* tracked by the <code>MediaTracker</code>.
*
* @serial
* @see #addImage(Image, int)
* @see #removeImage(Image)
*/
MediaEntry head;
/*
* JDK 1.1 serialVersionUID
*/
private static final long serialVersionUID = -483174189758638095L;
/** {@collect.stats}
* Creates a media tracker to track images for a given component.
* @param comp the component on which the images
* will eventually be drawn
*/
public MediaTracker(Component comp) {
target = comp;
}
/** {@collect.stats}
* Adds an image to the list of images being tracked by this media
* tracker. The image will eventually be rendered at its default
* (unscaled) size.
* @param image the image to be tracked
* @param id an identifier used to track this image
*/
public void addImage(Image image, int id) {
addImage(image, id, -1, -1);
}
/** {@collect.stats}
* Adds a scaled image to the list of images being tracked
* by this media tracker. The image will eventually be
* rendered at the indicated width and height.
*
* @param image the image to be tracked
* @param id an identifier that can be used to track this image
* @param w the width at which the image is rendered
* @param h the height at which the image is rendered
*/
public synchronized void addImage(Image image, int id, int w, int h) {
head = MediaEntry.insert(head,
new ImageMediaEntry(this, image, id, w, h));
}
/** {@collect.stats}
* Flag indicating that media is currently being loaded.
* @see java.awt.MediaTracker#statusAll
* @see java.awt.MediaTracker#statusID
*/
public static final int LOADING = 1;
/** {@collect.stats}
* Flag indicating that the downloading of media was aborted.
* @see java.awt.MediaTracker#statusAll
* @see java.awt.MediaTracker#statusID
*/
public static final int ABORTED = 2;
/** {@collect.stats}
* Flag indicating that the downloading of media encountered
* an error.
* @see java.awt.MediaTracker#statusAll
* @see java.awt.MediaTracker#statusID
*/
public static final int ERRORED = 4;
/** {@collect.stats}
* Flag indicating that the downloading of media was completed
* successfully.
* @see java.awt.MediaTracker#statusAll
* @see java.awt.MediaTracker#statusID
*/
public static final int COMPLETE = 8;
static final int DONE = (ABORTED | ERRORED | COMPLETE);
/** {@collect.stats}
* Checks to see if all images being tracked by this media tracker
* have finished loading.
* <p>
* This method does not start loading the images if they are not
* already loading.
* <p>
* If there is an error while loading or scaling an image, then that
* image is considered to have finished loading. Use the
* <code>isErrorAny</code> or <code>isErrorID</code> methods to
* check for errors.
* @return <code>true</code> if all images have finished loading,
* have been aborted, or have encountered
* an error; <code>false</code> otherwise
* @see java.awt.MediaTracker#checkAll(boolean)
* @see java.awt.MediaTracker#checkID
* @see java.awt.MediaTracker#isErrorAny
* @see java.awt.MediaTracker#isErrorID
*/
public boolean checkAll() {
return checkAll(false, true);
}
/** {@collect.stats}
* Checks to see if all images being tracked by this media tracker
* have finished loading.
* <p>
* If the value of the <code>load</code> flag is <code>true</code>,
* then this method starts loading any images that are not yet
* being loaded.
* <p>
* If there is an error while loading or scaling an image, that
* image is considered to have finished loading. Use the
* <code>isErrorAny</code> and <code>isErrorID</code> methods to
* check for errors.
* @param load if <code>true</code>, start loading any
* images that are not yet being loaded
* @return <code>true</code> if all images have finished loading,
* have been aborted, or have encountered
* an error; <code>false</code> otherwise
* @see java.awt.MediaTracker#checkID
* @see java.awt.MediaTracker#checkAll()
* @see java.awt.MediaTracker#isErrorAny()
* @see java.awt.MediaTracker#isErrorID(int)
*/
public boolean checkAll(boolean load) {
return checkAll(load, true);
}
private synchronized boolean checkAll(boolean load, boolean verify) {
MediaEntry cur = head;
boolean done = true;
while (cur != null) {
if ((cur.getStatus(load, verify) & DONE) == 0) {
done = false;
}
cur = cur.next;
}
return done;
}
/** {@collect.stats}
* Checks the error status of all of the images.
* @return <code>true</code> if any of the images tracked
* by this media tracker had an error during
* loading; <code>false</code> otherwise
* @see java.awt.MediaTracker#isErrorID
* @see java.awt.MediaTracker#getErrorsAny
*/
public synchronized boolean isErrorAny() {
MediaEntry cur = head;
while (cur != null) {
if ((cur.getStatus(false, true) & ERRORED) != 0) {
return true;
}
cur = cur.next;
}
return false;
}
/** {@collect.stats}
* Returns a list of all media that have encountered an error.
* @return an array of media objects tracked by this
* media tracker that have encountered
* an error, or <code>null</code> if
* there are none with errors
* @see java.awt.MediaTracker#isErrorAny
* @see java.awt.MediaTracker#getErrorsID
*/
public synchronized Object[] getErrorsAny() {
MediaEntry cur = head;
int numerrors = 0;
while (cur != null) {
if ((cur.getStatus(false, true) & ERRORED) != 0) {
numerrors++;
}
cur = cur.next;
}
if (numerrors == 0) {
return null;
}
Object errors[] = new Object[numerrors];
cur = head;
numerrors = 0;
while (cur != null) {
if ((cur.getStatus(false, false) & ERRORED) != 0) {
errors[numerrors++] = cur.getMedia();
}
cur = cur.next;
}
return errors;
}
/** {@collect.stats}
* Starts loading all images tracked by this media tracker. This
* method waits until all the images being tracked have finished
* loading.
* <p>
* If there is an error while loading or scaling an image, then that
* image is considered to have finished loading. Use the
* <code>isErrorAny</code> or <code>isErrorID</code> methods to
* check for errors.
* @see java.awt.MediaTracker#waitForID(int)
* @see java.awt.MediaTracker#waitForAll(long)
* @see java.awt.MediaTracker#isErrorAny
* @see java.awt.MediaTracker#isErrorID
* @exception InterruptedException if any thread has
* interrupted this thread
*/
public void waitForAll() throws InterruptedException {
waitForAll(0);
}
/** {@collect.stats}
* Starts loading all images tracked by this media tracker. This
* method waits until all the images being tracked have finished
* loading, or until the length of time specified in milliseconds
* by the <code>ms</code> argument has passed.
* <p>
* If there is an error while loading or scaling an image, then
* that image is considered to have finished loading. Use the
* <code>isErrorAny</code> or <code>isErrorID</code> methods to
* check for errors.
* @param ms the number of milliseconds to wait
* for the loading to complete
* @return <code>true</code> if all images were successfully
* loaded; <code>false</code> otherwise
* @see java.awt.MediaTracker#waitForID(int)
* @see java.awt.MediaTracker#waitForAll(long)
* @see java.awt.MediaTracker#isErrorAny
* @see java.awt.MediaTracker#isErrorID
* @exception InterruptedException if any thread has
* interrupted this thread.
*/
public synchronized boolean waitForAll(long ms)
throws InterruptedException
{
long end = System.currentTimeMillis() + ms;
boolean first = true;
while (true) {
int status = statusAll(first, first);
if ((status & LOADING) == 0) {
return (status == COMPLETE);
}
first = false;
long timeout;
if (ms == 0) {
timeout = 0;
} else {
timeout = end - System.currentTimeMillis();
if (timeout <= 0) {
return false;
}
}
wait(timeout);
}
}
/** {@collect.stats}
* Calculates and returns the bitwise inclusive <b>OR</b> of the
* status of all media that are tracked by this media tracker.
* <p>
* Possible flags defined by the
* <code>MediaTracker</code> class are <code>LOADING</code>,
* <code>ABORTED</code>, <code>ERRORED</code>, and
* <code>COMPLETE</code>. An image that hasn't started
* loading has zero as its status.
* <p>
* If the value of <code>load</code> is <code>true</code>, then
* this method starts loading any images that are not yet being loaded.
*
* @param load if <code>true</code>, start loading
* any images that are not yet being loaded
* @return the bitwise inclusive <b>OR</b> of the status of
* all of the media being tracked
* @see java.awt.MediaTracker#statusID(int, boolean)
* @see java.awt.MediaTracker#LOADING
* @see java.awt.MediaTracker#ABORTED
* @see java.awt.MediaTracker#ERRORED
* @see java.awt.MediaTracker#COMPLETE
*/
public int statusAll(boolean load) {
return statusAll(load, true);
}
private synchronized int statusAll(boolean load, boolean verify) {
MediaEntry cur = head;
int status = 0;
while (cur != null) {
status = status | cur.getStatus(load, verify);
cur = cur.next;
}
return status;
}
/** {@collect.stats}
* Checks to see if all images tracked by this media tracker that
* are tagged with the specified identifier have finished loading.
* <p>
* This method does not start loading the images if they are not
* already loading.
* <p>
* If there is an error while loading or scaling an image, then that
* image is considered to have finished loading. Use the
* <code>isErrorAny</code> or <code>isErrorID</code> methods to
* check for errors.
* @param id the identifier of the images to check
* @return <code>true</code> if all images have finished loading,
* have been aborted, or have encountered
* an error; <code>false</code> otherwise
* @see java.awt.MediaTracker#checkID(int, boolean)
* @see java.awt.MediaTracker#checkAll()
* @see java.awt.MediaTracker#isErrorAny()
* @see java.awt.MediaTracker#isErrorID(int)
*/
public boolean checkID(int id) {
return checkID(id, false, true);
}
/** {@collect.stats}
* Checks to see if all images tracked by this media tracker that
* are tagged with the specified identifier have finished loading.
* <p>
* If the value of the <code>load</code> flag is <code>true</code>,
* then this method starts loading any images that are not yet
* being loaded.
* <p>
* If there is an error while loading or scaling an image, then that
* image is considered to have finished loading. Use the
* <code>isErrorAny</code> or <code>isErrorID</code> methods to
* check for errors.
* @param id the identifier of the images to check
* @param load if <code>true</code>, start loading any
* images that are not yet being loaded
* @return <code>true</code> if all images have finished loading,
* have been aborted, or have encountered
* an error; <code>false</code> otherwise
* @see java.awt.MediaTracker#checkID(int, boolean)
* @see java.awt.MediaTracker#checkAll()
* @see java.awt.MediaTracker#isErrorAny()
* @see java.awt.MediaTracker#isErrorID(int)
*/
public boolean checkID(int id, boolean load) {
return checkID(id, load, true);
}
private synchronized boolean checkID(int id, boolean load, boolean verify)
{
MediaEntry cur = head;
boolean done = true;
while (cur != null) {
if (cur.getID() == id
&& (cur.getStatus(load, verify) & DONE) == 0)
{
done = false;
}
cur = cur.next;
}
return done;
}
/** {@collect.stats}
* Checks the error status of all of the images tracked by this
* media tracker with the specified identifier.
* @param id the identifier of the images to check
* @return <code>true</code> if any of the images with the
* specified identifier had an error during
* loading; <code>false</code> otherwise
* @see java.awt.MediaTracker#isErrorAny
* @see java.awt.MediaTracker#getErrorsID
*/
public synchronized boolean isErrorID(int id) {
MediaEntry cur = head;
while (cur != null) {
if (cur.getID() == id
&& (cur.getStatus(false, true) & ERRORED) != 0)
{
return true;
}
cur = cur.next;
}
return false;
}
/** {@collect.stats}
* Returns a list of media with the specified ID that
* have encountered an error.
* @param id the identifier of the images to check
* @return an array of media objects tracked by this media
* tracker with the specified identifier
* that have encountered an error, or
* <code>null</code> if there are none with errors
* @see java.awt.MediaTracker#isErrorID
* @see java.awt.MediaTracker#isErrorAny
* @see java.awt.MediaTracker#getErrorsAny
*/
public synchronized Object[] getErrorsID(int id) {
MediaEntry cur = head;
int numerrors = 0;
while (cur != null) {
if (cur.getID() == id
&& (cur.getStatus(false, true) & ERRORED) != 0)
{
numerrors++;
}
cur = cur.next;
}
if (numerrors == 0) {
return null;
}
Object errors[] = new Object[numerrors];
cur = head;
numerrors = 0;
while (cur != null) {
if (cur.getID() == id
&& (cur.getStatus(false, false) & ERRORED) != 0)
{
errors[numerrors++] = cur.getMedia();
}
cur = cur.next;
}
return errors;
}
/** {@collect.stats}
* Starts loading all images tracked by this media tracker with the
* specified identifier. This method waits until all the images with
* the specified identifier have finished loading.
* <p>
* If there is an error while loading or scaling an image, then that
* image is considered to have finished loading. Use the
* <code>isErrorAny</code> and <code>isErrorID</code> methods to
* check for errors.
* @param id the identifier of the images to check
* @see java.awt.MediaTracker#waitForAll
* @see java.awt.MediaTracker#isErrorAny()
* @see java.awt.MediaTracker#isErrorID(int)
* @exception InterruptedException if any thread has
* interrupted this thread.
*/
public void waitForID(int id) throws InterruptedException {
waitForID(id, 0);
}
/** {@collect.stats}
* Starts loading all images tracked by this media tracker with the
* specified identifier. This method waits until all the images with
* the specified identifier have finished loading, or until the
* length of time specified in milliseconds by the <code>ms</code>
* argument has passed.
* <p>
* If there is an error while loading or scaling an image, then that
* image is considered to have finished loading. Use the
* <code>statusID</code>, <code>isErrorID</code>, and
* <code>isErrorAny</code> methods to check for errors.
* @param id the identifier of the images to check
* @param ms the length of time, in milliseconds, to wait
* for the loading to complete
* @see java.awt.MediaTracker#waitForAll
* @see java.awt.MediaTracker#waitForID(int)
* @see java.awt.MediaTracker#statusID
* @see java.awt.MediaTracker#isErrorAny()
* @see java.awt.MediaTracker#isErrorID(int)
* @exception InterruptedException if any thread has
* interrupted this thread.
*/
public synchronized boolean waitForID(int id, long ms)
throws InterruptedException
{
long end = System.currentTimeMillis() + ms;
boolean first = true;
while (true) {
int status = statusID(id, first, first);
if ((status & LOADING) == 0) {
return (status == COMPLETE);
}
first = false;
long timeout;
if (ms == 0) {
timeout = 0;
} else {
timeout = end - System.currentTimeMillis();
if (timeout <= 0) {
return false;
}
}
wait(timeout);
}
}
/** {@collect.stats}
* Calculates and returns the bitwise inclusive <b>OR</b> of the
* status of all media with the specified identifier that are
* tracked by this media tracker.
* <p>
* Possible flags defined by the
* <code>MediaTracker</code> class are <code>LOADING</code>,
* <code>ABORTED</code>, <code>ERRORED</code>, and
* <code>COMPLETE</code>. An image that hasn't started
* loading has zero as its status.
* <p>
* If the value of <code>load</code> is <code>true</code>, then
* this method starts loading any images that are not yet being loaded.
* @param id the identifier of the images to check
* @param load if <code>true</code>, start loading
* any images that are not yet being loaded
* @return the bitwise inclusive <b>OR</b> of the status of
* all of the media with the specified
* identifier that are being tracked
* @see java.awt.MediaTracker#statusAll(boolean)
* @see java.awt.MediaTracker#LOADING
* @see java.awt.MediaTracker#ABORTED
* @see java.awt.MediaTracker#ERRORED
* @see java.awt.MediaTracker#COMPLETE
*/
public int statusID(int id, boolean load) {
return statusID(id, load, true);
}
private synchronized int statusID(int id, boolean load, boolean verify) {
MediaEntry cur = head;
int status = 0;
while (cur != null) {
if (cur.getID() == id) {
status = status | cur.getStatus(load, verify);
}
cur = cur.next;
}
return status;
}
/** {@collect.stats}
* Removes the specified image from this media tracker.
* All instances of the specified image are removed,
* regardless of scale or ID.
* @param image the image to be removed
* @see java.awt.MediaTracker#removeImage(java.awt.Image, int)
* @see java.awt.MediaTracker#removeImage(java.awt.Image, int, int, int)
* @since JDK1.1
*/
public synchronized void removeImage(Image image) {
MediaEntry cur = head;
MediaEntry prev = null;
while (cur != null) {
MediaEntry next = cur.next;
if (cur.getMedia() == image) {
if (prev == null) {
head = next;
} else {
prev.next = next;
}
cur.cancel();
} else {
prev = cur;
}
cur = next;
}
notifyAll(); // Notify in case remaining images are "done".
}
/** {@collect.stats}
* Removes the specified image from the specified tracking
* ID of this media tracker.
* All instances of <code>Image</code> being tracked
* under the specified ID are removed regardless of scale.
* @param image the image to be removed
* @param id the tracking ID frrom which to remove the image
* @see java.awt.MediaTracker#removeImage(java.awt.Image)
* @see java.awt.MediaTracker#removeImage(java.awt.Image, int, int, int)
* @since JDK1.1
*/
public synchronized void removeImage(Image image, int id) {
MediaEntry cur = head;
MediaEntry prev = null;
while (cur != null) {
MediaEntry next = cur.next;
if (cur.getID() == id && cur.getMedia() == image) {
if (prev == null) {
head = next;
} else {
prev.next = next;
}
cur.cancel();
} else {
prev = cur;
}
cur = next;
}
notifyAll(); // Notify in case remaining images are "done".
}
/** {@collect.stats}
* Removes the specified image with the specified
* width, height, and ID from this media tracker.
* Only the specified instance (with any duplicates) is removed.
* @param image the image to be removed
* @param id the tracking ID from which to remove the image
* @param width the width to remove (-1 for unscaled)
* @param height the height to remove (-1 for unscaled)
* @see java.awt.MediaTracker#removeImage(java.awt.Image)
* @see java.awt.MediaTracker#removeImage(java.awt.Image, int)
* @since JDK1.1
*/
public synchronized void removeImage(Image image, int id,
int width, int height) {
MediaEntry cur = head;
MediaEntry prev = null;
while (cur != null) {
MediaEntry next = cur.next;
if (cur.getID() == id && cur instanceof ImageMediaEntry
&& ((ImageMediaEntry) cur).matches(image, width, height))
{
if (prev == null) {
head = next;
} else {
prev.next = next;
}
cur.cancel();
} else {
prev = cur;
}
cur = next;
}
notifyAll(); // Notify in case remaining images are "done".
}
synchronized void setDone() {
notifyAll();
}
}
abstract class MediaEntry {
MediaTracker tracker;
int ID;
MediaEntry next;
int status;
boolean cancelled;
MediaEntry(MediaTracker mt, int id) {
tracker = mt;
ID = id;
}
abstract Object getMedia();
static MediaEntry insert(MediaEntry head, MediaEntry me) {
MediaEntry cur = head;
MediaEntry prev = null;
while (cur != null) {
if (cur.ID > me.ID) {
break;
}
prev = cur;
cur = cur.next;
}
me.next = cur;
if (prev == null) {
head = me;
} else {
prev.next = me;
}
return head;
}
int getID() {
return ID;
}
abstract void startLoad();
void cancel() {
cancelled = true;
}
static final int LOADING = MediaTracker.LOADING;
static final int ABORTED = MediaTracker.ABORTED;
static final int ERRORED = MediaTracker.ERRORED;
static final int COMPLETE = MediaTracker.COMPLETE;
static final int LOADSTARTED = (LOADING | ERRORED | COMPLETE);
static final int DONE = (ABORTED | ERRORED | COMPLETE);
synchronized int getStatus(boolean doLoad, boolean doVerify) {
if (doLoad && ((status & LOADSTARTED) == 0)) {
status = (status & ~ABORTED) | LOADING;
startLoad();
}
return status;
}
void setStatus(int flag) {
synchronized (this) {
status = flag;
}
tracker.setDone();
}
}
class ImageMediaEntry extends MediaEntry implements ImageObserver,
java.io.Serializable {
Image image;
int width;
int height;
/*
* JDK 1.1 serialVersionUID
*/
private static final long serialVersionUID = 4739377000350280650L;
ImageMediaEntry(MediaTracker mt, Image img, int c, int w, int h) {
super(mt, c);
image = img;
width = w;
height = h;
}
boolean matches(Image img, int w, int h) {
return (image == img && width == w && height == h);
}
Object getMedia() {
return image;
}
synchronized int getStatus(boolean doLoad, boolean doVerify) {
if (doVerify) {
int flags = tracker.target.checkImage(image, width, height, null);
int s = parseflags(flags);
if (s == 0) {
if ((status & (ERRORED | COMPLETE)) != 0) {
setStatus(ABORTED);
}
} else if (s != status) {
setStatus(s);
}
}
return super.getStatus(doLoad, doVerify);
}
void startLoad() {
if (tracker.target.prepareImage(image, width, height, this)) {
setStatus(COMPLETE);
}
}
int parseflags(int infoflags) {
if ((infoflags & ERROR) != 0) {
return ERRORED;
} else if ((infoflags & ABORT) != 0) {
return ABORTED;
} else if ((infoflags & (ALLBITS | FRAMEBITS)) != 0) {
return COMPLETE;
}
return 0;
}
public boolean imageUpdate(Image img, int infoflags,
int x, int y, int w, int h) {
if (cancelled) {
return false;
}
int s = parseflags(infoflags);
if (s != 0 && s != status) {
setStatus(s);
}
return ((status & LOADING) != 0);
}
}
|
Java
|
/*
* Copyright (c) 1995, 2006, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code 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
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package java.awt;
import java.awt.event.InputEvent;
import java.awt.event.KeyEvent;
import java.awt.peer.TextAreaPeer;
import java.io.ObjectOutputStream;
import java.io.ObjectInputStream;
import java.io.IOException;
import java.util.HashSet;
import java.util.Set;
import javax.accessibility.*;
/** {@collect.stats}
* A <code>TextArea</code> object is a multi-line region
* that displays text. It can be set to allow editing or
* to be read-only.
* <p>
* The following image shows the appearance of a text area:
* <p>
* <img src="doc-files/TextArea-1.gif" alt="A TextArea showing the word 'Hello!'"
* ALIGN=center HSPACE=10 VSPACE=7>
* <p>
* This text area could be created by the following line of code:
* <p>
* <hr><blockquote><pre>
* new TextArea("Hello", 5, 40);
* </pre></blockquote><hr>
* <p>
* @author Sami Shaio
* @since JDK1.0
*/
public class TextArea extends TextComponent {
/** {@collect.stats}
* The number of rows in the <code>TextArea</code>.
* This parameter will determine the text area's height.
* Guaranteed to be non-negative.
*
* @serial
* @see #getRows()
* @see #setRows(int)
*/
int rows;
/** {@collect.stats}
* The number of columns in the <code>TextArea</code>.
* A column is an approximate average character
* width that is platform-dependent.
* This parameter will determine the text area's width.
* Guaranteed to be non-negative.
*
* @serial
* @see #setColumns(int)
* @see #getColumns()
*/
int columns;
private static final String base = "text";
private static int nameCounter = 0;
/** {@collect.stats}
* Create and display both vertical and horizontal scrollbars.
* @since JDK1.1
*/
public static final int SCROLLBARS_BOTH = 0;
/** {@collect.stats}
* Create and display vertical scrollbar only.
* @since JDK1.1
*/
public static final int SCROLLBARS_VERTICAL_ONLY = 1;
/** {@collect.stats}
* Create and display horizontal scrollbar only.
* @since JDK1.1
*/
public static final int SCROLLBARS_HORIZONTAL_ONLY = 2;
/** {@collect.stats}
* Do not create or display any scrollbars for the text area.
* @since JDK1.1
*/
public static final int SCROLLBARS_NONE = 3;
/** {@collect.stats}
* Determines which scrollbars are created for the
* text area. It can be one of four values :
* <code>SCROLLBARS_BOTH</code> = both scrollbars.<BR>
* <code>SCROLLBARS_HORIZONTAL_ONLY</code> = Horizontal bar only.<BR>
* <code>SCROLLBARS_VERTICAL_ONLY</code> = Vertical bar only.<BR>
* <code>SCROLLBARS_NONE</code> = No scrollbars.<BR>
*
* @serial
* @see #getScrollbarVisibility()
*/
private int scrollbarVisibility;
/** {@collect.stats}
* Cache the Sets of forward and backward traversal keys so we need not
* look them up each time.
*/
private static Set forwardTraversalKeys, backwardTraversalKeys;
/*
* JDK 1.1 serialVersionUID
*/
private static final long serialVersionUID = 3692302836626095722L;
/** {@collect.stats}
* Initialize JNI field and method ids
*/
private static native void initIDs();
static {
/* ensure that the necessary native libraries are loaded */
Toolkit.loadLibraries();
if (!GraphicsEnvironment.isHeadless()) {
initIDs();
}
forwardTraversalKeys = KeyboardFocusManager.initFocusTraversalKeysSet(
"ctrl TAB",
new HashSet());
backwardTraversalKeys = KeyboardFocusManager.initFocusTraversalKeysSet(
"ctrl shift TAB",
new HashSet());
}
/** {@collect.stats}
* Constructs a new text area with the empty string as text.
* This text area is created with scrollbar visibility equal to
* {@link #SCROLLBARS_BOTH}, so both vertical and horizontal
* scrollbars will be visible for this text area.
* @exception HeadlessException if
* <code>GraphicsEnvironment.isHeadless</code> returns true
* @see java.awt.GraphicsEnvironment#isHeadless()
*/
public TextArea() throws HeadlessException {
this("", 0, 0, SCROLLBARS_BOTH);
}
/** {@collect.stats}
* Constructs a new text area with the specified text.
* This text area is created with scrollbar visibility equal to
* {@link #SCROLLBARS_BOTH}, so both vertical and horizontal
* scrollbars will be visible for this text area.
* @param text the text to be displayed; if
* <code>text</code> is <code>null</code>, the empty
* string <code>""</code> will be displayed
* @exception HeadlessException if
* <code>GraphicsEnvironment.isHeadless</code> returns true
* @see java.awt.GraphicsEnvironment#isHeadless()
*/
public TextArea(String text) throws HeadlessException {
this(text, 0, 0, SCROLLBARS_BOTH);
}
/** {@collect.stats}
* Constructs a new text area with the specified number of
* rows and columns and the empty string as text.
* A column is an approximate average character
* width that is platform-dependent. The text area is created with
* scrollbar visibility equal to {@link #SCROLLBARS_BOTH}, so both
* vertical and horizontal scrollbars will be visible for this
* text area.
* @param rows the number of rows
* @param columns the number of columns
* @exception HeadlessException if
* <code>GraphicsEnvironment.isHeadless</code> returns true
* @see java.awt.GraphicsEnvironment#isHeadless()
*/
public TextArea(int rows, int columns) throws HeadlessException {
this("", rows, columns, SCROLLBARS_BOTH);
}
/** {@collect.stats}
* Constructs a new text area with the specified text,
* and with the specified number of rows and columns.
* A column is an approximate average character
* width that is platform-dependent. The text area is created with
* scrollbar visibility equal to {@link #SCROLLBARS_BOTH}, so both
* vertical and horizontal scrollbars will be visible for this
* text area.
* @param text the text to be displayed; if
* <code>text</code> is <code>null</code>, the empty
* string <code>""</code> will be displayed
* @param rows the number of rows
* @param columns the number of columns
* @exception HeadlessException if
* <code>GraphicsEnvironment.isHeadless</code> returns true
* @see java.awt.GraphicsEnvironment#isHeadless()
*/
public TextArea(String text, int rows, int columns)
throws HeadlessException {
this(text, rows, columns, SCROLLBARS_BOTH);
}
/** {@collect.stats}
* Constructs a new text area with the specified text,
* and with the rows, columns, and scroll bar visibility
* as specified. All <code>TextArea</code> constructors defer to
* this one.
* <p>
* The <code>TextArea</code> class defines several constants
* that can be supplied as values for the
* <code>scrollbars</code> argument:
* <ul>
* <li><code>SCROLLBARS_BOTH</code>,
* <li><code>SCROLLBARS_VERTICAL_ONLY</code>,
* <li><code>SCROLLBARS_HORIZONTAL_ONLY</code>,
* <li><code>SCROLLBARS_NONE</code>.
* </ul>
* Any other value for the
* <code>scrollbars</code> argument is invalid and will result in
* this text area being created with scrollbar visibility equal to
* the default value of {@link #SCROLLBARS_BOTH}.
* @param text the text to be displayed; if
* <code>text</code> is <code>null</code>, the empty
* string <code>""</code> will be displayed
* @param rows the number of rows; if
* <code>rows</code> is less than <code>0</code>,
* <code>rows</code> is set to <code>0</code>
* @param columns the number of columns; if
* <code>columns</code> is less than <code>0</code>,
* <code>columns</code> is set to <code>0</code>
* @param scrollbars a constant that determines what
* scrollbars are created to view the text area
* @since JDK1.1
* @exception HeadlessException if
* <code>GraphicsEnvironment.isHeadless</code> returns true
* @see java.awt.GraphicsEnvironment#isHeadless()
*/
public TextArea(String text, int rows, int columns, int scrollbars)
throws HeadlessException {
super(text);
this.rows = (rows >= 0) ? rows : 0;
this.columns = (columns >= 0) ? columns : 0;
if (scrollbars >= SCROLLBARS_BOTH && scrollbars <= SCROLLBARS_NONE) {
this.scrollbarVisibility = scrollbars;
} else {
this.scrollbarVisibility = SCROLLBARS_BOTH;
}
setFocusTraversalKeys(KeyboardFocusManager.FORWARD_TRAVERSAL_KEYS,
forwardTraversalKeys);
setFocusTraversalKeys(KeyboardFocusManager.BACKWARD_TRAVERSAL_KEYS,
backwardTraversalKeys);
}
/** {@collect.stats}
* Construct a name for this component. Called by <code>getName</code>
* when the name is <code>null</code>.
*/
String constructComponentName() {
synchronized (TextArea.class) {
return base + nameCounter++;
}
}
/** {@collect.stats}
* Creates the <code>TextArea</code>'s peer. The peer allows us to modify
* the appearance of the <code>TextArea</code> without changing any of its
* functionality.
*/
public void addNotify() {
synchronized (getTreeLock()) {
if (peer == null)
peer = getToolkit().createTextArea(this);
super.addNotify();
}
}
/** {@collect.stats}
* Inserts the specified text at the specified position
* in this text area.
* <p>Note that passing <code>null</code> or inconsistent
* parameters is invalid and will result in unspecified
* behavior.
*
* @param str the non-<code>null</code> text to insert
* @param pos the position at which to insert
* @see java.awt.TextComponent#setText
* @see java.awt.TextArea#replaceRange
* @see java.awt.TextArea#append
* @since JDK1.1
*/
public void insert(String str, int pos) {
insertText(str, pos);
}
/** {@collect.stats}
* @deprecated As of JDK version 1.1,
* replaced by <code>insert(String, int)</code>.
*/
@Deprecated
public synchronized void insertText(String str, int pos) {
TextAreaPeer peer = (TextAreaPeer)this.peer;
if (peer != null) {
peer.insertText(str, pos);
} else {
text = text.substring(0, pos) + str + text.substring(pos);
}
}
/** {@collect.stats}
* Appends the given text to the text area's current text.
* <p>Note that passing <code>null</code> or inconsistent
* parameters is invalid and will result in unspecified
* behavior.
*
* @param str the non-<code>null</code> text to append
* @see java.awt.TextArea#insert
* @since JDK1.1
*/
public void append(String str) {
appendText(str);
}
/** {@collect.stats}
* @deprecated As of JDK version 1.1,
* replaced by <code>append(String)</code>.
*/
@Deprecated
public synchronized void appendText(String str) {
if (peer != null) {
insertText(str, getText().length());
} else {
text = text + str;
}
}
/** {@collect.stats}
* Replaces text between the indicated start and end positions
* with the specified replacement text. The text at the end
* position will not be replaced. The text at the start
* position will be replaced (unless the start position is the
* same as the end position).
* The text position is zero-based. The inserted substring may be
* of a different length than the text it replaces.
* <p>Note that passing <code>null</code> or inconsistent
* parameters is invalid and will result in unspecified
* behavior.
*
* @param str the non-<code>null</code> text to use as
* the replacement
* @param start the start position
* @param end the end position
* @see java.awt.TextArea#insert
* @since JDK1.1
*/
public void replaceRange(String str, int start, int end) {
replaceText(str, start, end);
}
/** {@collect.stats}
* @deprecated As of JDK version 1.1,
* replaced by <code>replaceRange(String, int, int)</code>.
*/
@Deprecated
public synchronized void replaceText(String str, int start, int end) {
TextAreaPeer peer = (TextAreaPeer)this.peer;
if (peer != null) {
peer.replaceText(str, start, end);
} else {
text = text.substring(0, start) + str + text.substring(end);
}
}
/** {@collect.stats}
* Returns the number of rows in the text area.
* @return the number of rows in the text area
* @see #setRows(int)
* @see #getColumns()
* @since JDK1
*/
public int getRows() {
return rows;
}
/** {@collect.stats}
* Sets the number of rows for this text area.
* @param rows the number of rows
* @see #getRows()
* @see #setColumns(int)
* @exception IllegalArgumentException if the value
* supplied for <code>rows</code>
* is less than <code>0</code>
* @since JDK1.1
*/
public void setRows(int rows) {
int oldVal = this.rows;
if (rows < 0) {
throw new IllegalArgumentException("rows less than zero.");
}
if (rows != oldVal) {
this.rows = rows;
invalidate();
}
}
/** {@collect.stats}
* Returns the number of columns in this text area.
* @return the number of columns in the text area
* @see #setColumns(int)
* @see #getRows()
*/
public int getColumns() {
return columns;
}
/** {@collect.stats}
* Sets the number of columns for this text area.
* @param columns the number of columns
* @see #getColumns()
* @see #setRows(int)
* @exception IllegalArgumentException if the value
* supplied for <code>columns</code>
* is less than <code>0</code>
* @since JDK1.1
*/
public void setColumns(int columns) {
int oldVal = this.columns;
if (columns < 0) {
throw new IllegalArgumentException("columns less than zero.");
}
if (columns != oldVal) {
this.columns = columns;
invalidate();
}
}
/** {@collect.stats}
* Returns an enumerated value that indicates which scroll bars
* the text area uses.
* <p>
* The <code>TextArea</code> class defines four integer constants
* that are used to specify which scroll bars are available.
* <code>TextArea</code> has one constructor that gives the
* application discretion over scroll bars.
*
* @return an integer that indicates which scroll bars are used
* @see java.awt.TextArea#SCROLLBARS_BOTH
* @see java.awt.TextArea#SCROLLBARS_VERTICAL_ONLY
* @see java.awt.TextArea#SCROLLBARS_HORIZONTAL_ONLY
* @see java.awt.TextArea#SCROLLBARS_NONE
* @see java.awt.TextArea#TextArea(java.lang.String, int, int, int)
* @since JDK1.1
*/
public int getScrollbarVisibility() {
return scrollbarVisibility;
}
/** {@collect.stats}
* Determines the preferred size of a text area with the specified
* number of rows and columns.
* @param rows the number of rows
* @param columns the number of columns
* @return the preferred dimensions required to display
* the text area with the specified
* number of rows and columns
* @see java.awt.Component#getPreferredSize
* @since JDK1.1
*/
public Dimension getPreferredSize(int rows, int columns) {
return preferredSize(rows, columns);
}
/** {@collect.stats}
* @deprecated As of JDK version 1.1,
* replaced by <code>getPreferredSize(int, int)</code>.
*/
@Deprecated
public Dimension preferredSize(int rows, int columns) {
synchronized (getTreeLock()) {
TextAreaPeer peer = (TextAreaPeer)this.peer;
return (peer != null) ?
peer.preferredSize(rows, columns) :
super.preferredSize();
}
}
/** {@collect.stats}
* Determines the preferred size of this text area.
* @return the preferred dimensions needed for this text area
* @see java.awt.Component#getPreferredSize
* @since JDK1.1
*/
public Dimension getPreferredSize() {
return preferredSize();
}
/** {@collect.stats}
* @deprecated As of JDK version 1.1,
* replaced by <code>getPreferredSize()</code>.
*/
@Deprecated
public Dimension preferredSize() {
synchronized (getTreeLock()) {
return ((rows > 0) && (columns > 0)) ?
preferredSize(rows, columns) :
super.preferredSize();
}
}
/** {@collect.stats}
* Determines the minimum size of a text area with the specified
* number of rows and columns.
* @param rows the number of rows
* @param columns the number of columns
* @return the minimum dimensions required to display
* the text area with the specified
* number of rows and columns
* @see java.awt.Component#getMinimumSize
* @since JDK1.1
*/
public Dimension getMinimumSize(int rows, int columns) {
return minimumSize(rows, columns);
}
/** {@collect.stats}
* @deprecated As of JDK version 1.1,
* replaced by <code>getMinimumSize(int, int)</code>.
*/
@Deprecated
public Dimension minimumSize(int rows, int columns) {
synchronized (getTreeLock()) {
TextAreaPeer peer = (TextAreaPeer)this.peer;
return (peer != null) ?
peer.minimumSize(rows, columns) :
super.minimumSize();
}
}
/** {@collect.stats}
* Determines the minimum size of this text area.
* @return the preferred dimensions needed for this text area
* @see java.awt.Component#getPreferredSize
* @since JDK1.1
*/
public Dimension getMinimumSize() {
return minimumSize();
}
/** {@collect.stats}
* @deprecated As of JDK version 1.1,
* replaced by <code>getMinimumSize()</code>.
*/
@Deprecated
public Dimension minimumSize() {
synchronized (getTreeLock()) {
return ((rows > 0) && (columns > 0)) ?
minimumSize(rows, columns) :
super.minimumSize();
}
}
/** {@collect.stats}
* Returns a string representing the state of this <code>TextArea</code>.
* This method is intended to be used only for debugging purposes, and the
* content and format of the returned string may vary between
* implementations. The returned string may be empty but may not be
* <code>null</code>.
*
* @return the parameter string of this text area
*/
protected String paramString() {
String sbVisStr;
switch (scrollbarVisibility) {
case SCROLLBARS_BOTH:
sbVisStr = "both";
break;
case SCROLLBARS_VERTICAL_ONLY:
sbVisStr = "vertical-only";
break;
case SCROLLBARS_HORIZONTAL_ONLY:
sbVisStr = "horizontal-only";
break;
case SCROLLBARS_NONE:
sbVisStr = "none";
break;
default:
sbVisStr = "invalid display policy";
}
return super.paramString() + ",rows=" + rows +
",columns=" + columns +
",scrollbarVisibility=" + sbVisStr;
}
/*
* Serialization support.
*/
/** {@collect.stats}
* The textArea Serialized Data Version.
*
* @serial
*/
private int textAreaSerializedDataVersion = 2;
/** {@collect.stats}
* Read the ObjectInputStream.
* @exception HeadlessException if
* <code>GraphicsEnvironment.isHeadless()</code> returns
* <code>true</code>
* @see java.awt.GraphicsEnvironment#isHeadless
*/
private void readObject(ObjectInputStream s)
throws ClassNotFoundException, IOException, HeadlessException
{
// HeadlessException will be thrown by TextComponent's readObject
s.defaultReadObject();
// Make sure the state we just read in for columns, rows,
// and scrollbarVisibility has legal values
if (columns < 0) {
columns = 0;
}
if (rows < 0) {
rows = 0;
}
if ((scrollbarVisibility < SCROLLBARS_BOTH) ||
(scrollbarVisibility > SCROLLBARS_NONE)) {
this.scrollbarVisibility = SCROLLBARS_BOTH;
}
if (textAreaSerializedDataVersion < 2) {
setFocusTraversalKeys(KeyboardFocusManager.FORWARD_TRAVERSAL_KEYS,
forwardTraversalKeys);
setFocusTraversalKeys(KeyboardFocusManager.BACKWARD_TRAVERSAL_KEYS,
backwardTraversalKeys);
}
}
/////////////////
// Accessibility support
////////////////
/** {@collect.stats}
* Returns the <code>AccessibleContext</code> associated with
* this <code>TextArea</code>. For text areas, the
* <code>AccessibleContext</code> takes the form of an
* <code>AccessibleAWTTextArea</code>.
* A new <code>AccessibleAWTTextArea</code> instance is created if necessary.
*
* @return an <code>AccessibleAWTTextArea</code> that serves as the
* <code>AccessibleContext</code> of this <code>TextArea</code>
* @since 1.3
*/
public AccessibleContext getAccessibleContext() {
if (accessibleContext == null) {
accessibleContext = new AccessibleAWTTextArea();
}
return accessibleContext;
}
/** {@collect.stats}
* This class implements accessibility support for the
* <code>TextArea</code> class. It provides an implementation of the
* Java Accessibility API appropriate to text area user-interface elements.
* @since 1.3
*/
protected class AccessibleAWTTextArea extends AccessibleAWTTextComponent
{
/*
* JDK 1.3 serialVersionUID
*/
private static final long serialVersionUID = 3472827823632144419L;
/** {@collect.stats}
* Gets the state set of this object.
*
* @return an instance of AccessibleStateSet describing the states
* of the object
* @see AccessibleStateSet
*/
public AccessibleStateSet getAccessibleStateSet() {
AccessibleStateSet states = super.getAccessibleStateSet();
states.add(AccessibleState.MULTI_LINE);
return states;
}
}
}
|
Java
|
/*
* Copyright (c) 1997, 2007, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code 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
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package java.awt;
import java.awt.geom.Rectangle2D;
import java.awt.geom.AffineTransform;
import java.awt.image.BufferedImage;
import java.awt.image.ColorModel;
/** {@collect.stats}
* The <code>TexturePaint</code> class provides a way to fill a
* {@link Shape} with a texture that is specified as
* a {@link BufferedImage}. The size of the <code>BufferedImage</code>
* object should be small because the <code>BufferedImage</code> data
* is copied by the <code>TexturePaint</code> object.
* At construction time, the texture is anchored to the upper
* left corner of a {@link Rectangle2D} that is
* specified in user space. Texture is computed for
* locations in the device space by conceptually replicating the
* specified <code>Rectangle2D</code> infinitely in all directions
* in user space and mapping the <code>BufferedImage</code> to each
* replicated <code>Rectangle2D</code>.
* @see Paint
* @see Graphics2D#setPaint
*/
public class TexturePaint implements Paint {
BufferedImage bufImg;
double tx;
double ty;
double sx;
double sy;
/** {@collect.stats}
* Constructs a <code>TexturePaint</code> object.
* @param txtr the <code>BufferedImage</code> object with the texture
* used for painting
* @param anchor the <code>Rectangle2D</code> in user space used to
* anchor and replicate the texture
*/
public TexturePaint(BufferedImage txtr,
Rectangle2D anchor) {
this.bufImg = txtr;
this.tx = anchor.getX();
this.ty = anchor.getY();
this.sx = anchor.getWidth() / bufImg.getWidth();
this.sy = anchor.getHeight() / bufImg.getHeight();
}
/** {@collect.stats}
* Returns the <code>BufferedImage</code> texture used to
* fill the shapes.
* @return a <code>BufferedImage</code>.
*/
public BufferedImage getImage() {
return bufImg;
}
/** {@collect.stats}
* Returns a copy of the anchor rectangle which positions and
* sizes the textured image.
* @return the <code>Rectangle2D</code> used to anchor and
* size this <code>TexturePaint</code>.
*/
public Rectangle2D getAnchorRect() {
return new Rectangle2D.Double(tx, ty,
sx * bufImg.getWidth(),
sy * bufImg.getHeight());
}
/** {@collect.stats}
* Creates and returns a {@link PaintContext} used to
* generate a tiled image pattern.
* See the {@link Paint#createContext specification} of the
* method in the {@link Paint} interface for information
* on null parameter handling.
*
* @param cm the preferred {@link ColorModel} which represents the most convenient
* format for the caller to receive the pixel data, or {@code null}
* if there is no preference.
* @param deviceBounds the device space bounding box
* of the graphics primitive being rendered.
* @param userBounds the user space bounding box
* of the graphics primitive being rendered.
* @param xform the {@link AffineTransform} from user
* space into device space.
* @param hints the set of hints that the context object can use to
* choose between rendering alternatives.
* @return the {@code PaintContext} for
* generating color patterns.
* @see Paint
* @see PaintContext
* @see ColorModel
* @see Rectangle
* @see Rectangle2D
* @see AffineTransform
* @see RenderingHints
*/
public PaintContext createContext(ColorModel cm,
Rectangle deviceBounds,
Rectangle2D userBounds,
AffineTransform xform,
RenderingHints hints) {
if (xform == null) {
xform = new AffineTransform();
} else {
xform = (AffineTransform) xform.clone();
}
xform.translate(tx, ty);
xform.scale(sx, sy);
return TexturePaintContext.getContext(bufImg, xform, hints,
deviceBounds);
}
/** {@collect.stats}
* Returns the transparency mode for this <code>TexturePaint</code>.
* @return the transparency mode for this <code>TexturePaint</code>
* as an integer value.
* @see Transparency
*/
public int getTransparency() {
return (bufImg.getColorModel()).getTransparency();
}
}
|
Java
|
/*
* Copyright (c) 1995, 2006, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code 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
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package java.awt;
import java.awt.peer.LabelPeer;
import java.io.IOException;
import java.io.ObjectInputStream;
import javax.accessibility.*;
/** {@collect.stats}
* A <code>Label</code> object is a component for placing text in a
* container. A label displays a single line of read-only text.
* The text can be changed by the application, but a user cannot edit it
* directly.
* <p>
* For example, the code . . .
* <p>
* <hr><blockquote><pre>
* setLayout(new FlowLayout(FlowLayout.CENTER, 10, 10));
* add(new Label("Hi There!"));
* add(new Label("Another Label"));
* </pre></blockquote><hr>
* <p>
* produces the following labels:
* <p>
* <img src="doc-files/Label-1.gif" alt="Two labels: 'Hi There!' and 'Another label'"
* ALIGN=center HSPACE=10 VSPACE=7>
*
* @author Sami Shaio
* @since JDK1.0
*/
public class Label extends Component implements Accessible {
static {
/* ensure that the necessary native libraries are loaded */
Toolkit.loadLibraries();
if (!GraphicsEnvironment.isHeadless()) {
initIDs();
}
}
/** {@collect.stats}
* Indicates that the label should be left justified.
*/
public static final int LEFT = 0;
/** {@collect.stats}
* Indicates that the label should be centered.
*/
public static final int CENTER = 1;
/** {@collect.stats}
* Indicates that the label should be right justified.
* @since JDK1.0t.
*/
public static final int RIGHT = 2;
/** {@collect.stats}
* The text of this label.
* This text can be modified by the program
* but never by the user.
*
* @serial
* @see #getText()
* @see #setText(String)
*/
String text;
/** {@collect.stats}
* The label's alignment. The default alignment is set
* to be left justified.
*
* @serial
* @see #getAlignment()
* @see #setAlignment(int)
*/
int alignment = LEFT;
private static final String base = "label";
private static int nameCounter = 0;
/*
* JDK 1.1 serialVersionUID
*/
private static final long serialVersionUID = 3094126758329070636L;
/** {@collect.stats}
* Constructs an empty label.
* The text of the label is the empty string <code>""</code>.
* @exception HeadlessException if GraphicsEnvironment.isHeadless()
* returns true.
* @see java.awt.GraphicsEnvironment#isHeadless
*/
public Label() throws HeadlessException {
this("", LEFT);
}
/** {@collect.stats}
* Constructs a new label with the specified string of text,
* left justified.
* @param text the string that the label presents.
* A <code>null</code> value
* will be accepted without causing a NullPointerException
* to be thrown.
* @exception HeadlessException if GraphicsEnvironment.isHeadless()
* returns true.
* @see java.awt.GraphicsEnvironment#isHeadless
*/
public Label(String text) throws HeadlessException {
this(text, LEFT);
}
/** {@collect.stats}
* Constructs a new label that presents the specified string of
* text with the specified alignment.
* Possible values for <code>alignment</code> are <code>Label.LEFT</code>,
* <code>Label.RIGHT</code>, and <code>Label.CENTER</code>.
* @param text the string that the label presents.
* A <code>null</code> value
* will be accepted without causing a NullPointerException
* to be thrown.
* @param alignment the alignment value.
* @exception HeadlessException if GraphicsEnvironment.isHeadless()
* returns true.
* @see java.awt.GraphicsEnvironment#isHeadless
*/
public Label(String text, int alignment) throws HeadlessException {
GraphicsEnvironment.checkHeadless();
this.text = text;
setAlignment(alignment);
}
/** {@collect.stats}
* Read a label from an object input stream.
* @exception HeadlessException if
* <code>GraphicsEnvironment.isHeadless()</code> returns
* <code>true</code>
* @serial
* @since 1.4
* @see java.awt.GraphicsEnvironment#isHeadless
*/
private void readObject(ObjectInputStream s)
throws ClassNotFoundException, IOException, HeadlessException {
GraphicsEnvironment.checkHeadless();
s.defaultReadObject();
}
/** {@collect.stats}
* Construct a name for this component. Called by getName() when the
* name is <code>null</code>.
*/
String constructComponentName() {
synchronized (Label.class) {
return base + nameCounter++;
}
}
/** {@collect.stats}
* Creates the peer for this label. The peer allows us to
* modify the appearance of the label without changing its
* functionality.
*/
public void addNotify() {
synchronized (getTreeLock()) {
if (peer == null)
peer = getToolkit().createLabel(this);
super.addNotify();
}
}
/** {@collect.stats}
* Gets the current alignment of this label. Possible values are
* <code>Label.LEFT</code>, <code>Label.RIGHT</code>, and
* <code>Label.CENTER</code>.
* @see java.awt.Label#setAlignment
*/
public int getAlignment() {
return alignment;
}
/** {@collect.stats}
* Sets the alignment for this label to the specified alignment.
* Possible values are <code>Label.LEFT</code>,
* <code>Label.RIGHT</code>, and <code>Label.CENTER</code>.
* @param alignment the alignment to be set.
* @exception IllegalArgumentException if an improper value for
* <code>alignment</code> is given.
* @see java.awt.Label#getAlignment
*/
public synchronized void setAlignment(int alignment) {
switch (alignment) {
case LEFT:
case CENTER:
case RIGHT:
this.alignment = alignment;
LabelPeer peer = (LabelPeer)this.peer;
if (peer != null) {
peer.setAlignment(alignment);
}
return;
}
throw new IllegalArgumentException("improper alignment: " + alignment);
}
/** {@collect.stats}
* Gets the text of this label.
* @return the text of this label, or <code>null</code> if
* the text has been set to <code>null</code>.
* @see java.awt.Label#setText
*/
public String getText() {
return text;
}
/** {@collect.stats}
* Sets the text for this label to the specified text.
* @param text the text that this label displays. If
* <code>text</code> is <code>null</code>, it is
* treated for display purposes like an empty
* string <code>""</code>.
* @see java.awt.Label#getText
*/
public void setText(String text) {
boolean testvalid = false;
synchronized (this) {
if (text != this.text && (this.text == null ||
!this.text.equals(text))) {
this.text = text;
LabelPeer peer = (LabelPeer)this.peer;
if (peer != null) {
peer.setText(text);
}
testvalid = true;
}
}
// This could change the preferred size of the Component.
if (testvalid && valid) {
invalidate();
}
}
/** {@collect.stats}
* Returns a string representing the state of this <code>Label</code>.
* This method is intended to be used only for debugging purposes, and the
* content and format of the returned string may vary between
* implementations. The returned string may be empty but may not be
* <code>null</code>.
*
* @return the parameter string of this label
*/
protected String paramString() {
String str = ",align=";
switch (alignment) {
case LEFT: str += "left"; break;
case CENTER: str += "center"; break;
case RIGHT: str += "right"; break;
}
return super.paramString() + str + ",text=" + text;
}
/** {@collect.stats}
* Initialize JNI field and method IDs
*/
private static native void initIDs();
/////////////////
// Accessibility support
////////////////
/** {@collect.stats}
* Gets the AccessibleContext associated with this Label.
* For labels, the AccessibleContext takes the form of an
* AccessibleAWTLabel.
* A new AccessibleAWTLabel instance is created if necessary.
*
* @return an AccessibleAWTLabel that serves as the
* AccessibleContext of this Label
* @since 1.3
*/
public AccessibleContext getAccessibleContext() {
if (accessibleContext == null) {
accessibleContext = new AccessibleAWTLabel();
}
return accessibleContext;
}
/** {@collect.stats}
* This class implements accessibility support for the
* <code>Label</code> class. It provides an implementation of the
* Java Accessibility API appropriate to label user-interface elements.
* @since 1.3
*/
protected class AccessibleAWTLabel extends AccessibleAWTComponent
{
/*
* JDK 1.3 serialVersionUID
*/
private static final long serialVersionUID = -3568967560160480438L;
public AccessibleAWTLabel() {
super();
}
/** {@collect.stats}
* Get the accessible name of this object.
*
* @return the localized name of the object -- can be null if this
* object does not have a name
* @see AccessibleContext#setAccessibleName
*/
public String getAccessibleName() {
if (accessibleName != null) {
return accessibleName;
} else {
if (getText() == null) {
return super.getAccessibleName();
} else {
return getText();
}
}
}
/** {@collect.stats}
* Get the role of this object.
*
* @return an instance of AccessibleRole describing the role of the object
* @see AccessibleRole
*/
public AccessibleRole getAccessibleRole() {
return AccessibleRole.LABEL;
}
} // inner class AccessibleAWTLabel
}
|
Java
|
/*
* Copyright (c) 2000, 2005, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code 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
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package java.awt;
/** {@collect.stats}
* A FocusTraversalPolicy defines the order in which Components with a
* particular focus cycle root are traversed. Instances can apply the policy to
* arbitrary focus cycle roots, allowing themselves to be shared across
* Containers. They do not need to be reinitialized when the focus cycle roots
* of a Component hierarchy change.
* <p>
* The core responsibility of a FocusTraversalPolicy is to provide algorithms
* determining the next and previous Components to focus when traversing
* forward or backward in a UI. Each FocusTraversalPolicy must also provide
* algorithms for determining the first, last, and default Components in a
* traversal cycle. First and last Components are used when normal forward and
* backward traversal, respectively, wraps. The default Component is the first
* to receive focus when traversing down into a new focus traversal cycle.
* A FocusTraversalPolicy can optionally provide an algorithm for determining
* a Window's initial Component. The initial Component is the first to receive
* focus when a Window is first made visible.
* <p>
* FocusTraversalPolicy takes into account <a
* href="doc-files/FocusSpec.html#FocusTraversalPolicyProviders">focus traversal
* policy providers</a>. When searching for first/last/next/previous Component,
* if a focus traversal policy provider is encountered, its focus traversal
* policy is used to perform the search operation.
* <p>
* Please see
* <a href="http://java.sun.com/docs/books/tutorial/uiswing/misc/focus.html">
* How to Use the Focus Subsystem</a>,
* a section in <em>The Java Tutorial</em>, and the
* <a href="../../java/awt/doc-files/FocusSpec.html">Focus Specification</a>
* for more information.
*
* @author David Mendenhall
*
* @see Container#setFocusTraversalPolicy
* @see Container#getFocusTraversalPolicy
* @see Container#setFocusCycleRoot
* @see Container#isFocusCycleRoot
* @see Container#setFocusTraversalPolicyProvider
* @see Container#isFocusTraversalPolicyProvider
* @see KeyboardFocusManager#setDefaultFocusTraversalPolicy
* @see KeyboardFocusManager#getDefaultFocusTraversalPolicy
* @since 1.4
*/
public abstract class FocusTraversalPolicy {
/** {@collect.stats}
* Returns the Component that should receive the focus after aComponent.
* aContainer must be a focus cycle root of aComponent or a focus traversal
* policy provider.
*
* @param aContainer a focus cycle root of aComponent or focus traversal
* policy provider
* @param aComponent a (possibly indirect) child of aContainer, or
* aContainer itself
* @return the Component that should receive the focus after aComponent, or
* null if no suitable Component can be found
* @throws IllegalArgumentException if aContainer is not a focus cycle
* root of aComponent or a focus traversal policy provider, or if
* either aContainer or aComponent is null
*/
public abstract Component getComponentAfter(Container aContainer,
Component aComponent);
/** {@collect.stats}
* Returns the Component that should receive the focus before aComponent.
* aContainer must be a focus cycle root of aComponent or a focus traversal
* policy provider.
*
* @param aContainer a focus cycle root of aComponent or focus traversal
* policy provider
* @param aComponent a (possibly indirect) child of aContainer, or
* aContainer itself
* @return the Component that should receive the focus before aComponent,
* or null if no suitable Component can be found
* @throws IllegalArgumentException if aContainer is not a focus cycle
* root of aComponent or a focus traversal policy provider, or if
* either aContainer or aComponent is null
*/
public abstract Component getComponentBefore(Container aContainer,
Component aComponent);
/** {@collect.stats}
* Returns the first Component in the traversal cycle. This method is used
* to determine the next Component to focus when traversal wraps in the
* forward direction.
*
* @param aContainer the focus cycle root or focus traversal policy provider
* whose first Component is to be returned
* @return the first Component in the traversal cycle of aContainer,
* or null if no suitable Component can be found
* @throws IllegalArgumentException if aContainer is null
*/
public abstract Component getFirstComponent(Container aContainer);
/** {@collect.stats}
* Returns the last Component in the traversal cycle. This method is used
* to determine the next Component to focus when traversal wraps in the
* reverse direction.
*
* @param aContainer the focus cycle root or focus traversal policy
* provider whose last Component is to be returned
* @return the last Component in the traversal cycle of aContainer,
* or null if no suitable Component can be found
* @throws IllegalArgumentException if aContainer is null
*/
public abstract Component getLastComponent(Container aContainer);
/** {@collect.stats}
* Returns the default Component to focus. This Component will be the first
* to receive focus when traversing down into a new focus traversal cycle
* rooted at aContainer.
*
* @param aContainer the focus cycle root or focus traversal policy
* provider whose default Component is to be returned
* @return the default Component in the traversal cycle of aContainer,
* or null if no suitable Component can be found
* @throws IllegalArgumentException if aContainer is null
*/
public abstract Component getDefaultComponent(Container aContainer);
/** {@collect.stats}
* Returns the Component that should receive the focus when a Window is
* made visible for the first time. Once the Window has been made visible
* by a call to <code>show()</code> or <code>setVisible(true)</code>, the
* initial Component will not be used again. Instead, if the Window loses
* and subsequently regains focus, or is made invisible or undisplayable
* and subsequently made visible and displayable, the Window's most
* recently focused Component will become the focus owner. The default
* implementation of this method returns the default Component.
*
* @param window the Window whose initial Component is to be returned
* @return the Component that should receive the focus when window is made
* visible for the first time, or null if no suitable Component can
* be found
* @see #getDefaultComponent
* @see Window#getMostRecentFocusOwner
* @throws IllegalArgumentException if window is null
*/
public Component getInitialComponent(Window window) {
if ( window == null ){
throw new IllegalArgumentException("window cannot be equal to null.");
}
Component def = getDefaultComponent(window);
if (def == null && window.isFocusableWindow()) {
def = window;
}
return def;
}
}
|
Java
|
/*
* Copyright (c) 1996, 2005, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code 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
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package java.awt;
import java.awt.RenderingHints.Key;
import java.awt.geom.AffineTransform;
import java.awt.image.ImageObserver;
import java.awt.image.BufferedImageOp;
import java.awt.image.BufferedImage;
import java.awt.image.RenderedImage;
import java.awt.image.renderable.RenderableImage;
import java.awt.font.GlyphVector;
import java.awt.font.FontRenderContext;
import java.awt.font.TextAttribute;
import java.text.AttributedCharacterIterator;
import java.util.Map;
/** {@collect.stats}
* This <code>Graphics2D</code> class extends the
* {@link Graphics} class to provide more sophisticated
* control over geometry, coordinate transformations, color management,
* and text layout. This is the fundamental class for rendering
* 2-dimensional shapes, text and images on the Java(tm) platform.
* <p>
* <h2>Coordinate Spaces</h2>
* All coordinates passed to a <code>Graphics2D</code> object are specified
* in a device-independent coordinate system called User Space, which is
* used by applications. The <code>Graphics2D</code> object contains
* an {@link AffineTransform} object as part of its rendering state
* that defines how to convert coordinates from user space to
* device-dependent coordinates in Device Space.
* <p>
* Coordinates in device space usually refer to individual device pixels
* and are aligned on the infinitely thin gaps between these pixels.
* Some <code>Graphics2D</code> objects can be used to capture rendering
* operations for storage into a graphics metafile for playback on a
* concrete device of unknown physical resolution at a later time. Since
* the resolution might not be known when the rendering operations are
* captured, the <code>Graphics2D</code> <code>Transform</code> is set up
* to transform user coordinates to a virtual device space that
* approximates the expected resolution of the target device. Further
* transformations might need to be applied at playback time if the
* estimate is incorrect.
* <p>
* Some of the operations performed by the rendering attribute objects
* occur in the device space, but all <code>Graphics2D</code> methods take
* user space coordinates.
* <p>
* Every <code>Graphics2D</code> object is associated with a target that
* defines where rendering takes place. A
* {@link GraphicsConfiguration} object defines the characteristics
* of the rendering target, such as pixel format and resolution.
* The same rendering target is used throughout the life of a
* <code>Graphics2D</code> object.
* <p>
* When creating a <code>Graphics2D</code> object, the
* <code>GraphicsConfiguration</code>
* specifies the <a name="#deftransform">default transform</a> for
* the target of the <code>Graphics2D</code> (a
* {@link Component} or {@link Image}). This default transform maps the
* user space coordinate system to screen and printer device coordinates
* such that the origin maps to the upper left hand corner of the
* target region of the device with increasing X coordinates extending
* to the right and increasing Y coordinates extending downward.
* The scaling of the default transform is set to identity for those devices
* that are close to 72 dpi, such as screen devices.
* The scaling of the default transform is set to approximately 72 user
* space coordinates per square inch for high resolution devices, such as
* printers. For image buffers, the default transform is the
* <code>Identity</code> transform.
*
* <h2>Rendering Process</h2>
* The Rendering Process can be broken down into four phases that are
* controlled by the <code>Graphics2D</code> rendering attributes.
* The renderer can optimize many of these steps, either by caching the
* results for future calls, by collapsing multiple virtual steps into
* a single operation, or by recognizing various attributes as common
* simple cases that can be eliminated by modifying other parts of the
* operation.
* <p>
* The steps in the rendering process are:
* <ol>
* <li>
* Determine what to render.
* <li>
* Constrain the rendering operation to the current <code>Clip</code>.
* The <code>Clip</code> is specified by a {@link Shape} in user
* space and is controlled by the program using the various clip
* manipulation methods of <code>Graphics</code> and
* <code>Graphics2D</code>. This <i>user clip</i>
* is transformed into device space by the current
* <code>Transform</code> and combined with the
* <i>device clip</i>, which is defined by the visibility of windows and
* device extents. The combination of the user clip and device clip
* defines the <i>composite clip</i>, which determines the final clipping
* region. The user clip is not modified by the rendering
* system to reflect the resulting composite clip.
* <li>
* Determine what colors to render.
* <li>
* Apply the colors to the destination drawing surface using the current
* {@link Composite} attribute in the <code>Graphics2D</code> context.
* </ol>
* <br>
* The three types of rendering operations, along with details of each
* of their particular rendering processes are:
* <ol>
* <li>
* <b><a name="rendershape"><code>Shape</code> operations</a></b>
* <ol>
* <li>
* If the operation is a <code>draw(Shape)</code> operation, then
* the {@link Stroke#createStrokedShape(Shape) createStrokedShape}
* method on the current {@link Stroke} attribute in the
* <code>Graphics2D</code> context is used to construct a new
* <code>Shape</code> object that contains the outline of the specified
* <code>Shape</code>.
* <li>
* The <code>Shape</code> is transformed from user space to device space
* using the current <code>Transform</code>
* in the <code>Graphics2D</code> context.
* <li>
* The outline of the <code>Shape</code> is extracted using the
* {@link Shape#getPathIterator(AffineTransform) getPathIterator} method of
* <code>Shape</code>, which returns a
* {@link java.awt.geom.PathIterator PathIterator}
* object that iterates along the boundary of the <code>Shape</code>.
* <li>
* If the <code>Graphics2D</code> object cannot handle the curved segments
* that the <code>PathIterator</code> object returns then it can call the
* alternate
* {@link Shape#getPathIterator(AffineTransform, double) getPathIterator}
* method of <code>Shape</code>, which flattens the <code>Shape</code>.
* <li>
* The current {@link Paint} in the <code>Graphics2D</code> context
* is queried for a {@link PaintContext}, which specifies the
* colors to render in device space.
* </ol>
* <li>
* <b><a name=rendertext>Text operations</a></b>
* <ol>
* <li>
* The following steps are used to determine the set of glyphs required
* to render the indicated <code>String</code>:
* <ol>
* <li>
* If the argument is a <code>String</code>, then the current
* <code>Font</code> in the <code>Graphics2D</code> context is asked to
* convert the Unicode characters in the <code>String</code> into a set of
* glyphs for presentation with whatever basic layout and shaping
* algorithms the font implements.
* <li>
* If the argument is an
* {@link AttributedCharacterIterator},
* the iterator is asked to convert itself to a
* {@link java.awt.font.TextLayout TextLayout}
* using its embedded font attributes. The <code>TextLayout</code>
* implements more sophisticated glyph layout algorithms that
* perform Unicode bi-directional layout adjustments automatically
* for multiple fonts of differing writing directions.
* <li>
* If the argument is a
* {@link GlyphVector}, then the
* <code>GlyphVector</code> object already contains the appropriate
* font-specific glyph codes with explicit coordinates for the position of
* each glyph.
* </ol>
* <li>
* The current <code>Font</code> is queried to obtain outlines for the
* indicated glyphs. These outlines are treated as shapes in user space
* relative to the position of each glyph that was determined in step 1.
* <li>
* The character outlines are filled as indicated above
* under <a href="#rendershape"><code>Shape</code> operations</a>.
* <li>
* The current <code>Paint</code> is queried for a
* <code>PaintContext</code>, which specifies
* the colors to render in device space.
* </ol>
* <li>
* <b><a name= renderingimage><code>Image</code> Operations</a></b>
* <ol>
* <li>
* The region of interest is defined by the bounding box of the source
* <code>Image</code>.
* This bounding box is specified in Image Space, which is the
* <code>Image</code> object's local coordinate system.
* <li>
* If an <code>AffineTransform</code> is passed to
* {@link #drawImage(java.awt.Image, java.awt.geom.AffineTransform, java.awt.image.ImageObserver) drawImage(Image, AffineTransform, ImageObserver)},
* the <code>AffineTransform</code> is used to transform the bounding
* box from image space to user space. If no <code>AffineTransform</code>
* is supplied, the bounding box is treated as if it is already in user space.
* <li>
* The bounding box of the source <code>Image</code> is transformed from user
* space into device space using the current <code>Transform</code>.
* Note that the result of transforming the bounding box does not
* necessarily result in a rectangular region in device space.
* <li>
* The <code>Image</code> object determines what colors to render,
* sampled according to the source to destination
* coordinate mapping specified by the current <code>Transform</code> and the
* optional image transform.
* </ol>
* </ol>
*
* <h2>Default Rendering Attributes</h2>
* The default values for the <code>Graphics2D</code> rendering attributes are:
* <dl compact>
* <dt><i><code>Paint</code></i>
* <dd>The color of the <code>Component</code>.
* <dt><i><code>Font</code></i>
* <dd>The <code>Font</code> of the <code>Component</code>.
* <dt><i><code>Stroke</code></i>
* <dd>A square pen with a linewidth of 1, no dashing, miter segment joins
* and square end caps.
* <dt><i><code>Transform</code></i>
* <dd>The
* {@link GraphicsConfiguration#getDefaultTransform() getDefaultTransform}
* for the <code>GraphicsConfiguration</code> of the <code>Component</code>.
* <dt><i><code>Composite</code></i>
* <dd>The {@link AlphaComposite#SRC_OVER} rule.
* <dt><i><code>Clip</code></i>
* <dd>No rendering <code>Clip</code>, the output is clipped to the
* <code>Component</code>.
* </dl>
*
* <h2>Rendering Compatibility Issues</h2>
* The JDK(tm) 1.1 rendering model is based on a pixelization model
* that specifies that coordinates
* are infinitely thin, lying between the pixels. Drawing operations are
* performed using a one-pixel wide pen that fills the
* pixel below and to the right of the anchor point on the path.
* The JDK 1.1 rendering model is consistent with the
* capabilities of most of the existing class of platform
* renderers that need to resolve integer coordinates to a
* discrete pen that must fall completely on a specified number of pixels.
* <p>
* The Java 2D(tm) (Java(tm) 2 platform) API supports antialiasing renderers.
* A pen with a width of one pixel does not need to fall
* completely on pixel N as opposed to pixel N+1. The pen can fall
* partially on both pixels. It is not necessary to choose a bias
* direction for a wide pen since the blending that occurs along the
* pen traversal edges makes the sub-pixel position of the pen
* visible to the user. On the other hand, when antialiasing is
* turned off by setting the
* {@link RenderingHints#KEY_ANTIALIASING KEY_ANTIALIASING} hint key
* to the
* {@link RenderingHints#VALUE_ANTIALIAS_OFF VALUE_ANTIALIAS_OFF}
* hint value, the renderer might need
* to apply a bias to determine which pixel to modify when the pen
* is straddling a pixel boundary, such as when it is drawn
* along an integer coordinate in device space. While the capabilities
* of an antialiasing renderer make it no longer necessary for the
* rendering model to specify a bias for the pen, it is desirable for the
* antialiasing and non-antialiasing renderers to perform similarly for
* the common cases of drawing one-pixel wide horizontal and vertical
* lines on the screen. To ensure that turning on antialiasing by
* setting the
* {@link RenderingHints#KEY_ANTIALIASING KEY_ANTIALIASING} hint
* key to
* {@link RenderingHints#VALUE_ANTIALIAS_ON VALUE_ANTIALIAS_ON}
* does not cause such lines to suddenly become twice as wide and half
* as opaque, it is desirable to have the model specify a path for such
* lines so that they completely cover a particular set of pixels to help
* increase their crispness.
* <p>
* Java 2D API maintains compatibility with JDK 1.1 rendering
* behavior, such that legacy operations and existing renderer
* behavior is unchanged under Java 2D API. Legacy
* methods that map onto general <code>draw</code> and
* <code>fill</code> methods are defined, which clearly indicates
* how <code>Graphics2D</code> extends <code>Graphics</code> based
* on settings of <code>Stroke</code> and <code>Transform</code>
* attributes and rendering hints. The definition
* performs identically under default attribute settings.
* For example, the default <code>Stroke</code> is a
* <code>BasicStroke</code> with a width of 1 and no dashing and the
* default Transform for screen drawing is an Identity transform.
* <p>
* The following two rules provide predictable rendering behavior whether
* aliasing or antialiasing is being used.
* <ul>
* <li> Device coordinates are defined to be between device pixels which
* avoids any inconsistent results between aliased and antaliased
* rendering. If coordinates were defined to be at a pixel's center, some
* of the pixels covered by a shape, such as a rectangle, would only be
* half covered.
* With aliased rendering, the half covered pixels would either be
* rendered inside the shape or outside the shape. With anti-aliased
* rendering, the pixels on the entire edge of the shape would be half
* covered. On the other hand, since coordinates are defined to be
* between pixels, a shape like a rectangle would have no half covered
* pixels, whether or not it is rendered using antialiasing.
* <li> Lines and paths stroked using the <code>BasicStroke</code>
* object may be "normalized" to provide consistent rendering of the
* outlines when positioned at various points on the drawable and
* whether drawn with aliased or antialiased rendering. This
* normalization process is controlled by the
* {@link RenderingHints#KEY_STROKE_CONTROL KEY_STROKE_CONTROL} hint.
* The exact normalization algorithm is not specified, but the goals
* of this normalization are to ensure that lines are rendered with
* consistent visual appearance regardless of how they fall on the
* pixel grid and to promote more solid horizontal and vertical
* lines in antialiased mode so that they resemble their non-antialiased
* counterparts more closely. A typical normalization step might
* promote antialiased line endpoints to pixel centers to reduce the
* amount of blending or adjust the subpixel positioning of
* non-antialiased lines so that the floating point line widths
* round to even or odd pixel counts with equal likelihood. This
* process can move endpoints by up to half a pixel (usually towards
* positive infinity along both axes) to promote these consistent
* results.
* </ul>
* <p>
* The following definitions of general legacy methods
* perform identically to previously specified behavior under default
* attribute settings:
* <ul>
* <li>
* For <code>fill</code> operations, including <code>fillRect</code>,
* <code>fillRoundRect</code>, <code>fillOval</code>,
* <code>fillArc</code>, <code>fillPolygon</code>, and
* <code>clearRect</code>, {@link #fill(Shape) fill} can now be called
* with the desired <code>Shape</code>. For example, when filling a
* rectangle:
* <pre>
* fill(new Rectangle(x, y, w, h));
* </pre>
* is called.
* <p>
* <li>
* Similarly, for draw operations, including <code>drawLine</code>,
* <code>drawRect</code>, <code>drawRoundRect</code>,
* <code>drawOval</code>, <code>drawArc</code>, <code>drawPolyline</code>,
* and <code>drawPolygon</code>, {@link #draw(Shape) draw} can now be
* called with the desired <code>Shape</code>. For example, when drawing a
* rectangle:
* <pre>
* draw(new Rectangle(x, y, w, h));
* </pre>
* is called.
* <p>
* <li>
* The <code>draw3DRect</code> and <code>fill3DRect</code> methods were
* implemented in terms of the <code>drawLine</code> and
* <code>fillRect</code> methods in the <code>Graphics</code> class which
* would predicate their behavior upon the current <code>Stroke</code>
* and <code>Paint</code> objects in a <code>Graphics2D</code> context.
* This class overrides those implementations with versions that use
* the current <code>Color</code> exclusively, overriding the current
* <code>Paint</code> and which uses <code>fillRect</code> to describe
* the exact same behavior as the preexisting methods regardless of the
* setting of the current <code>Stroke</code>.
* </ul>
* The <code>Graphics</code> class defines only the <code>setColor</code>
* method to control the color to be painted. Since the Java 2D API extends
* the <code>Color</code> object to implement the new <code>Paint</code>
* interface, the existing
* <code>setColor</code> method is now a convenience method for setting the
* current <code>Paint</code> attribute to a <code>Color</code> object.
* <code>setColor(c)</code> is equivalent to <code>setPaint(c)</code>.
* <p>
* The <code>Graphics</code> class defines two methods for controlling
* how colors are applied to the destination.
* <ol>
* <li>
* The <code>setPaintMode</code> method is implemented as a convenience
* method to set the default <code>Composite</code>, equivalent to
* <code>setComposite(new AlphaComposite.SrcOver)</code>.
* <li>
* The <code>setXORMode(Color xorcolor)</code> method is implemented
* as a convenience method to set a special <code>Composite</code> object that
* ignores the <code>Alpha</code> components of source colors and sets the
* destination color to the value:
* <pre>
* dstpixel = (PixelOf(srccolor) ^ PixelOf(xorcolor) ^ dstpixel);
* </pre>
* </ol>
*
* @author Jim Graham
* @see java.awt.RenderingHints
*/
public abstract class Graphics2D extends Graphics {
/** {@collect.stats}
* Constructs a new <code>Graphics2D</code> object. Since
* <code>Graphics2D</code> is an abstract class, and since it must be
* customized by subclasses for different output devices,
* <code>Graphics2D</code> objects cannot be created directly.
* Instead, <code>Graphics2D</code> objects must be obtained from another
* <code>Graphics2D</code> object, created by a
* <code>Component</code>, or obtained from images such as
* {@link BufferedImage} objects.
* @see java.awt.Component#getGraphics
* @see java.awt.Graphics#create
*/
protected Graphics2D() {
}
/** {@collect.stats}
* Draws a 3-D highlighted outline of the specified rectangle.
* The edges of the rectangle are highlighted so that they
* appear to be beveled and lit from the upper left corner.
* <p>
* The colors used for the highlighting effect are determined
* based on the current color.
* The resulting rectangle covers an area that is
* <code>width + 1</code> pixels wide
* by <code>height + 1</code> pixels tall. This method
* uses the current <code>Color</code> exclusively and ignores
* the current <code>Paint</code>.
* @param x the x coordinate of the rectangle to be drawn.
* @param y the y coordinate of the rectangle to be drawn.
* @param width the width of the rectangle to be drawn.
* @param height the height of the rectangle to be drawn.
* @param raised a boolean that determines whether the rectangle
* appears to be raised above the surface
* or sunk into the surface.
* @see java.awt.Graphics#fill3DRect
*/
public void draw3DRect(int x, int y, int width, int height,
boolean raised) {
Paint p = getPaint();
Color c = getColor();
Color brighter = c.brighter();
Color darker = c.darker();
setColor(raised ? brighter : darker);
//drawLine(x, y, x, y + height);
fillRect(x, y, 1, height + 1);
//drawLine(x + 1, y, x + width - 1, y);
fillRect(x + 1, y, width - 1, 1);
setColor(raised ? darker : brighter);
//drawLine(x + 1, y + height, x + width, y + height);
fillRect(x + 1, y + height, width, 1);
//drawLine(x + width, y, x + width, y + height - 1);
fillRect(x + width, y, 1, height);
setPaint(p);
}
/** {@collect.stats}
* Paints a 3-D highlighted rectangle filled with the current color.
* The edges of the rectangle are highlighted so that it appears
* as if the edges were beveled and lit from the upper left corner.
* The colors used for the highlighting effect and for filling are
* determined from the current <code>Color</code>. This method uses
* the current <code>Color</code> exclusively and ignores the current
* <code>Paint</code>.
* @param x the x coordinate of the rectangle to be filled.
* @param y the y coordinate of the rectangle to be filled.
* @param width the width of the rectangle to be filled.
* @param height the height of the rectangle to be filled.
* @param raised a boolean value that determines whether the
* rectangle appears to be raised above the surface
* or etched into the surface.
* @see java.awt.Graphics#draw3DRect
*/
public void fill3DRect(int x, int y, int width, int height,
boolean raised) {
Paint p = getPaint();
Color c = getColor();
Color brighter = c.brighter();
Color darker = c.darker();
if (!raised) {
setColor(darker);
} else if (p != c) {
setColor(c);
}
fillRect(x+1, y+1, width-2, height-2);
setColor(raised ? brighter : darker);
//drawLine(x, y, x, y + height - 1);
fillRect(x, y, 1, height);
//drawLine(x + 1, y, x + width - 2, y);
fillRect(x + 1, y, width - 2, 1);
setColor(raised ? darker : brighter);
//drawLine(x + 1, y + height - 1, x + width - 1, y + height - 1);
fillRect(x + 1, y + height - 1, width - 1, 1);
//drawLine(x + width - 1, y, x + width - 1, y + height - 2);
fillRect(x + width - 1, y, 1, height - 1);
setPaint(p);
}
/** {@collect.stats}
* Strokes the outline of a <code>Shape</code> using the settings of the
* current <code>Graphics2D</code> context. The rendering attributes
* applied include the <code>Clip</code>, <code>Transform</code>,
* <code>Paint</code>, <code>Composite</code> and
* <code>Stroke</code> attributes.
* @param s the <code>Shape</code> to be rendered
* @see #setStroke
* @see #setPaint
* @see java.awt.Graphics#setColor
* @see #transform
* @see #setTransform
* @see #clip
* @see #setClip
* @see #setComposite
*/
public abstract void draw(Shape s);
/** {@collect.stats}
* Renders an image, applying a transform from image space into user space
* before drawing.
* The transformation from user space into device space is done with
* the current <code>Transform</code> in the <code>Graphics2D</code>.
* The specified transformation is applied to the image before the
* transform attribute in the <code>Graphics2D</code> context is applied.
* The rendering attributes applied include the <code>Clip</code>,
* <code>Transform</code>, and <code>Composite</code> attributes.
* Note that no rendering is done if the specified transform is
* noninvertible.
* @param img the specified image to be rendered.
* This method does nothing if <code>img</code> is null.
* @param xform the transformation from image space into user space
* @param obs the {@link ImageObserver}
* to be notified as more of the <code>Image</code>
* is converted
* @return <code>true</code> if the <code>Image</code> is
* fully loaded and completely rendered, or if it's null;
* <code>false</code> if the <code>Image</code> is still being loaded.
* @see #transform
* @see #setTransform
* @see #setComposite
* @see #clip
* @see #setClip
*/
public abstract boolean drawImage(Image img,
AffineTransform xform,
ImageObserver obs);
/** {@collect.stats}
* Renders a <code>BufferedImage</code> that is
* filtered with a
* {@link BufferedImageOp}.
* The rendering attributes applied include the <code>Clip</code>,
* <code>Transform</code>
* and <code>Composite</code> attributes. This is equivalent to:
* <pre>
* img1 = op.filter(img, null);
* drawImage(img1, new AffineTransform(1f,0f,0f,1f,x,y), null);
* </pre>
* @param op the filter to be applied to the image before rendering
* @param img the specified <code>BufferedImage</code> to be rendered.
* This method does nothing if <code>img</code> is null.
* @param x the x coordinate of the location in user space where
* the upper left corner of the image is rendered
* @param y the y coordinate of the location in user space where
* the upper left corner of the image is rendered
*
* @see #transform
* @see #setTransform
* @see #setComposite
* @see #clip
* @see #setClip
*/
public abstract void drawImage(BufferedImage img,
BufferedImageOp op,
int x,
int y);
/** {@collect.stats}
* Renders a {@link RenderedImage},
* applying a transform from image
* space into user space before drawing.
* The transformation from user space into device space is done with
* the current <code>Transform</code> in the <code>Graphics2D</code>.
* The specified transformation is applied to the image before the
* transform attribute in the <code>Graphics2D</code> context is applied.
* The rendering attributes applied include the <code>Clip</code>,
* <code>Transform</code>, and <code>Composite</code> attributes. Note
* that no rendering is done if the specified transform is
* noninvertible.
* @param img the image to be rendered. This method does
* nothing if <code>img</code> is null.
* @param xform the transformation from image space into user space
* @see #transform
* @see #setTransform
* @see #setComposite
* @see #clip
* @see #setClip
*/
public abstract void drawRenderedImage(RenderedImage img,
AffineTransform xform);
/** {@collect.stats}
* Renders a
* {@link RenderableImage},
* applying a transform from image space into user space before drawing.
* The transformation from user space into device space is done with
* the current <code>Transform</code> in the <code>Graphics2D</code>.
* The specified transformation is applied to the image before the
* transform attribute in the <code>Graphics2D</code> context is applied.
* The rendering attributes applied include the <code>Clip</code>,
* <code>Transform</code>, and <code>Composite</code> attributes. Note
* that no rendering is done if the specified transform is
* noninvertible.
*<p>
* Rendering hints set on the <code>Graphics2D</code> object might
* be used in rendering the <code>RenderableImage</code>.
* If explicit control is required over specific hints recognized by a
* specific <code>RenderableImage</code>, or if knowledge of which hints
* are used is required, then a <code>RenderedImage</code> should be
* obtained directly from the <code>RenderableImage</code>
* and rendered using
*{@link #drawRenderedImage(RenderedImage, AffineTransform) drawRenderedImage}.
* @param img the image to be rendered. This method does
* nothing if <code>img</code> is null.
* @param xform the transformation from image space into user space
* @see #transform
* @see #setTransform
* @see #setComposite
* @see #clip
* @see #setClip
* @see #drawRenderedImage
*/
public abstract void drawRenderableImage(RenderableImage img,
AffineTransform xform);
/** {@collect.stats}
* Renders the text of the specified <code>String</code>, using the
* current text attribute state in the <code>Graphics2D</code> context.
* The baseline of the
* first character is at position (<i>x</i>, <i>y</i>) in
* the User Space.
* The rendering attributes applied include the <code>Clip</code>,
* <code>Transform</code>, <code>Paint</code>, <code>Font</code> and
* <code>Composite</code> attributes. For characters in script
* systems such as Hebrew and Arabic, the glyphs can be rendered from
* right to left, in which case the coordinate supplied is the
* location of the leftmost character on the baseline.
* @param str the string to be rendered
* @param x the x coordinate of the location where the
* <code>String</code> should be rendered
* @param y the y coordinate of the location where the
* <code>String</code> should be rendered
* @throws NullPointerException if <code>str</code> is
* <code>null</code>
* @see java.awt.Graphics#drawBytes
* @see java.awt.Graphics#drawChars
* @since JDK1.0
*/
public abstract void drawString(String str, int x, int y);
/** {@collect.stats}
* Renders the text specified by the specified <code>String</code>,
* using the current text attribute state in the <code>Graphics2D</code> context.
* The baseline of the first character is at position
* (<i>x</i>, <i>y</i>) in the User Space.
* The rendering attributes applied include the <code>Clip</code>,
* <code>Transform</code>, <code>Paint</code>, <code>Font</code> and
* <code>Composite</code> attributes. For characters in script systems
* such as Hebrew and Arabic, the glyphs can be rendered from right to
* left, in which case the coordinate supplied is the location of the
* leftmost character on the baseline.
* @param str the <code>String</code> to be rendered
* @param x the x coordinate of the location where the
* <code>String</code> should be rendered
* @param y the y coordinate of the location where the
* <code>String</code> should be rendered
* @throws NullPointerException if <code>str</code> is
* <code>null</code>
* @see #setPaint
* @see java.awt.Graphics#setColor
* @see java.awt.Graphics#setFont
* @see #setTransform
* @see #setComposite
* @see #setClip
*/
public abstract void drawString(String str, float x, float y);
/** {@collect.stats}
* Renders the text of the specified iterator applying its attributes
* in accordance with the specification of the {@link TextAttribute} class.
* <p>
* The baseline of the first character is at position
* (<i>x</i>, <i>y</i>) in User Space.
* For characters in script systems such as Hebrew and Arabic,
* the glyphs can be rendered from right to left, in which case the
* coordinate supplied is the location of the leftmost character
* on the baseline.
* @param iterator the iterator whose text is to be rendered
* @param x the x coordinate where the iterator's text is to be
* rendered
* @param y the y coordinate where the iterator's text is to be
* rendered
* @throws NullPointerException if <code>iterator</code> is
* <code>null</code>
* @see #setPaint
* @see java.awt.Graphics#setColor
* @see #setTransform
* @see #setComposite
* @see #setClip
*/
public abstract void drawString(AttributedCharacterIterator iterator,
int x, int y);
/** {@collect.stats}
* Renders the text of the specified iterator applying its attributes
* in accordance with the specification of the {@link TextAttribute} class.
* <p>
* The baseline of the first character is at position
* (<i>x</i>, <i>y</i>) in User Space.
* For characters in script systems such as Hebrew and Arabic,
* the glyphs can be rendered from right to left, in which case the
* coordinate supplied is the location of the leftmost character
* on the baseline.
* @param iterator the iterator whose text is to be rendered
* @param x the x coordinate where the iterator's text is to be
* rendered
* @param y the y coordinate where the iterator's text is to be
* rendered
* @throws NullPointerException if <code>iterator</code> is
* <code>null</code>
* @see #setPaint
* @see java.awt.Graphics#setColor
* @see #setTransform
* @see #setComposite
* @see #setClip
*/
public abstract void drawString(AttributedCharacterIterator iterator,
float x, float y);
/** {@collect.stats}
* Renders the text of the specified
* {@link GlyphVector} using
* the <code>Graphics2D</code> context's rendering attributes.
* The rendering attributes applied include the <code>Clip</code>,
* <code>Transform</code>, <code>Paint</code>, and
* <code>Composite</code> attributes. The <code>GlyphVector</code>
* specifies individual glyphs from a {@link Font}.
* The <code>GlyphVector</code> can also contain the glyph positions.
* This is the fastest way to render a set of characters to the
* screen.
* @param g the <code>GlyphVector</code> to be rendered
* @param x the x position in User Space where the glyphs should
* be rendered
* @param y the y position in User Space where the glyphs should
* be rendered
* @throws NullPointerException if <code>g</code> is <code>null</code>.
*
* @see java.awt.Font#createGlyphVector
* @see java.awt.font.GlyphVector
* @see #setPaint
* @see java.awt.Graphics#setColor
* @see #setTransform
* @see #setComposite
* @see #setClip
*/
public abstract void drawGlyphVector(GlyphVector g, float x, float y);
/** {@collect.stats}
* Fills the interior of a <code>Shape</code> using the settings of the
* <code>Graphics2D</code> context. The rendering attributes applied
* include the <code>Clip</code>, <code>Transform</code>,
* <code>Paint</code>, and <code>Composite</code>.
* @param s the <code>Shape</code> to be filled
* @see #setPaint
* @see java.awt.Graphics#setColor
* @see #transform
* @see #setTransform
* @see #setComposite
* @see #clip
* @see #setClip
*/
public abstract void fill(Shape s);
/** {@collect.stats}
* Checks whether or not the specified <code>Shape</code> intersects
* the specified {@link Rectangle}, which is in device
* space. If <code>onStroke</code> is false, this method checks
* whether or not the interior of the specified <code>Shape</code>
* intersects the specified <code>Rectangle</code>. If
* <code>onStroke</code> is <code>true</code>, this method checks
* whether or not the <code>Stroke</code> of the specified
* <code>Shape</code> outline intersects the specified
* <code>Rectangle</code>.
* The rendering attributes taken into account include the
* <code>Clip</code>, <code>Transform</code>, and <code>Stroke</code>
* attributes.
* @param rect the area in device space to check for a hit
* @param s the <code>Shape</code> to check for a hit
* @param onStroke flag used to choose between testing the
* stroked or the filled shape. If the flag is <code>true</code>, the
* <code>Stroke</code> oultine is tested. If the flag is
* <code>false</code>, the filled <code>Shape</code> is tested.
* @return <code>true</code> if there is a hit; <code>false</code>
* otherwise.
* @see #setStroke
* @see #fill
* @see #draw
* @see #transform
* @see #setTransform
* @see #clip
* @see #setClip
*/
public abstract boolean hit(Rectangle rect,
Shape s,
boolean onStroke);
/** {@collect.stats}
* Returns the device configuration associated with this
* <code>Graphics2D</code>.
* @return the device configuration of this <code>Graphics2D</code>.
*/
public abstract GraphicsConfiguration getDeviceConfiguration();
/** {@collect.stats}
* Sets the <code>Composite</code> for the <code>Graphics2D</code> context.
* The <code>Composite</code> is used in all drawing methods such as
* <code>drawImage</code>, <code>drawString</code>, <code>draw</code>,
* and <code>fill</code>. It specifies how new pixels are to be combined
* with the existing pixels on the graphics device during the rendering
* process.
* <p>If this <code>Graphics2D</code> context is drawing to a
* <code>Component</code> on the display screen and the
* <code>Composite</code> is a custom object rather than an
* instance of the <code>AlphaComposite</code> class, and if
* there is a security manager, its <code>checkPermission</code>
* method is called with an <code>AWTPermission("readDisplayPixels")</code>
* permission.
* @throws SecurityException
* if a custom <code>Composite</code> object is being
* used to render to the screen and a security manager
* is set and its <code>checkPermission</code> method
* does not allow the operation.
* @param comp the <code>Composite</code> object to be used for rendering
* @see java.awt.Graphics#setXORMode
* @see java.awt.Graphics#setPaintMode
* @see #getComposite
* @see AlphaComposite
* @see SecurityManager#checkPermission
* @see java.awt.AWTPermission
*/
public abstract void setComposite(Composite comp);
/** {@collect.stats}
* Sets the <code>Paint</code> attribute for the
* <code>Graphics2D</code> context. Calling this method
* with a <code>null</code> <code>Paint</code> object does
* not have any effect on the current <code>Paint</code> attribute
* of this <code>Graphics2D</code>.
* @param paint the <code>Paint</code> object to be used to generate
* color during the rendering process, or <code>null</code>
* @see java.awt.Graphics#setColor
* @see #getPaint
* @see GradientPaint
* @see TexturePaint
*/
public abstract void setPaint( Paint paint );
/** {@collect.stats}
* Sets the <code>Stroke</code> for the <code>Graphics2D</code> context.
* @param s the <code>Stroke</code> object to be used to stroke a
* <code>Shape</code> during the rendering process
* @see BasicStroke
* @see #getStroke
*/
public abstract void setStroke(Stroke s);
/** {@collect.stats}
* Sets the value of a single preference for the rendering algorithms.
* Hint categories include controls for rendering quality and overall
* time/quality trade-off in the rendering process. Refer to the
* <code>RenderingHints</code> class for definitions of some common
* keys and values.
* @param hintKey the key of the hint to be set.
* @param hintValue the value indicating preferences for the specified
* hint category.
* @see #getRenderingHint(RenderingHints.Key)
* @see RenderingHints
*/
public abstract void setRenderingHint(Key hintKey, Object hintValue);
/** {@collect.stats}
* Returns the value of a single preference for the rendering algorithms.
* Hint categories include controls for rendering quality and overall
* time/quality trade-off in the rendering process. Refer to the
* <code>RenderingHints</code> class for definitions of some common
* keys and values.
* @param hintKey the key corresponding to the hint to get.
* @return an object representing the value for the specified hint key.
* Some of the keys and their associated values are defined in the
* <code>RenderingHints</code> class.
* @see RenderingHints
* @see #setRenderingHint(RenderingHints.Key, Object)
*/
public abstract Object getRenderingHint(Key hintKey);
/** {@collect.stats}
* Replaces the values of all preferences for the rendering
* algorithms with the specified <code>hints</code>.
* The existing values for all rendering hints are discarded and
* the new set of known hints and values are initialized from the
* specified {@link Map} object.
* Hint categories include controls for rendering quality and
* overall time/quality trade-off in the rendering process.
* Refer to the <code>RenderingHints</code> class for definitions of
* some common keys and values.
* @param hints the rendering hints to be set
* @see #getRenderingHints
* @see RenderingHints
*/
public abstract void setRenderingHints(Map<?,?> hints);
/** {@collect.stats}
* Sets the values of an arbitrary number of preferences for the
* rendering algorithms.
* Only values for the rendering hints that are present in the
* specified <code>Map</code> object are modified.
* All other preferences not present in the specified
* object are left unmodified.
* Hint categories include controls for rendering quality and
* overall time/quality trade-off in the rendering process.
* Refer to the <code>RenderingHints</code> class for definitions of
* some common keys and values.
* @param hints the rendering hints to be set
* @see RenderingHints
*/
public abstract void addRenderingHints(Map<?,?> hints);
/** {@collect.stats}
* Gets the preferences for the rendering algorithms. Hint categories
* include controls for rendering quality and overall time/quality
* trade-off in the rendering process.
* Returns all of the hint key/value pairs that were ever specified in
* one operation. Refer to the
* <code>RenderingHints</code> class for definitions of some common
* keys and values.
* @return a reference to an instance of <code>RenderingHints</code>
* that contains the current preferences.
* @see RenderingHints
* @see #setRenderingHints(Map)
*/
public abstract RenderingHints getRenderingHints();
/** {@collect.stats}
* Translates the origin of the <code>Graphics2D</code> context to the
* point (<i>x</i>, <i>y</i>) in the current coordinate system.
* Modifies the <code>Graphics2D</code> context so that its new origin
* corresponds to the point (<i>x</i>, <i>y</i>) in the
* <code>Graphics2D</code> context's former coordinate system. All
* coordinates used in subsequent rendering operations on this graphics
* context are relative to this new origin.
* @param x the specified x coordinate
* @param y the specified y coordinate
* @since JDK1.0
*/
public abstract void translate(int x, int y);
/** {@collect.stats}
* Concatenates the current
* <code>Graphics2D</code> <code>Transform</code>
* with a translation transform.
* Subsequent rendering is translated by the specified
* distance relative to the previous position.
* This is equivalent to calling transform(T), where T is an
* <code>AffineTransform</code> represented by the following matrix:
* <pre>
* [ 1 0 tx ]
* [ 0 1 ty ]
* [ 0 0 1 ]
* </pre>
* @param tx the distance to translate along the x-axis
* @param ty the distance to translate along the y-axis
*/
public abstract void translate(double tx, double ty);
/** {@collect.stats}
* Concatenates the current <code>Graphics2D</code>
* <code>Transform</code> with a rotation transform.
* Subsequent rendering is rotated by the specified radians relative
* to the previous origin.
* This is equivalent to calling <code>transform(R)</code>, where R is an
* <code>AffineTransform</code> represented by the following matrix:
* <pre>
* [ cos(theta) -sin(theta) 0 ]
* [ sin(theta) cos(theta) 0 ]
* [ 0 0 1 ]
* </pre>
* Rotating with a positive angle theta rotates points on the positive
* x axis toward the positive y axis.
* @param theta the angle of rotation in radians
*/
public abstract void rotate(double theta);
/** {@collect.stats}
* Concatenates the current <code>Graphics2D</code>
* <code>Transform</code> with a translated rotation
* transform. Subsequent rendering is transformed by a transform
* which is constructed by translating to the specified location,
* rotating by the specified radians, and translating back by the same
* amount as the original translation. This is equivalent to the
* following sequence of calls:
* <pre>
* translate(x, y);
* rotate(theta);
* translate(-x, -y);
* </pre>
* Rotating with a positive angle theta rotates points on the positive
* x axis toward the positive y axis.
* @param theta the angle of rotation in radians
* @param x the x coordinate of the origin of the rotation
* @param y the y coordinate of the origin of the rotation
*/
public abstract void rotate(double theta, double x, double y);
/** {@collect.stats}
* Concatenates the current <code>Graphics2D</code>
* <code>Transform</code> with a scaling transformation
* Subsequent rendering is resized according to the specified scaling
* factors relative to the previous scaling.
* This is equivalent to calling <code>transform(S)</code>, where S is an
* <code>AffineTransform</code> represented by the following matrix:
* <pre>
* [ sx 0 0 ]
* [ 0 sy 0 ]
* [ 0 0 1 ]
* </pre>
* @param sx the amount by which X coordinates in subsequent
* rendering operations are multiplied relative to previous
* rendering operations.
* @param sy the amount by which Y coordinates in subsequent
* rendering operations are multiplied relative to previous
* rendering operations.
*/
public abstract void scale(double sx, double sy);
/** {@collect.stats}
* Concatenates the current <code>Graphics2D</code>
* <code>Transform</code> with a shearing transform.
* Subsequent renderings are sheared by the specified
* multiplier relative to the previous position.
* This is equivalent to calling <code>transform(SH)</code>, where SH
* is an <code>AffineTransform</code> represented by the following
* matrix:
* <pre>
* [ 1 shx 0 ]
* [ shy 1 0 ]
* [ 0 0 1 ]
* </pre>
* @param shx the multiplier by which coordinates are shifted in
* the positive X axis direction as a function of their Y coordinate
* @param shy the multiplier by which coordinates are shifted in
* the positive Y axis direction as a function of their X coordinate
*/
public abstract void shear(double shx, double shy);
/** {@collect.stats}
* Composes an <code>AffineTransform</code> object with the
* <code>Transform</code> in this <code>Graphics2D</code> according
* to the rule last-specified-first-applied. If the current
* <code>Transform</code> is Cx, the result of composition
* with Tx is a new <code>Transform</code> Cx'. Cx' becomes the
* current <code>Transform</code> for this <code>Graphics2D</code>.
* Transforming a point p by the updated <code>Transform</code> Cx' is
* equivalent to first transforming p by Tx and then transforming
* the result by the original <code>Transform</code> Cx. In other
* words, Cx'(p) = Cx(Tx(p)). A copy of the Tx is made, if necessary,
* so further modifications to Tx do not affect rendering.
* @param Tx the <code>AffineTransform</code> object to be composed with
* the current <code>Transform</code>
* @see #setTransform
* @see AffineTransform
*/
public abstract void transform(AffineTransform Tx);
/** {@collect.stats}
* Overwrites the Transform in the <code>Graphics2D</code> context.
* WARNING: This method should <b>never</b> be used to apply a new
* coordinate transform on top of an existing transform because the
* <code>Graphics2D</code> might already have a transform that is
* needed for other purposes, such as rendering Swing
* components or applying a scaling transformation to adjust for the
* resolution of a printer.
* <p>To add a coordinate transform, use the
* <code>transform</code>, <code>rotate</code>, <code>scale</code>,
* or <code>shear</code> methods. The <code>setTransform</code>
* method is intended only for restoring the original
* <code>Graphics2D</code> transform after rendering, as shown in this
* example:
* <pre><blockquote>
* // Get the current transform
* AffineTransform saveAT = g2.getTransform();
* // Perform transformation
* g2d.transform(...);
* // Render
* g2d.draw(...);
* // Restore original transform
* g2d.setTransform(saveAT);
* </blockquote></pre>
*
* @param Tx the <code>AffineTransform</code> that was retrieved
* from the <code>getTransform</code> method
* @see #transform
* @see #getTransform
* @see AffineTransform
*/
public abstract void setTransform(AffineTransform Tx);
/** {@collect.stats}
* Returns a copy of the current <code>Transform</code> in the
* <code>Graphics2D</code> context.
* @return the current <code>AffineTransform</code> in the
* <code>Graphics2D</code> context.
* @see #transform
* @see #setTransform
*/
public abstract AffineTransform getTransform();
/** {@collect.stats}
* Returns the current <code>Paint</code> of the
* <code>Graphics2D</code> context.
* @return the current <code>Graphics2D</code> <code>Paint</code>,
* which defines a color or pattern.
* @see #setPaint
* @see java.awt.Graphics#setColor
*/
public abstract Paint getPaint();
/** {@collect.stats}
* Returns the current <code>Composite</code> in the
* <code>Graphics2D</code> context.
* @return the current <code>Graphics2D</code> <code>Composite</code>,
* which defines a compositing style.
* @see #setComposite
*/
public abstract Composite getComposite();
/** {@collect.stats}
* Sets the background color for the <code>Graphics2D</code> context.
* The background color is used for clearing a region.
* When a <code>Graphics2D</code> is constructed for a
* <code>Component</code>, the background color is
* inherited from the <code>Component</code>. Setting the background color
* in the <code>Graphics2D</code> context only affects the subsequent
* <code>clearRect</code> calls and not the background color of the
* <code>Component</code>. To change the background
* of the <code>Component</code>, use appropriate methods of
* the <code>Component</code>.
* @param color the background color that isused in
* subsequent calls to <code>clearRect</code>
* @see #getBackground
* @see java.awt.Graphics#clearRect
*/
public abstract void setBackground(Color color);
/** {@collect.stats}
* Returns the background color used for clearing a region.
* @return the current <code>Graphics2D</code> <code>Color</code>,
* which defines the background color.
* @see #setBackground
*/
public abstract Color getBackground();
/** {@collect.stats}
* Returns the current <code>Stroke</code> in the
* <code>Graphics2D</code> context.
* @return the current <code>Graphics2D</code> <code>Stroke</code>,
* which defines the line style.
* @see #setStroke
*/
public abstract Stroke getStroke();
/** {@collect.stats}
* Intersects the current <code>Clip</code> with the interior of the
* specified <code>Shape</code> and sets the <code>Clip</code> to the
* resulting intersection. The specified <code>Shape</code> is
* transformed with the current <code>Graphics2D</code>
* <code>Transform</code> before being intersected with the current
* <code>Clip</code>. This method is used to make the current
* <code>Clip</code> smaller.
* To make the <code>Clip</code> larger, use <code>setClip</code>.
* The <i>user clip</i> modified by this method is independent of the
* clipping associated with device bounds and visibility. If no clip has
* previously been set, or if the clip has been cleared using
* {@link Graphics#setClip(Shape) setClip} with a <code>null</code>
* argument, the specified <code>Shape</code> becomes the new
* user clip.
* @param s the <code>Shape</code> to be intersected with the current
* <code>Clip</code>. If <code>s</code> is <code>null</code>,
* this method clears the current <code>Clip</code>.
*/
public abstract void clip(Shape s);
/** {@collect.stats}
* Get the rendering context of the <code>Font</code> within this
* <code>Graphics2D</code> context.
* The {@link FontRenderContext}
* encapsulates application hints such as anti-aliasing and
* fractional metrics, as well as target device specific information
* such as dots-per-inch. This information should be provided by the
* application when using objects that perform typographical
* formatting, such as <code>Font</code> and
* <code>TextLayout</code>. This information should also be provided
* by applications that perform their own layout and need accurate
* measurements of various characteristics of glyphs such as advance
* and line height when various rendering hints have been applied to
* the text rendering.
*
* @return a reference to an instance of FontRenderContext.
* @see java.awt.font.FontRenderContext
* @see java.awt.Font#createGlyphVector
* @see java.awt.font.TextLayout
* @since 1.2
*/
public abstract FontRenderContext getFontRenderContext();
}
|
Java
|
/*
* Copyright (c) 1995, 2006, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code 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
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package java.awt;
import java.util.Hashtable;
import java.util.Arrays;
/** {@collect.stats}
* The <code>GridBagLayout</code> class is a flexible layout
* manager that aligns components vertically, horizontally or along their
* baseline without requiring that the components be of the same size.
* Each <code>GridBagLayout</code> object maintains a dynamic,
* rectangular grid of cells, with each component occupying
* one or more cells, called its <em>display area</em>.
* <p>
* Each component managed by a <code>GridBagLayout</code> is associated with
* an instance of {@link GridBagConstraints}. The constraints object
* specifies where a component's display area should be located on the grid
* and how the component should be positioned within its display area. In
* addition to its constraints object, the <code>GridBagLayout</code> also
* considers each component's minimum and preferred sizes in order to
* determine a component's size.
* <p>
* The overall orientation of the grid depends on the container's
* {@link ComponentOrientation} property. For horizontal left-to-right
* orientations, grid coordinate (0,0) is in the upper left corner of the
* container with x increasing to the right and y increasing downward. For
* horizontal right-to-left orientations, grid coordinate (0,0) is in the upper
* right corner of the container with x increasing to the left and y
* increasing downward.
* <p>
* To use a grid bag layout effectively, you must customize one or more
* of the <code>GridBagConstraints</code> objects that are associated
* with its components. You customize a <code>GridBagConstraints</code>
* object by setting one or more of its instance variables:
* <p>
* <dl>
* <dt>{@link GridBagConstraints#gridx},
* {@link GridBagConstraints#gridy}
* <dd>Specifies the cell containing the leading corner of the component's
* display area, where the cell at the origin of the grid has address
* <code>gridx = 0</code>,
* <code>gridy = 0</code>. For horizontal left-to-right layout,
* a component's leading corner is its upper left. For horizontal
* right-to-left layout, a component's leading corner is its upper right.
* Use <code>GridBagConstraints.RELATIVE</code> (the default value)
* to specify that the component be placed immediately following
* (along the x axis for <code>gridx</code> or the y axis for
* <code>gridy</code>) the component that was added to the container
* just before this component was added.
* <dt>{@link GridBagConstraints#gridwidth},
* {@link GridBagConstraints#gridheight}
* <dd>Specifies the number of cells in a row (for <code>gridwidth</code>)
* or column (for <code>gridheight</code>)
* in the component's display area.
* The default value is 1.
* Use <code>GridBagConstraints.REMAINDER</code> to specify
* that the component's display area will be from <code>gridx</code>
* to the last cell in the row (for <code>gridwidth</code>)
* or from <code>gridy</code> to the last cell in the column
* (for <code>gridheight</code>).
*
* Use <code>GridBagConstraints.RELATIVE</code> to specify
* that the component's display area will be from <code>gridx</code>
* to the next to the last cell in its row (for <code>gridwidth</code>
* or from <code>gridy</code> to the next to the last cell in its
* column (for <code>gridheight</code>).
*
* <dt>{@link GridBagConstraints#fill}
* <dd>Used when the component's display area
* is larger than the component's requested size
* to determine whether (and how) to resize the component.
* Possible values are
* <code>GridBagConstraints.NONE</code> (the default),
* <code>GridBagConstraints.HORIZONTAL</code>
* (make the component wide enough to fill its display area
* horizontally, but don't change its height),
* <code>GridBagConstraints.VERTICAL</code>
* (make the component tall enough to fill its display area
* vertically, but don't change its width), and
* <code>GridBagConstraints.BOTH</code>
* (make the component fill its display area entirely).
* <dt>{@link GridBagConstraints#ipadx},
* {@link GridBagConstraints#ipady}
* <dd>Specifies the component's internal padding within the layout,
* how much to add to the minimum size of the component.
* The width of the component will be at least its minimum width
* plus <code>ipadx</code> pixels. Similarly, the height of
* the component will be at least the minimum height plus
* <code>ipady</code> pixels.
* <dt>{@link GridBagConstraints#insets}
* <dd>Specifies the component's external padding, the minimum
* amount of space between the component and the edges of its display area.
* <dt>{@link GridBagConstraints#anchor}
* <dd>Specifies where the component should be positioned in its display area.
* There are three kinds of possible values: absolute, orientation-relative,
* and baseline-relative
* Orientation relative values are interpreted relative to the container's
* <code>ComponentOrientation</code> property while absolute values
* are not. Baseline relative values are calculated relative to the
* baseline. Valid values are:</dd>
* <p>
* <center><table BORDER=0 COLS=3 WIDTH=800
* SUMMARY="absolute, relative and baseline values as described above">
* <tr>
* <th><P ALIGN="LEFT">Absolute Values</th>
* <th><P ALIGN="LEFT">Orientation Relative Values</th>
* <th><P ALIGN="LEFT">Baseline Relative Values</th>
* </tr>
* <tr>
* <td>
* <li><code>GridBagConstraints.NORTH</code></li>
* <li><code>GridBagConstraints.SOUTH</code></li>
* <li><code>GridBagConstraints.WEST</code></li>
* <li><code>GridBagConstraints.EAST</code></li>
* <li><code>GridBagConstraints.NORTHWEST</code></li>
* <li><code>GridBagConstraints.NORTHEAST</code></li>
* <li><code>GridBagConstraints.SOUTHWEST</code></li>
* <li><code>GridBagConstraints.SOUTHEAST</code></li>
* <li><code>GridBagConstraints.CENTER</code> (the default)</li>
* </td>
* <td>
* <li><code>GridBagConstraints.PAGE_START</code></li>
* <li><code>GridBagConstraints.PAGE_END</code></li>
* <li><code>GridBagConstraints.LINE_START</code></li>
* <li><code>GridBagConstraints.LINE_END</code></li>
* <li><code>GridBagConstraints.FIRST_LINE_START</code></li>
* <li><code>GridBagConstraints.FIRST_LINE_END</code></li>
* <li><code>GridBagConstraints.LAST_LINE_START</code></li>
* <li><code>GridBagConstraints.LAST_LINE_END</code></li>
* </td>
* <td>
* <li><code>GridBagConstraints.BASELINE</code></li>
* <li><code>GridBagConstraints.BASELINE_LEADING</code></li>
* <li><code>GridBagConstraints.BASELINE_TRAILING</code></li>
* <li><code>GridBagConstraints.ABOVE_BASELINE</code></li>
* <li><code>GridBagConstraints.ABOVE_BASELINE_LEADING</code></li>
* <li><code>GridBagConstraints.ABOVE_BASELINE_TRAILING</code></li>
* <li><code>GridBagConstraints.BELOW_BASELINE</code></li>
* <li><code>GridBagConstraints.BELOW_BASELINE_LEADING</code></li>
* <li><code>GridBagConstraints.BELOW_BASELINE_TRAILING</code></li>
* </td>
* </tr>
* </table></center><p>
* <dt>{@link GridBagConstraints#weightx},
* {@link GridBagConstraints#weighty}
* <dd>Used to determine how to distribute space, which is
* important for specifying resizing behavior.
* Unless you specify a weight for at least one component
* in a row (<code>weightx</code>) and column (<code>weighty</code>),
* all the components clump together in the center of their container.
* This is because when the weight is zero (the default),
* the <code>GridBagLayout</code> object puts any extra space
* between its grid of cells and the edges of the container.
* </dl>
* <p>
* Each row may have a baseline; the baseline is determined by the
* components in that row that have a valid baseline and are aligned
* along the baseline (the component's anchor value is one of {@code
* BASELINE}, {@code BASELINE_LEADING} or {@code BASELINE_TRAILING}).
* If none of the components in the row has a valid baseline, the row
* does not have a baseline.
* <p>
* If a component spans rows it is aligned either to the baseline of
* the start row (if the baseline-resize behavior is {@code
* CONSTANT_ASCENT}) or the end row (if the baseline-resize behavior
* is {@code CONSTANT_DESCENT}). The row that the component is
* aligned to is called the <em>prevailing row</em>.
* <p>
* The following figure shows a baseline layout and includes a
* component that spans rows:
* <center><table summary="Baseline Layout">
* <tr ALIGN=CENTER>
* <td>
* <img src="doc-files/GridBagLayout-baseline.png"
* alt="The following text describes this graphic (Figure 1)." ALIGN=center>
* </td>
* </table></center>
* This layout consists of three components:
* <ul><li>A panel that starts in row 0 and ends in row 1. The panel
* has a baseline-resize behavior of <code>CONSTANT_DESCENT</code> and has
* an anchor of <code>BASELINE</code>. As the baseline-resize behavior
* is <code>CONSTANT_DESCENT</code> the prevailing row for the panel is
* row 1.
* <li>Two buttons, each with a baseline-resize behavior of
* <code>CENTER_OFFSET</code> and an anchor of <code>BASELINE</code>.
* </ul>
* Because the second button and the panel share the same prevailing row,
* they are both aligned along their baseline.
* <p>
* Components positioned using one of the baseline-relative values resize
* differently than when positioned using an absolute or orientation-relative
* value. How components change is dictated by how the baseline of the
* prevailing row changes. The baseline is anchored to the
* bottom of the display area if any components with the same prevailing row
* have a baseline-resize behavior of <code>CONSTANT_DESCENT</code>,
* otherwise the baseline is anchored to the top of the display area.
* The following rules dictate the resize behavior:
* <ul>
* <li>Resizable components positioned above the baseline can only
* grow as tall as the baseline. For example, if the baseline is at 100
* and anchored at the top, a resizable component positioned above the
* baseline can never grow more than 100 units.
* <li>Similarly, resizable components positioned below the baseline can
* only grow as high as the difference between the display height and the
* baseline.
* <li>Resizable components positioned on the baseline with a
* baseline-resize behavior of <code>OTHER</code> are only resized if
* the baseline at the resized size fits within the display area. If
* the baseline is such that it does not fit within the display area
* the component is not resized.
* <li>Components positioned on the baseline that do not have a
* baseline-resize behavior of <code>OTHER</code>
* can only grow as tall as {@code display height - baseline + baseline of component}.
* </ul>
* If you position a component along the baseline, but the
* component does not have a valid baseline, it will be vertically centered
* in its space. Similarly if you have positioned a component relative
* to the baseline and none of the components in the row have a valid
* baseline the component is vertically centered.
* <p>
* The following figures show ten components (all buttons)
* managed by a grid bag layout. Figure 2 shows the layout for a horizontal,
* left-to-right container and Figure 3 shows the layout for a horizontal,
* right-to-left container.
* <p>
* <center><table COLS=2 WIDTH=600 summary="layout">
* <tr ALIGN=CENTER>
* <td>
* <img src="doc-files/GridBagLayout-1.gif" alt="The preceeding text describes this graphic (Figure 1)." ALIGN=center HSPACE=10 VSPACE=7>
* </td>
* <td>
* <img src="doc-files/GridBagLayout-2.gif" alt="The preceeding text describes this graphic (Figure 2)." ALIGN=center HSPACE=10 VSPACE=7>
* </td>
* <tr ALIGN=CENTER>
* <td>Figure 2: Horizontal, Left-to-Right</td>
* <td>Figure 3: Horizontal, Right-to-Left</td>
* </tr>
* </table></center>
* <p>
* Each of the ten components has the <code>fill</code> field
* of its associated <code>GridBagConstraints</code> object
* set to <code>GridBagConstraints.BOTH</code>.
* In addition, the components have the following non-default constraints:
* <p>
* <ul>
* <li>Button1, Button2, Button3: <code>weightx = 1.0</code>
* <li>Button4: <code>weightx = 1.0</code>,
* <code>gridwidth = GridBagConstraints.REMAINDER</code>
* <li>Button5: <code>gridwidth = GridBagConstraints.REMAINDER</code>
* <li>Button6: <code>gridwidth = GridBagConstraints.RELATIVE</code>
* <li>Button7: <code>gridwidth = GridBagConstraints.REMAINDER</code>
* <li>Button8: <code>gridheight = 2</code>,
* <code>weighty = 1.0</code>
* <li>Button9, Button 10:
* <code>gridwidth = GridBagConstraints.REMAINDER</code>
* </ul>
* <p>
* Here is the code that implements the example shown above:
* <p>
* <hr><blockquote><pre>
* import java.awt.*;
* import java.util.*;
* import java.applet.Applet;
*
* public class GridBagEx1 extends Applet {
*
* protected void makebutton(String name,
* GridBagLayout gridbag,
* GridBagConstraints c) {
* Button button = new Button(name);
* gridbag.setConstraints(button, c);
* add(button);
* }
*
* public void init() {
* GridBagLayout gridbag = new GridBagLayout();
* GridBagConstraints c = new GridBagConstraints();
*
* setFont(new Font("SansSerif", Font.PLAIN, 14));
* setLayout(gridbag);
*
* c.fill = GridBagConstraints.BOTH;
* c.weightx = 1.0;
* makebutton("Button1", gridbag, c);
* makebutton("Button2", gridbag, c);
* makebutton("Button3", gridbag, c);
*
* c.gridwidth = GridBagConstraints.REMAINDER; //end row
* makebutton("Button4", gridbag, c);
*
* c.weightx = 0.0; //reset to the default
* makebutton("Button5", gridbag, c); //another row
*
* c.gridwidth = GridBagConstraints.RELATIVE; //next-to-last in row
* makebutton("Button6", gridbag, c);
*
* c.gridwidth = GridBagConstraints.REMAINDER; //end row
* makebutton("Button7", gridbag, c);
*
* c.gridwidth = 1; //reset to the default
* c.gridheight = 2;
* c.weighty = 1.0;
* makebutton("Button8", gridbag, c);
*
* c.weighty = 0.0; //reset to the default
* c.gridwidth = GridBagConstraints.REMAINDER; //end row
* c.gridheight = 1; //reset to the default
* makebutton("Button9", gridbag, c);
* makebutton("Button10", gridbag, c);
*
* setSize(300, 100);
* }
*
* public static void main(String args[]) {
* Frame f = new Frame("GridBag Layout Example");
* GridBagEx1 ex1 = new GridBagEx1();
*
* ex1.init();
*
* f.add("Center", ex1);
* f.pack();
* f.setSize(f.getPreferredSize());
* f.show();
* }
* }
* </pre></blockquote><hr>
* <p>
* @author Doug Stein
* @author Bill Spitzak (orignial NeWS & OLIT implementation)
* @see java.awt.GridBagConstraints
* @see java.awt.GridBagLayoutInfo
* @see java.awt.ComponentOrientation
* @since JDK1.0
*/
public class GridBagLayout implements LayoutManager2,
java.io.Serializable {
static final int EMPIRICMULTIPLIER = 2;
/** {@collect.stats}
* This field is no longer used to reserve arrays and keeped for backward
* compatibility. Previously, this was
* the maximum number of grid positions (both horizontal and
* vertical) that could be laid out by the grid bag layout.
* Current implementation doesn't impose any limits
* on the size of a grid.
*/
protected static final int MAXGRIDSIZE = 512;
/** {@collect.stats}
* The smallest grid that can be laid out by the grid bag layout.
*/
protected static final int MINSIZE = 1;
/** {@collect.stats}
* The preferred grid size that can be laid out by the grid bag layout.
*/
protected static final int PREFERREDSIZE = 2;
/** {@collect.stats}
* This hashtable maintains the association between
* a component and its gridbag constraints.
* The Keys in <code>comptable</code> are the components and the
* values are the instances of <code>GridBagConstraints</code>.
*
* @serial
* @see java.awt.GridBagConstraints
*/
protected Hashtable<Component,GridBagConstraints> comptable;
/** {@collect.stats}
* This field holds a gridbag constraints instance
* containing the default values, so if a component
* does not have gridbag constraints associated with
* it, then the component will be assigned a
* copy of the <code>defaultConstraints</code>.
*
* @serial
* @see #getConstraints(Component)
* @see #setConstraints(Component, GridBagConstraints)
* @see #lookupConstraints(Component)
*/
protected GridBagConstraints defaultConstraints;
/** {@collect.stats}
* This field holds the layout information
* for the gridbag. The information in this field
* is based on the most recent validation of the
* gridbag.
* If <code>layoutInfo</code> is <code>null</code>
* this indicates that there are no components in
* the gridbag or if there are components, they have
* not yet been validated.
*
* @serial
* @see #getLayoutInfo(Container, int)
*/
protected GridBagLayoutInfo layoutInfo;
/** {@collect.stats}
* This field holds the overrides to the column minimum
* width. If this field is non-<code>null</code> the values are
* applied to the gridbag after all of the minimum columns
* widths have been calculated.
* If columnWidths has more elements than the number of
* columns, columns are added to the gridbag to match
* the number of elements in columnWidth.
*
* @serial
* @see #getLayoutDimensions()
*/
public int columnWidths[];
/** {@collect.stats}
* This field holds the overrides to the row minimum
* heights. If this field is non-<code>null</code> the values are
* applied to the gridbag after all of the minimum row
* heights have been calculated.
* If <code>rowHeights</code> has more elements than the number of
* rows, rowa are added to the gridbag to match
* the number of elements in <code>rowHeights</code>.
*
* @serial
* @see #getLayoutDimensions()
*/
public int rowHeights[];
/** {@collect.stats}
* This field holds the overrides to the column weights.
* If this field is non-<code>null</code> the values are
* applied to the gridbag after all of the columns
* weights have been calculated.
* If <code>columnWeights[i]</code> > weight for column i, then
* column i is assigned the weight in <code>columnWeights[i]</code>.
* If <code>columnWeights</code> has more elements than the number
* of columns, the excess elements are ignored - they do
* not cause more columns to be created.
*
* @serial
*/
public double columnWeights[];
/** {@collect.stats}
* This field holds the overrides to the row weights.
* If this field is non-<code>null</code> the values are
* applied to the gridbag after all of the rows
* weights have been calculated.
* If <code>rowWeights[i]</code> > weight for row i, then
* row i is assigned the weight in <code>rowWeights[i]</code>.
* If <code>rowWeights</code> has more elements than the number
* of rows, the excess elements are ignored - they do
* not cause more rows to be created.
*
* @serial
*/
public double rowWeights[];
/** {@collect.stats}
* The component being positioned. This is set before calling into
* <code>adjustForGravity</code>.
*/
private Component componentAdjusting;
/** {@collect.stats}
* Creates a grid bag layout manager.
*/
public GridBagLayout () {
comptable = new Hashtable<Component,GridBagConstraints>();
defaultConstraints = new GridBagConstraints();
}
/** {@collect.stats}
* Sets the constraints for the specified component in this layout.
* @param comp the component to be modified
* @param constraints the constraints to be applied
*/
public void setConstraints(Component comp, GridBagConstraints constraints) {
comptable.put(comp, (GridBagConstraints)constraints.clone());
}
/** {@collect.stats}
* Gets the constraints for the specified component. A copy of
* the actual <code>GridBagConstraints</code> object is returned.
* @param comp the component to be queried
* @return the constraint for the specified component in this
* grid bag layout; a copy of the actual constraint
* object is returned
*/
public GridBagConstraints getConstraints(Component comp) {
GridBagConstraints constraints = comptable.get(comp);
if (constraints == null) {
setConstraints(comp, defaultConstraints);
constraints = comptable.get(comp);
}
return (GridBagConstraints)constraints.clone();
}
/** {@collect.stats}
* Retrieves the constraints for the specified component.
* The return value is not a copy, but is the actual
* <code>GridBagConstraints</code> object used by the layout mechanism.
* <p>
* If <code>comp</code> is not in the <code>GridBagLayout</code>,
* a set of default <code>GridBagConstraints</code> are returned.
* A <code>comp</code> value of <code>null</code> is invalid
* and returns <code>null</code>.
*
* @param comp the component to be queried
* @return the contraints for the specified component
*/
protected GridBagConstraints lookupConstraints(Component comp) {
GridBagConstraints constraints = comptable.get(comp);
if (constraints == null) {
setConstraints(comp, defaultConstraints);
constraints = comptable.get(comp);
}
return constraints;
}
/** {@collect.stats}
* Removes the constraints for the specified component in this layout
* @param comp the component to be modified
*/
private void removeConstraints(Component comp) {
comptable.remove(comp);
}
/** {@collect.stats}
* Determines the origin of the layout area, in the graphics coordinate
* space of the target container. This value represents the pixel
* coordinates of the top-left corner of the layout area regardless of
* the <code>ComponentOrientation</code> value of the container. This
* is distinct from the grid origin given by the cell coordinates (0,0).
* Most applications do not call this method directly.
* @return the graphics origin of the cell in the top-left
* corner of the layout grid
* @see java.awt.ComponentOrientation
* @since JDK1.1
*/
public Point getLayoutOrigin () {
Point origin = new Point(0,0);
if (layoutInfo != null) {
origin.x = layoutInfo.startx;
origin.y = layoutInfo.starty;
}
return origin;
}
/** {@collect.stats}
* Determines column widths and row heights for the layout grid.
* <p>
* Most applications do not call this method directly.
* @return an array of two arrays, containing the widths
* of the layout columns and
* the heights of the layout rows
* @since JDK1.1
*/
public int [][] getLayoutDimensions () {
if (layoutInfo == null)
return new int[2][0];
int dim[][] = new int [2][];
dim[0] = new int[layoutInfo.width];
dim[1] = new int[layoutInfo.height];
System.arraycopy(layoutInfo.minWidth, 0, dim[0], 0, layoutInfo.width);
System.arraycopy(layoutInfo.minHeight, 0, dim[1], 0, layoutInfo.height);
return dim;
}
/** {@collect.stats}
* Determines the weights of the layout grid's columns and rows.
* Weights are used to calculate how much a given column or row
* stretches beyond its preferred size, if the layout has extra
* room to fill.
* <p>
* Most applications do not call this method directly.
* @return an array of two arrays, representing the
* horizontal weights of the layout columns
* and the vertical weights of the layout rows
* @since JDK1.1
*/
public double [][] getLayoutWeights () {
if (layoutInfo == null)
return new double[2][0];
double weights[][] = new double [2][];
weights[0] = new double[layoutInfo.width];
weights[1] = new double[layoutInfo.height];
System.arraycopy(layoutInfo.weightX, 0, weights[0], 0, layoutInfo.width);
System.arraycopy(layoutInfo.weightY, 0, weights[1], 0, layoutInfo.height);
return weights;
}
/** {@collect.stats}
* Determines which cell in the layout grid contains the point
* specified by <code>(x, y)</code>. Each cell is identified
* by its column index (ranging from 0 to the number of columns
* minus 1) and its row index (ranging from 0 to the number of
* rows minus 1).
* <p>
* If the <code>(x, y)</code> point lies
* outside the grid, the following rules are used.
* The column index is returned as zero if <code>x</code> lies to the
* left of the layout for a left-to-right container or to the right of
* the layout for a right-to-left container. The column index is returned
* as the number of columns if <code>x</code> lies
* to the right of the layout in a left-to-right container or to the left
* in a right-to-left container.
* The row index is returned as zero if <code>y</code> lies above the
* layout, and as the number of rows if <code>y</code> lies
* below the layout. The orientation of a container is determined by its
* <code>ComponentOrientation</code> property.
* @param x the <i>x</i> coordinate of a point
* @param y the <i>y</i> coordinate of a point
* @return an ordered pair of indexes that indicate which cell
* in the layout grid contains the point
* (<i>x</i>, <i>y</i>).
* @see java.awt.ComponentOrientation
* @since JDK1.1
*/
public Point location(int x, int y) {
Point loc = new Point(0,0);
int i, d;
if (layoutInfo == null)
return loc;
d = layoutInfo.startx;
if (!rightToLeft) {
for (i=0; i<layoutInfo.width; i++) {
d += layoutInfo.minWidth[i];
if (d > x)
break;
}
} else {
for (i=layoutInfo.width-1; i>=0; i--) {
if (d > x)
break;
d += layoutInfo.minWidth[i];
}
i++;
}
loc.x = i;
d = layoutInfo.starty;
for (i=0; i<layoutInfo.height; i++) {
d += layoutInfo.minHeight[i];
if (d > y)
break;
}
loc.y = i;
return loc;
}
/** {@collect.stats}
* Has no effect, since this layout manager does not use a per-component string.
*/
public void addLayoutComponent(String name, Component comp) {
}
/** {@collect.stats}
* Adds the specified component to the layout, using the specified
* <code>constraints</code> object. Note that constraints
* are mutable and are, therefore, cloned when cached.
*
* @param comp the component to be added
* @param constraints an object that determines how
* the component is added to the layout
* @exception IllegalArgumentException if <code>constraints</code>
* is not a <code>GridBagConstraint</code>
*/
public void addLayoutComponent(Component comp, Object constraints) {
if (constraints instanceof GridBagConstraints) {
setConstraints(comp, (GridBagConstraints)constraints);
} else if (constraints != null) {
throw new IllegalArgumentException("cannot add to layout: constraints must be a GridBagConstraint");
}
}
/** {@collect.stats}
* Removes the specified component from this layout.
* <p>
* Most applications do not call this method directly.
* @param comp the component to be removed.
* @see java.awt.Container#remove(java.awt.Component)
* @see java.awt.Container#removeAll()
*/
public void removeLayoutComponent(Component comp) {
removeConstraints(comp);
}
/** {@collect.stats}
* Determines the preferred size of the <code>parent</code>
* container using this grid bag layout.
* <p>
* Most applications do not call this method directly.
*
* @param parent the container in which to do the layout
* @see java.awt.Container#getPreferredSize
* @return the preferred size of the <code>parent</code>
* container
*/
public Dimension preferredLayoutSize(Container parent) {
GridBagLayoutInfo info = getLayoutInfo(parent, PREFERREDSIZE);
return getMinSize(parent, info);
}
/** {@collect.stats}
* Determines the minimum size of the <code>parent</code> container
* using this grid bag layout.
* <p>
* Most applications do not call this method directly.
* @param parent the container in which to do the layout
* @see java.awt.Container#doLayout
* @return the minimum size of the <code>parent</code> container
*/
public Dimension minimumLayoutSize(Container parent) {
GridBagLayoutInfo info = getLayoutInfo(parent, MINSIZE);
return getMinSize(parent, info);
}
/** {@collect.stats}
* Returns the maximum dimensions for this layout given the components
* in the specified target container.
* @param target the container which needs to be laid out
* @see Container
* @see #minimumLayoutSize(Container)
* @see #preferredLayoutSize(Container)
* @return the maximum dimensions for this layout
*/
public Dimension maximumLayoutSize(Container target) {
return new Dimension(Integer.MAX_VALUE, Integer.MAX_VALUE);
}
/** {@collect.stats}
* Returns the alignment along the x axis. This specifies how
* the component would like to be aligned relative to other
* components. The value should be a number between 0 and 1
* where 0 represents alignment along the origin, 1 is aligned
* the furthest away from the origin, 0.5 is centered, etc.
* <p>
* @return the value <code>0.5f</code> to indicate centered
*/
public float getLayoutAlignmentX(Container parent) {
return 0.5f;
}
/** {@collect.stats}
* Returns the alignment along the y axis. This specifies how
* the component would like to be aligned relative to other
* components. The value should be a number between 0 and 1
* where 0 represents alignment along the origin, 1 is aligned
* the furthest away from the origin, 0.5 is centered, etc.
* <p>
* @return the value <code>0.5f</code> to indicate centered
*/
public float getLayoutAlignmentY(Container parent) {
return 0.5f;
}
/** {@collect.stats}
* Invalidates the layout, indicating that if the layout manager
* has cached information it should be discarded.
*/
public void invalidateLayout(Container target) {
}
/** {@collect.stats}
* Lays out the specified container using this grid bag layout.
* This method reshapes components in the specified container in
* order to satisfy the contraints of this <code>GridBagLayout</code>
* object.
* <p>
* Most applications do not call this method directly.
* @param parent the container in which to do the layout
* @see java.awt.Container
* @see java.awt.Container#doLayout
*/
public void layoutContainer(Container parent) {
arrangeGrid(parent);
}
/** {@collect.stats}
* Returns a string representation of this grid bag layout's values.
* @return a string representation of this grid bag layout.
*/
public String toString() {
return getClass().getName();
}
/** {@collect.stats}
* Print the layout information. Useful for debugging.
*/
/* DEBUG
*
* protected void dumpLayoutInfo(GridBagLayoutInfo s) {
* int x;
*
* System.out.println("Col\tWidth\tWeight");
* for (x=0; x<s.width; x++) {
* System.out.println(x + "\t" +
* s.minWidth[x] + "\t" +
* s.weightX[x]);
* }
* System.out.println("Row\tHeight\tWeight");
* for (x=0; x<s.height; x++) {
* System.out.println(x + "\t" +
* s.minHeight[x] + "\t" +
* s.weightY[x]);
* }
* }
*/
/** {@collect.stats}
* Print the layout constraints. Useful for debugging.
*/
/* DEBUG
*
* protected void dumpConstraints(GridBagConstraints constraints) {
* System.out.println(
* "wt " +
* constraints.weightx +
* " " +
* constraints.weighty +
* ", " +
*
* "box " +
* constraints.gridx +
* " " +
* constraints.gridy +
* " " +
* constraints.gridwidth +
* " " +
* constraints.gridheight +
* ", " +
*
* "min " +
* constraints.minWidth +
* " " +
* constraints.minHeight +
* ", " +
*
* "pad " +
* constraints.insets.bottom +
* " " +
* constraints.insets.left +
* " " +
* constraints.insets.right +
* " " +
* constraints.insets.top +
* " " +
* constraints.ipadx +
* " " +
* constraints.ipady);
* }
*/
/** {@collect.stats}
* Fills in an instance of <code>GridBagLayoutInfo</code> for the
* current set of managed children. This requires three passes through the
* set of children:
*
* <ol>
* <li>Figure out the dimensions of the layout grid.
* <li>Determine which cells the components occupy.
* <li>Distribute the weights and min sizes amoung the rows/columns.
* </ol>
*
* This also caches the minsizes for all the children when they are
* first encountered (so subsequent loops don't need to ask again).
* <p>
* This method should only be used internally by
* <code>GridBagLayout</code>.
*
* @param parent the layout container
* @param sizeflag either <code>PREFERREDSIZE</code> or
* <code>MINSIZE</code>
* @return the <code>GridBagLayoutInfo</code> for the set of children
* @since 1.4
*/
protected GridBagLayoutInfo getLayoutInfo(Container parent, int sizeflag) {
return GetLayoutInfo(parent, sizeflag);
}
/*
* Calculate maximum array sizes to allocate arrays without ensureCapacity
* we may use preCalculated sizes in whole class because of upper estimation of
* maximumArrayXIndex and maximumArrayYIndex.
*/
private long[] preInitMaximumArraySizes(Container parent){
Component components[] = parent.getComponents();
Component comp;
GridBagConstraints constraints;
int curX, curY;
int curWidth, curHeight;
int preMaximumArrayXIndex = 0;
int preMaximumArrayYIndex = 0;
long [] returnArray = new long[2];
for (int compId = 0 ; compId < components.length ; compId++) {
comp = components[compId];
if (!comp.isVisible()) {
continue;
}
constraints = lookupConstraints(comp);
curX = constraints.gridx;
curY = constraints.gridy;
curWidth = constraints.gridwidth;
curHeight = constraints.gridheight;
// -1==RELATIVE, means that column|row equals to previously added component,
// since each next Component with gridx|gridy == RELATIVE starts from
// previous position, so we should start from previous component which
// already used in maximumArray[X|Y]Index calculation. We could just increase
// maximum by 1 to handle situation when component with gridx=-1 was added.
if (curX < 0){
curX = ++preMaximumArrayYIndex;
}
if (curY < 0){
curY = ++preMaximumArrayXIndex;
}
// gridwidth|gridheight may be equal to RELATIVE (-1) or REMAINDER (0)
// in any case using 1 instead of 0 or -1 should be sufficient to for
// correct maximumArraySizes calculation
if (curWidth <= 0){
curWidth = 1;
}
if (curHeight <= 0){
curHeight = 1;
}
preMaximumArrayXIndex = Math.max(curY + curHeight, preMaximumArrayXIndex);
preMaximumArrayYIndex = Math.max(curX + curWidth, preMaximumArrayYIndex);
} //for (components) loop
// Must specify index++ to allocate well-working arrays.
/* fix for 4623196.
* now return long array instead of Point
*/
returnArray[0] = preMaximumArrayXIndex;
returnArray[1] = preMaximumArrayYIndex;
return returnArray;
} //PreInitMaximumSizes
/** {@collect.stats}
* This method is obsolete and supplied for backwards
* compatability only; new code should call {@link
* #getLayoutInfo(java.awt.Container, int) getLayoutInfo} instead.
* This method is the same as <code>getLayoutInfo</code>;
* refer to <code>getLayoutInfo</code> for details on parameters
* and return value.
*/
protected GridBagLayoutInfo GetLayoutInfo(Container parent, int sizeflag) {
synchronized (parent.getTreeLock()) {
GridBagLayoutInfo r;
Component comp;
GridBagConstraints constraints;
Dimension d;
Component components[] = parent.getComponents();
// Code below will address index curX+curWidth in the case of yMaxArray, weightY
// ( respectively curY+curHeight for xMaxArray, weightX ) where
// curX in 0 to preInitMaximumArraySizes.y
// Thus, the maximum index that could
// be calculated in the following code is curX+curX.
// EmpericMultier equals 2 because of this.
int layoutWidth, layoutHeight;
int []xMaxArray;
int []yMaxArray;
int compindex, i, k, px, py, pixels_diff, nextSize;
int curX = 0; // constraints.gridx
int curY = 0; // constraints.gridy
int curWidth = 1; // constraints.gridwidth
int curHeight = 1; // constraints.gridheight
int curRow, curCol;
double weight_diff, weight;
int maximumArrayXIndex = 0;
int maximumArrayYIndex = 0;
int anchor;
/*
* Pass #1
*
* Figure out the dimensions of the layout grid (use a value of 1 for
* zero or negative widths and heights).
*/
layoutWidth = layoutHeight = 0;
curRow = curCol = -1;
long [] arraySizes = preInitMaximumArraySizes(parent);
/* fix for 4623196.
* If user try to create a very big grid we can
* get NegativeArraySizeException because of integer value
* overflow (EMPIRICMULTIPLIER*gridSize might be more then Integer.MAX_VALUE).
* We need to detect this situation and try to create a
* grid with Integer.MAX_VALUE size instead.
*/
maximumArrayXIndex = (EMPIRICMULTIPLIER * arraySizes[0] > Integer.MAX_VALUE )? Integer.MAX_VALUE : EMPIRICMULTIPLIER*(int)arraySizes[0];
maximumArrayYIndex = (EMPIRICMULTIPLIER * arraySizes[1] > Integer.MAX_VALUE )? Integer.MAX_VALUE : EMPIRICMULTIPLIER*(int)arraySizes[1];
if (rowHeights != null){
maximumArrayXIndex = Math.max(maximumArrayXIndex, rowHeights.length);
}
if (columnWidths != null){
maximumArrayYIndex = Math.max(maximumArrayYIndex, columnWidths.length);
}
xMaxArray = new int[maximumArrayXIndex];
yMaxArray = new int[maximumArrayYIndex];
boolean hasBaseline = false;
for (compindex = 0 ; compindex < components.length ; compindex++) {
comp = components[compindex];
if (!comp.isVisible())
continue;
constraints = lookupConstraints(comp);
curX = constraints.gridx;
curY = constraints.gridy;
curWidth = constraints.gridwidth;
if (curWidth <= 0)
curWidth = 1;
curHeight = constraints.gridheight;
if (curHeight <= 0)
curHeight = 1;
/* If x or y is negative, then use relative positioning: */
if (curX < 0 && curY < 0) {
if (curRow >= 0)
curY = curRow;
else if (curCol >= 0)
curX = curCol;
else
curY = 0;
}
if (curX < 0) {
px = 0;
for (i = curY; i < (curY + curHeight); i++) {
px = Math.max(px, xMaxArray[i]);
}
curX = px - curX - 1;
if(curX < 0)
curX = 0;
}
else if (curY < 0) {
py = 0;
for (i = curX; i < (curX + curWidth); i++) {
py = Math.max(py, yMaxArray[i]);
}
curY = py - curY - 1;
if(curY < 0)
curY = 0;
}
/* Adjust the grid width and height
* fix for 5005945: unneccessary loops removed
*/
px = curX + curWidth;
if (layoutWidth < px) {
layoutWidth = px;
}
py = curY + curHeight;
if (layoutHeight < py) {
layoutHeight = py;
}
/* Adjust xMaxArray and yMaxArray */
for (i = curX; i < (curX + curWidth); i++) {
yMaxArray[i] =py;
}
for (i = curY; i < (curY + curHeight); i++) {
xMaxArray[i] = px;
}
/* Cache the current slave's size. */
if (sizeflag == PREFERREDSIZE)
d = comp.getPreferredSize();
else
d = comp.getMinimumSize();
constraints.minWidth = d.width;
constraints.minHeight = d.height;
if (calculateBaseline(comp, constraints, d)) {
hasBaseline = true;
}
/* Zero width and height must mean that this is the last item (or
* else something is wrong). */
if (constraints.gridheight == 0 && constraints.gridwidth == 0)
curRow = curCol = -1;
/* Zero width starts a new row */
if (constraints.gridheight == 0 && curRow < 0)
curCol = curX + curWidth;
/* Zero height starts a new column */
else if (constraints.gridwidth == 0 && curCol < 0)
curRow = curY + curHeight;
} //for (components) loop
/*
* Apply minimum row/column dimensions
*/
if (columnWidths != null && layoutWidth < columnWidths.length)
layoutWidth = columnWidths.length;
if (rowHeights != null && layoutHeight < rowHeights.length)
layoutHeight = rowHeights.length;
r = new GridBagLayoutInfo(layoutWidth, layoutHeight);
/*
* Pass #2
*
* Negative values for gridX are filled in with the current x value.
* Negative values for gridY are filled in with the current y value.
* Negative or zero values for gridWidth and gridHeight end the current
* row or column, respectively.
*/
curRow = curCol = -1;
Arrays.fill(xMaxArray, 0);
Arrays.fill(yMaxArray, 0);
int[] maxAscent = null;
int[] maxDescent = null;
short[] baselineType = null;
if (hasBaseline) {
r.maxAscent = maxAscent = new int[layoutHeight];
r.maxDescent = maxDescent = new int[layoutHeight];
r.baselineType = baselineType = new short[layoutHeight];
r.hasBaseline = true;
}
for (compindex = 0 ; compindex < components.length ; compindex++) {
comp = components[compindex];
if (!comp.isVisible())
continue;
constraints = lookupConstraints(comp);
curX = constraints.gridx;
curY = constraints.gridy;
curWidth = constraints.gridwidth;
curHeight = constraints.gridheight;
/* If x or y is negative, then use relative positioning: */
if (curX < 0 && curY < 0) {
if(curRow >= 0)
curY = curRow;
else if(curCol >= 0)
curX = curCol;
else
curY = 0;
}
if (curX < 0) {
if (curHeight <= 0) {
curHeight += r.height - curY;
if (curHeight < 1)
curHeight = 1;
}
px = 0;
for (i = curY; i < (curY + curHeight); i++)
px = Math.max(px, xMaxArray[i]);
curX = px - curX - 1;
if(curX < 0)
curX = 0;
}
else if (curY < 0) {
if (curWidth <= 0) {
curWidth += r.width - curX;
if (curWidth < 1)
curWidth = 1;
}
py = 0;
for (i = curX; i < (curX + curWidth); i++){
py = Math.max(py, yMaxArray[i]);
}
curY = py - curY - 1;
if(curY < 0)
curY = 0;
}
if (curWidth <= 0) {
curWidth += r.width - curX;
if (curWidth < 1)
curWidth = 1;
}
if (curHeight <= 0) {
curHeight += r.height - curY;
if (curHeight < 1)
curHeight = 1;
}
px = curX + curWidth;
py = curY + curHeight;
for (i = curX; i < (curX + curWidth); i++) { yMaxArray[i] = py; }
for (i = curY; i < (curY + curHeight); i++) { xMaxArray[i] = px; }
/* Make negative sizes start a new row/column */
if (constraints.gridheight == 0 && constraints.gridwidth == 0)
curRow = curCol = -1;
if (constraints.gridheight == 0 && curRow < 0)
curCol = curX + curWidth;
else if (constraints.gridwidth == 0 && curCol < 0)
curRow = curY + curHeight;
/* Assign the new values to the gridbag slave */
constraints.tempX = curX;
constraints.tempY = curY;
constraints.tempWidth = curWidth;
constraints.tempHeight = curHeight;
anchor = constraints.anchor;
if (hasBaseline) {
switch(anchor) {
case GridBagConstraints.BASELINE:
case GridBagConstraints.BASELINE_LEADING:
case GridBagConstraints.BASELINE_TRAILING:
if (constraints.ascent >= 0) {
if (curHeight == 1) {
maxAscent[curY] =
Math.max(maxAscent[curY],
constraints.ascent);
maxDescent[curY] =
Math.max(maxDescent[curY],
constraints.descent);
}
else {
if (constraints.baselineResizeBehavior ==
Component.BaselineResizeBehavior.
CONSTANT_DESCENT) {
maxDescent[curY + curHeight - 1] =
Math.max(maxDescent[curY + curHeight
- 1],
constraints.descent);
}
else {
maxAscent[curY] = Math.max(maxAscent[curY],
constraints.ascent);
}
}
if (constraints.baselineResizeBehavior ==
Component.BaselineResizeBehavior.CONSTANT_DESCENT) {
baselineType[curY + curHeight - 1] |=
(1 << constraints.
baselineResizeBehavior.ordinal());
}
else {
baselineType[curY] |= (1 << constraints.
baselineResizeBehavior.ordinal());
}
}
break;
case GridBagConstraints.ABOVE_BASELINE:
case GridBagConstraints.ABOVE_BASELINE_LEADING:
case GridBagConstraints.ABOVE_BASELINE_TRAILING:
// Component positioned above the baseline.
// To make the bottom edge of the component aligned
// with the baseline the bottom inset is
// added to the descent, the rest to the ascent.
pixels_diff = constraints.minHeight +
constraints.insets.top +
constraints.ipady;
maxAscent[curY] = Math.max(maxAscent[curY],
pixels_diff);
maxDescent[curY] = Math.max(maxDescent[curY],
constraints.insets.bottom);
break;
case GridBagConstraints.BELOW_BASELINE:
case GridBagConstraints.BELOW_BASELINE_LEADING:
case GridBagConstraints.BELOW_BASELINE_TRAILING:
// Component positioned below the baseline.
// To make the top edge of the component aligned
// with the baseline the top inset is
// added to the ascent, the rest to the descent.
pixels_diff = constraints.minHeight +
constraints.insets.bottom + constraints.ipady;
maxDescent[curY] = Math.max(maxDescent[curY],
pixels_diff);
maxAscent[curY] = Math.max(maxAscent[curY],
constraints.insets.top);
break;
}
}
}
r.weightX = new double[maximumArrayYIndex];
r.weightY = new double[maximumArrayXIndex];
r.minWidth = new int[maximumArrayYIndex];
r.minHeight = new int[maximumArrayXIndex];
/*
* Apply minimum row/column dimensions and weights
*/
if (columnWidths != null)
System.arraycopy(columnWidths, 0, r.minWidth, 0, columnWidths.length);
if (rowHeights != null)
System.arraycopy(rowHeights, 0, r.minHeight, 0, rowHeights.length);
if (columnWeights != null)
System.arraycopy(columnWeights, 0, r.weightX, 0, Math.min(r.weightX.length, columnWeights.length));
if (rowWeights != null)
System.arraycopy(rowWeights, 0, r.weightY, 0, Math.min(r.weightY.length, rowWeights.length));
/*
* Pass #3
*
* Distribute the minimun widths and weights:
*/
nextSize = Integer.MAX_VALUE;
for (i = 1;
i != Integer.MAX_VALUE;
i = nextSize, nextSize = Integer.MAX_VALUE) {
for (compindex = 0 ; compindex < components.length ; compindex++) {
comp = components[compindex];
if (!comp.isVisible())
continue;
constraints = lookupConstraints(comp);
if (constraints.tempWidth == i) {
px = constraints.tempX + constraints.tempWidth; /* right column */
/*
* Figure out if we should use this slave\'s weight. If the weight
* is less than the total weight spanned by the width of the cell,
* then discard the weight. Otherwise split the difference
* according to the existing weights.
*/
weight_diff = constraints.weightx;
for (k = constraints.tempX; k < px; k++)
weight_diff -= r.weightX[k];
if (weight_diff > 0.0) {
weight = 0.0;
for (k = constraints.tempX; k < px; k++)
weight += r.weightX[k];
for (k = constraints.tempX; weight > 0.0 && k < px; k++) {
double wt = r.weightX[k];
double dx = (wt * weight_diff) / weight;
r.weightX[k] += dx;
weight_diff -= dx;
weight -= wt;
}
/* Assign the remainder to the rightmost cell */
r.weightX[px-1] += weight_diff;
}
/*
* Calculate the minWidth array values.
* First, figure out how wide the current slave needs to be.
* Then, see if it will fit within the current minWidth values.
* If it will not fit, add the difference according to the
* weightX array.
*/
pixels_diff =
constraints.minWidth + constraints.ipadx +
constraints.insets.left + constraints.insets.right;
for (k = constraints.tempX; k < px; k++)
pixels_diff -= r.minWidth[k];
if (pixels_diff > 0) {
weight = 0.0;
for (k = constraints.tempX; k < px; k++)
weight += r.weightX[k];
for (k = constraints.tempX; weight > 0.0 && k < px; k++) {
double wt = r.weightX[k];
int dx = (int)((wt * ((double)pixels_diff)) / weight);
r.minWidth[k] += dx;
pixels_diff -= dx;
weight -= wt;
}
/* Any leftovers go into the rightmost cell */
r.minWidth[px-1] += pixels_diff;
}
}
else if (constraints.tempWidth > i && constraints.tempWidth < nextSize)
nextSize = constraints.tempWidth;
if (constraints.tempHeight == i) {
py = constraints.tempY + constraints.tempHeight; /* bottom row */
/*
* Figure out if we should use this slave's weight. If the weight
* is less than the total weight spanned by the height of the cell,
* then discard the weight. Otherwise split it the difference
* according to the existing weights.
*/
weight_diff = constraints.weighty;
for (k = constraints.tempY; k < py; k++)
weight_diff -= r.weightY[k];
if (weight_diff > 0.0) {
weight = 0.0;
for (k = constraints.tempY; k < py; k++)
weight += r.weightY[k];
for (k = constraints.tempY; weight > 0.0 && k < py; k++) {
double wt = r.weightY[k];
double dy = (wt * weight_diff) / weight;
r.weightY[k] += dy;
weight_diff -= dy;
weight -= wt;
}
/* Assign the remainder to the bottom cell */
r.weightY[py-1] += weight_diff;
}
/*
* Calculate the minHeight array values.
* First, figure out how tall the current slave needs to be.
* Then, see if it will fit within the current minHeight values.
* If it will not fit, add the difference according to the
* weightY array.
*/
pixels_diff = -1;
if (hasBaseline) {
switch(constraints.anchor) {
case GridBagConstraints.BASELINE:
case GridBagConstraints.BASELINE_LEADING:
case GridBagConstraints.BASELINE_TRAILING:
if (constraints.ascent >= 0) {
if (constraints.tempHeight == 1) {
pixels_diff =
maxAscent[constraints.tempY] +
maxDescent[constraints.tempY];
}
else if (constraints.baselineResizeBehavior !=
Component.BaselineResizeBehavior.
CONSTANT_DESCENT) {
pixels_diff =
maxAscent[constraints.tempY] +
constraints.descent;
}
else {
pixels_diff = constraints.ascent +
maxDescent[constraints.tempY +
constraints.tempHeight - 1];
}
}
break;
case GridBagConstraints.ABOVE_BASELINE:
case GridBagConstraints.ABOVE_BASELINE_LEADING:
case GridBagConstraints.ABOVE_BASELINE_TRAILING:
pixels_diff = constraints.insets.top +
constraints.minHeight +
constraints.ipady +
maxDescent[constraints.tempY];
break;
case GridBagConstraints.BELOW_BASELINE:
case GridBagConstraints.BELOW_BASELINE_LEADING:
case GridBagConstraints.BELOW_BASELINE_TRAILING:
pixels_diff = maxAscent[constraints.tempY] +
constraints.minHeight +
constraints.insets.bottom +
constraints.ipady;
break;
}
}
if (pixels_diff == -1) {
pixels_diff =
constraints.minHeight + constraints.ipady +
constraints.insets.top +
constraints.insets.bottom;
}
for (k = constraints.tempY; k < py; k++)
pixels_diff -= r.minHeight[k];
if (pixels_diff > 0) {
weight = 0.0;
for (k = constraints.tempY; k < py; k++)
weight += r.weightY[k];
for (k = constraints.tempY; weight > 0.0 && k < py; k++) {
double wt = r.weightY[k];
int dy = (int)((wt * ((double)pixels_diff)) / weight);
r.minHeight[k] += dy;
pixels_diff -= dy;
weight -= wt;
}
/* Any leftovers go into the bottom cell */
r.minHeight[py-1] += pixels_diff;
}
}
else if (constraints.tempHeight > i &&
constraints.tempHeight < nextSize)
nextSize = constraints.tempHeight;
}
}
return r;
}
} //getLayoutInfo()
/** {@collect.stats}
* Calculate the baseline for the specified component.
* If {@code c} is positioned along it's baseline, the baseline is
* obtained and the {@code constraints} ascent, descent and
* baseline resize behavior are set from the component; and true is
* returned. Otherwise false is returned.
*/
private boolean calculateBaseline(Component c,
GridBagConstraints constraints,
Dimension size) {
int anchor = constraints.anchor;
if (anchor == GridBagConstraints.BASELINE ||
anchor == GridBagConstraints.BASELINE_LEADING ||
anchor == GridBagConstraints.BASELINE_TRAILING) {
// Apply the padding to the component, then ask for the baseline.
int w = size.width + constraints.ipadx;
int h = size.height + constraints.ipady;
constraints.ascent = c.getBaseline(w, h);
if (constraints.ascent >= 0) {
// Component has a baseline
int baseline = constraints.ascent;
// Adjust the ascent and descent to include the insets.
constraints.descent = h - constraints.ascent +
constraints.insets.bottom;
constraints.ascent += constraints.insets.top;
constraints.baselineResizeBehavior =
c.getBaselineResizeBehavior();
constraints.centerPadding = 0;
if (constraints.baselineResizeBehavior == Component.
BaselineResizeBehavior.CENTER_OFFSET) {
// Component has a baseline resize behavior of
// CENTER_OFFSET, calculate centerPadding and
// centerOffset (see the description of
// CENTER_OFFSET in the enum for detais on this
// algorithm).
int nextBaseline = c.getBaseline(w, h + 1);
constraints.centerOffset = baseline - h / 2;
if (h % 2 == 0) {
if (baseline != nextBaseline) {
constraints.centerPadding = 1;
}
}
else if (baseline == nextBaseline){
constraints.centerOffset--;
constraints.centerPadding = 1;
}
}
}
return true;
}
else {
constraints.ascent = -1;
return false;
}
}
/** {@collect.stats}
* Adjusts the x, y, width, and height fields to the correct
* values depending on the constraint geometry and pads.
* This method should only be used internally by
* <code>GridBagLayout</code>.
*
* @param constraints the constraints to be applied
* @param r the <code>Rectangle</code> to be adjusted
* @since 1.4
*/
protected void adjustForGravity(GridBagConstraints constraints,
Rectangle r) {
AdjustForGravity(constraints, r);
}
/** {@collect.stats}
* This method is obsolete and supplied for backwards
* compatability only; new code should call {@link
* #adjustForGravity(java.awt.GridBagConstraints, java.awt.Rectangle)
* adjustForGravity} instead.
* This method is the same as <code>adjustForGravity</code>;
* refer to <code>adjustForGravity</code> for details
* on parameters.
*/
protected void AdjustForGravity(GridBagConstraints constraints,
Rectangle r) {
int diffx, diffy;
int cellY = r.y;
int cellHeight = r.height;
if (!rightToLeft) {
r.x += constraints.insets.left;
} else {
r.x -= r.width - constraints.insets.right;
}
r.width -= (constraints.insets.left + constraints.insets.right);
r.y += constraints.insets.top;
r.height -= (constraints.insets.top + constraints.insets.bottom);
diffx = 0;
if ((constraints.fill != GridBagConstraints.HORIZONTAL &&
constraints.fill != GridBagConstraints.BOTH)
&& (r.width > (constraints.minWidth + constraints.ipadx))) {
diffx = r.width - (constraints.minWidth + constraints.ipadx);
r.width = constraints.minWidth + constraints.ipadx;
}
diffy = 0;
if ((constraints.fill != GridBagConstraints.VERTICAL &&
constraints.fill != GridBagConstraints.BOTH)
&& (r.height > (constraints.minHeight + constraints.ipady))) {
diffy = r.height - (constraints.minHeight + constraints.ipady);
r.height = constraints.minHeight + constraints.ipady;
}
switch (constraints.anchor) {
case GridBagConstraints.BASELINE:
r.x += diffx/2;
alignOnBaseline(constraints, r, cellY, cellHeight);
break;
case GridBagConstraints.BASELINE_LEADING:
if (rightToLeft) {
r.x += diffx;
}
alignOnBaseline(constraints, r, cellY, cellHeight);
break;
case GridBagConstraints.BASELINE_TRAILING:
if (!rightToLeft) {
r.x += diffx;
}
alignOnBaseline(constraints, r, cellY, cellHeight);
break;
case GridBagConstraints.ABOVE_BASELINE:
r.x += diffx/2;
alignAboveBaseline(constraints, r, cellY, cellHeight);
break;
case GridBagConstraints.ABOVE_BASELINE_LEADING:
if (rightToLeft) {
r.x += diffx;
}
alignAboveBaseline(constraints, r, cellY, cellHeight);
break;
case GridBagConstraints.ABOVE_BASELINE_TRAILING:
if (!rightToLeft) {
r.x += diffx;
}
alignAboveBaseline(constraints, r, cellY, cellHeight);
break;
case GridBagConstraints.BELOW_BASELINE:
r.x += diffx/2;
alignBelowBaseline(constraints, r, cellY, cellHeight);
break;
case GridBagConstraints.BELOW_BASELINE_LEADING:
if (rightToLeft) {
r.x += diffx;
}
alignBelowBaseline(constraints, r, cellY, cellHeight);
break;
case GridBagConstraints.BELOW_BASELINE_TRAILING:
if (!rightToLeft) {
r.x += diffx;
}
alignBelowBaseline(constraints, r, cellY, cellHeight);
break;
case GridBagConstraints.CENTER:
r.x += diffx/2;
r.y += diffy/2;
break;
case GridBagConstraints.PAGE_START:
case GridBagConstraints.NORTH:
r.x += diffx/2;
break;
case GridBagConstraints.NORTHEAST:
r.x += diffx;
break;
case GridBagConstraints.EAST:
r.x += diffx;
r.y += diffy/2;
break;
case GridBagConstraints.SOUTHEAST:
r.x += diffx;
r.y += diffy;
break;
case GridBagConstraints.PAGE_END:
case GridBagConstraints.SOUTH:
r.x += diffx/2;
r.y += diffy;
break;
case GridBagConstraints.SOUTHWEST:
r.y += diffy;
break;
case GridBagConstraints.WEST:
r.y += diffy/2;
break;
case GridBagConstraints.NORTHWEST:
break;
case GridBagConstraints.LINE_START:
if (rightToLeft) {
r.x += diffx;
}
r.y += diffy/2;
break;
case GridBagConstraints.LINE_END:
if (!rightToLeft) {
r.x += diffx;
}
r.y += diffy/2;
break;
case GridBagConstraints.FIRST_LINE_START:
if (rightToLeft) {
r.x += diffx;
}
break;
case GridBagConstraints.FIRST_LINE_END:
if (!rightToLeft) {
r.x += diffx;
}
break;
case GridBagConstraints.LAST_LINE_START:
if (rightToLeft) {
r.x += diffx;
}
r.y += diffy;
break;
case GridBagConstraints.LAST_LINE_END:
if (!rightToLeft) {
r.x += diffx;
}
r.y += diffy;
break;
default:
throw new IllegalArgumentException("illegal anchor value");
}
}
/** {@collect.stats}
* Positions on the baseline.
*
* @param cellY the location of the row, does not include insets
* @param cellHeight the height of the row, does not take into account
* insets
* @param r available bounds for the component, is padded by insets and
* ipady
*/
private void alignOnBaseline(GridBagConstraints cons, Rectangle r,
int cellY, int cellHeight) {
if (cons.ascent >= 0) {
if (cons.baselineResizeBehavior == Component.
BaselineResizeBehavior.CONSTANT_DESCENT) {
// Anchor to the bottom.
// Baseline is at (cellY + cellHeight - maxDescent).
// Bottom of component (maxY) is at baseline + descent
// of component. We need to subtract the bottom inset here
// as the descent in the constraints object includes the
// bottom inset.
int maxY = cellY + cellHeight -
layoutInfo.maxDescent[cons.tempY + cons.tempHeight - 1] +
cons.descent - cons.insets.bottom;
if (!cons.isVerticallyResizable()) {
// Component not resizable, calculate y location
// from maxY - height.
r.y = maxY - cons.minHeight;
r.height = cons.minHeight;
} else {
// Component is resizable. As brb is constant descent,
// can expand component to fill region above baseline.
// Subtract out the top inset so that components insets
// are honored.
r.height = maxY - cellY - cons.insets.top;
}
}
else {
// BRB is not constant_descent
int baseline; // baseline for the row, relative to cellY
// Component baseline, includes insets.top
int ascent = cons.ascent;
if (layoutInfo.hasConstantDescent(cons.tempY)) {
// Mixed ascent/descent in same row, calculate position
// off maxDescent
baseline = cellHeight - layoutInfo.maxDescent[cons.tempY];
}
else {
// Only ascents/unknown in this row, anchor to top
baseline = layoutInfo.maxAscent[cons.tempY];
}
if (cons.baselineResizeBehavior == Component.
BaselineResizeBehavior.OTHER) {
// BRB is other, which means we can only determine
// the baseline by asking for it again giving the
// size we plan on using for the component.
boolean fits = false;
ascent = componentAdjusting.getBaseline(r.width, r.height);
if (ascent >= 0) {
// Component has a baseline, pad with top inset
// (this follows from calculateBaseline which
// does the same).
ascent += cons.insets.top;
}
if (ascent >= 0 && ascent <= baseline) {
// Components baseline fits within rows baseline.
// Make sure the descent fits within the space as well.
if (baseline + (r.height - ascent - cons.insets.top) <=
cellHeight - cons.insets.bottom) {
// It fits, we're good.
fits = true;
}
else if (cons.isVerticallyResizable()) {
// Doesn't fit, but it's resizable. Try
// again assuming we'll get ascent again.
int ascent2 = componentAdjusting.getBaseline(
r.width, cellHeight - cons.insets.bottom -
baseline + ascent);
if (ascent2 >= 0) {
ascent2 += cons.insets.top;
}
if (ascent2 >= 0 && ascent2 <= ascent) {
// It'll fit
r.height = cellHeight - cons.insets.bottom -
baseline + ascent;
ascent = ascent2;
fits = true;
}
}
}
if (!fits) {
// Doesn't fit, use min size and original ascent
ascent = cons.ascent;
r.width = cons.minWidth;
r.height = cons.minHeight;
}
}
// Reset the components y location based on
// components ascent and baseline for row. Because ascent
// includes the baseline
r.y = cellY + baseline - ascent + cons.insets.top;
if (cons.isVerticallyResizable()) {
switch(cons.baselineResizeBehavior) {
case CONSTANT_ASCENT:
r.height = Math.max(cons.minHeight,cellY + cellHeight -
r.y - cons.insets.bottom);
break;
case CENTER_OFFSET:
{
int upper = r.y - cellY - cons.insets.top;
int lower = cellY + cellHeight - r.y -
cons.minHeight - cons.insets.bottom;
int delta = Math.min(upper, lower);
delta += delta;
if (delta > 0 &&
(cons.minHeight + cons.centerPadding +
delta) / 2 + cons.centerOffset != baseline) {
// Off by 1
delta--;
}
r.height = cons.minHeight + delta;
r.y = cellY + baseline -
(r.height + cons.centerPadding) / 2 -
cons.centerOffset;
}
break;
case OTHER:
// Handled above
break;
default:
break;
}
}
}
}
else {
centerVertically(cons, r, cellHeight);
}
}
/** {@collect.stats}
* Positions the specified component above the baseline. That is
* the bottom edge of the component will be aligned along the baseline.
* If the row does not have a baseline, this centers the component.
*/
private void alignAboveBaseline(GridBagConstraints cons, Rectangle r,
int cellY, int cellHeight) {
if (layoutInfo.hasBaseline(cons.tempY)) {
int maxY; // Baseline for the row
if (layoutInfo.hasConstantDescent(cons.tempY)) {
// Prefer descent
maxY = cellY + cellHeight - layoutInfo.maxDescent[cons.tempY];
}
else {
// Prefer ascent
maxY = cellY + layoutInfo.maxAscent[cons.tempY];
}
if (cons.isVerticallyResizable()) {
// Component is resizable. Top edge is offset by top
// inset, bottom edge on baseline.
r.y = cellY + cons.insets.top;
r.height = maxY - r.y;
}
else {
// Not resizable.
r.height = cons.minHeight + cons.ipady;
r.y = maxY - r.height;
}
}
else {
centerVertically(cons, r, cellHeight);
}
}
/** {@collect.stats}
* Positions below the baseline.
*/
private void alignBelowBaseline(GridBagConstraints cons, Rectangle r,
int cellY, int cellHeight) {
if (layoutInfo.hasBaseline(cons.tempY)) {
if (layoutInfo.hasConstantDescent(cons.tempY)) {
// Prefer descent
r.y = cellY + cellHeight - layoutInfo.maxDescent[cons.tempY];
}
else {
// Prefer ascent
r.y = cellY + layoutInfo.maxAscent[cons.tempY];
}
if (cons.isVerticallyResizable()) {
r.height = cellY + cellHeight - r.y - cons.insets.bottom;
}
}
else {
centerVertically(cons, r, cellHeight);
}
}
private void centerVertically(GridBagConstraints cons, Rectangle r,
int cellHeight) {
if (!cons.isVerticallyResizable()) {
r.y += Math.max(0, (cellHeight - cons.insets.top -
cons.insets.bottom - cons.minHeight -
cons.ipady) / 2);
}
}
/** {@collect.stats}
* Figures out the minimum size of the
* master based on the information from <code>getLayoutInfo</code>.
* This method should only be used internally by
* <code>GridBagLayout</code>.
*
* @param parent the layout container
* @param info the layout info for this parent
* @return a <code>Dimension</code> object containing the
* minimum size
* @since 1.4
*/
protected Dimension getMinSize(Container parent, GridBagLayoutInfo info) {
return GetMinSize(parent, info);
}
/** {@collect.stats}
* This method is obsolete and supplied for backwards
* compatability only; new code should call {@link
* #getMinSize(java.awt.Container, GridBagLayoutInfo) getMinSize} instead.
* This method is the same as <code>getMinSize</code>;
* refer to <code>getMinSize</code> for details on parameters
* and return value.
*/
protected Dimension GetMinSize(Container parent, GridBagLayoutInfo info) {
Dimension d = new Dimension();
int i, t;
Insets insets = parent.getInsets();
t = 0;
for(i = 0; i < info.width; i++)
t += info.minWidth[i];
d.width = t + insets.left + insets.right;
t = 0;
for(i = 0; i < info.height; i++)
t += info.minHeight[i];
d.height = t + insets.top + insets.bottom;
return d;
}
transient boolean rightToLeft = false;
/** {@collect.stats}
* Lays out the grid.
* This method should only be used internally by
* <code>GridBagLayout</code>.
*
* @param parent the layout container
* @since 1.4
*/
protected void arrangeGrid(Container parent) {
ArrangeGrid(parent);
}
/** {@collect.stats}
* This method is obsolete and supplied for backwards
* compatability only; new code should call {@link
* #arrangeGrid(Container) arrangeGrid} instead.
* This method is the same as <code>arrangeGrid</code>;
* refer to <code>arrangeGrid</code> for details on the
* parameter.
*/
protected void ArrangeGrid(Container parent) {
Component comp;
int compindex;
GridBagConstraints constraints;
Insets insets = parent.getInsets();
Component components[] = parent.getComponents();
Dimension d;
Rectangle r = new Rectangle();
int i, diffw, diffh;
double weight;
GridBagLayoutInfo info;
rightToLeft = !parent.getComponentOrientation().isLeftToRight();
/*
* If the parent has no slaves anymore, then don't do anything
* at all: just leave the parent's size as-is.
*/
if (components.length == 0 &&
(columnWidths == null || columnWidths.length == 0) &&
(rowHeights == null || rowHeights.length == 0)) {
return;
}
/*
* Pass #1: scan all the slaves to figure out the total amount
* of space needed.
*/
info = getLayoutInfo(parent, PREFERREDSIZE);
d = getMinSize(parent, info);
if (parent.width < d.width || parent.height < d.height) {
info = getLayoutInfo(parent, MINSIZE);
d = getMinSize(parent, info);
}
layoutInfo = info;
r.width = d.width;
r.height = d.height;
/*
* DEBUG
*
* DumpLayoutInfo(info);
* for (compindex = 0 ; compindex < components.length ; compindex++) {
* comp = components[compindex];
* if (!comp.isVisible())
* continue;
* constraints = lookupConstraints(comp);
* DumpConstraints(constraints);
* }
* System.out.println("minSize " + r.width + " " + r.height);
*/
/*
* If the current dimensions of the window don't match the desired
* dimensions, then adjust the minWidth and minHeight arrays
* according to the weights.
*/
diffw = parent.width - r.width;
if (diffw != 0) {
weight = 0.0;
for (i = 0; i < info.width; i++)
weight += info.weightX[i];
if (weight > 0.0) {
for (i = 0; i < info.width; i++) {
int dx = (int)(( ((double)diffw) * info.weightX[i]) / weight);
info.minWidth[i] += dx;
r.width += dx;
if (info.minWidth[i] < 0) {
r.width -= info.minWidth[i];
info.minWidth[i] = 0;
}
}
}
diffw = parent.width - r.width;
}
else {
diffw = 0;
}
diffh = parent.height - r.height;
if (diffh != 0) {
weight = 0.0;
for (i = 0; i < info.height; i++)
weight += info.weightY[i];
if (weight > 0.0) {
for (i = 0; i < info.height; i++) {
int dy = (int)(( ((double)diffh) * info.weightY[i]) / weight);
info.minHeight[i] += dy;
r.height += dy;
if (info.minHeight[i] < 0) {
r.height -= info.minHeight[i];
info.minHeight[i] = 0;
}
}
}
diffh = parent.height - r.height;
}
else {
diffh = 0;
}
/*
* DEBUG
*
* System.out.println("Re-adjusted:");
* DumpLayoutInfo(info);
*/
/*
* Now do the actual layout of the slaves using the layout information
* that has been collected.
*/
info.startx = diffw/2 + insets.left;
info.starty = diffh/2 + insets.top;
for (compindex = 0 ; compindex < components.length ; compindex++) {
comp = components[compindex];
if (!comp.isVisible()){
continue;
}
constraints = lookupConstraints(comp);
if (!rightToLeft) {
r.x = info.startx;
for(i = 0; i < constraints.tempX; i++)
r.x += info.minWidth[i];
} else {
r.x = parent.width - (diffw/2 + insets.right);
for(i = 0; i < constraints.tempX; i++)
r.x -= info.minWidth[i];
}
r.y = info.starty;
for(i = 0; i < constraints.tempY; i++)
r.y += info.minHeight[i];
r.width = 0;
for(i = constraints.tempX;
i < (constraints.tempX + constraints.tempWidth);
i++) {
r.width += info.minWidth[i];
}
r.height = 0;
for(i = constraints.tempY;
i < (constraints.tempY + constraints.tempHeight);
i++) {
r.height += info.minHeight[i];
}
componentAdjusting = comp;
adjustForGravity(constraints, r);
/* fix for 4408108 - components were being created outside of the container */
/* fix for 4969409 "-" replaced by "+" */
if (r.x < 0) {
r.width += r.x;
r.x = 0;
}
if (r.y < 0) {
r.height += r.y;
r.y = 0;
}
/*
* If the window is too small to be interesting then
* unmap it. Otherwise configure it and then make sure
* it's mapped.
*/
if ((r.width <= 0) || (r.height <= 0)) {
comp.setBounds(0, 0, 0, 0);
}
else {
if (comp.x != r.x || comp.y != r.y ||
comp.width != r.width || comp.height != r.height) {
comp.setBounds(r.x, r.y, r.width, r.height);
}
}
}
}
// Added for serial backwards compatability (4348425)
static final long serialVersionUID = 8838754796412211005L;
}
|
Java
|
/*
* Copyright (c) 1995, 2006, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code 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
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package java.awt;
import java.io.ObjectInputStream;
import java.io.IOException;
/** {@collect.stats}
* A flow layout arranges components in a directional flow, much
* like lines of text in a paragraph. The flow direction is
* determined by the container's <code>componentOrientation</code>
* property and may be one of two values:
* <ul>
* <li><code>ComponentOrientation.LEFT_TO_RIGHT</code>
* <li><code>ComponentOrientation.RIGHT_TO_LEFT</code>
* </ul>
* Flow layouts are typically used
* to arrange buttons in a panel. It arranges buttons
* horizontally until no more buttons fit on the same line.
* The line alignment is determined by the <code>align</code>
* property. The possible values are:
* <ul>
* <li>{@link #LEFT LEFT}
* <li>{@link #RIGHT RIGHT}
* <li>{@link #CENTER CENTER}
* <li>{@link #LEADING LEADING}
* <li>{@link #TRAILING TRAILING}
* </ul>
* <p>
* For example, the following picture shows an applet using the flow
* layout manager (its default layout manager) to position three buttons:
* <p>
* <img src="doc-files/FlowLayout-1.gif"
* ALT="Graphic of Layout for Three Buttons"
* ALIGN=center HSPACE=10 VSPACE=7>
* <p>
* Here is the code for this applet:
* <p>
* <hr><blockquote><pre>
* import java.awt.*;
* import java.applet.Applet;
*
* public class myButtons extends Applet {
* Button button1, button2, button3;
* public void init() {
* button1 = new Button("Ok");
* button2 = new Button("Open");
* button3 = new Button("Close");
* add(button1);
* add(button2);
* add(button3);
* }
* }
* </pre></blockquote><hr>
* <p>
* A flow layout lets each component assume its natural (preferred) size.
*
* @author Arthur van Hoff
* @author Sami Shaio
* @since JDK1.0
* @see ComponentOrientation
*/
public class FlowLayout implements LayoutManager, java.io.Serializable {
/** {@collect.stats}
* This value indicates that each row of components
* should be left-justified.
*/
public static final int LEFT = 0;
/** {@collect.stats}
* This value indicates that each row of components
* should be centered.
*/
public static final int CENTER = 1;
/** {@collect.stats}
* This value indicates that each row of components
* should be right-justified.
*/
public static final int RIGHT = 2;
/** {@collect.stats}
* This value indicates that each row of components
* should be justified to the leading edge of the container's
* orientation, for example, to the left in left-to-right orientations.
*
* @see java.awt.Component#getComponentOrientation
* @see java.awt.ComponentOrientation
* @since 1.2
*/
public static final int LEADING = 3;
/** {@collect.stats}
* This value indicates that each row of components
* should be justified to the trailing edge of the container's
* orientation, for example, to the right in left-to-right orientations.
*
* @see java.awt.Component#getComponentOrientation
* @see java.awt.ComponentOrientation
* @since 1.2
*/
public static final int TRAILING = 4;
/** {@collect.stats}
* <code>align</code> is the property that determines
* how each row distributes empty space.
* It can be one of the following values:
* <ul>
* <code>LEFT</code>
* <code>RIGHT</code>
* <code>CENTER</code>
* <code>LEADING</code>
* <code>TRAILING</code>
* </ul>
*
* @serial
* @see #getAlignment
* @see #setAlignment
*/
int align; // This is for 1.1 serialization compatibility
/** {@collect.stats}
* <code>newAlign</code> is the property that determines
* how each row distributes empty space for the Java 2 platform,
* v1.2 and greater.
* It can be one of the following three values:
* <ul>
* <code>LEFT</code>
* <code>RIGHT</code>
* <code>CENTER</code>
* <code>LEADING</code>
* <code>TRAILING</code>
* </ul>
*
* @serial
* @since 1.2
* @see #getAlignment
* @see #setAlignment
*/
int newAlign; // This is the one we actually use
/** {@collect.stats}
* The flow layout manager allows a seperation of
* components with gaps. The horizontal gap will
* specify the space between components and between
* the components and the borders of the
* <code>Container</code>.
*
* @serial
* @see #getHgap()
* @see #setHgap(int)
*/
int hgap;
/** {@collect.stats}
* The flow layout manager allows a seperation of
* components with gaps. The vertical gap will
* specify the space between rows and between the
* the rows and the borders of the <code>Container</code>.
*
* @serial
* @see #getHgap()
* @see #setHgap(int)
*/
int vgap;
/** {@collect.stats}
* If true, components will be aligned on their baseline.
*/
private boolean alignOnBaseline;
/*
* JDK 1.1 serialVersionUID
*/
private static final long serialVersionUID = -7262534875583282631L;
/** {@collect.stats}
* Constructs a new <code>FlowLayout</code> with a centered alignment and a
* default 5-unit horizontal and vertical gap.
*/
public FlowLayout() {
this(CENTER, 5, 5);
}
/** {@collect.stats}
* Constructs a new <code>FlowLayout</code> with the specified
* alignment and a default 5-unit horizontal and vertical gap.
* The value of the alignment argument must be one of
* <code>FlowLayout.LEFT</code>, <code>FlowLayout.RIGHT</code>,
* <code>FlowLayout.CENTER</code>, <code>FlowLayout.LEADING</code>,
* or <code>FlowLayout.TRAILING</code>.
* @param align the alignment value
*/
public FlowLayout(int align) {
this(align, 5, 5);
}
/** {@collect.stats}
* Creates a new flow layout manager with the indicated alignment
* and the indicated horizontal and vertical gaps.
* <p>
* The value of the alignment argument must be one of
* <code>FlowLayout.LEFT</code>, <code>FlowLayout.RIGHT</code>,
* <code>FlowLayout.CENTER</code>, <code>FlowLayout.LEADING</code>,
* or <code>FlowLayout.TRAILING</code>.
* @param align the alignment value
* @param hgap the horizontal gap between components
* and between the components and the
* borders of the <code>Container</code>
* @param vgap the vertical gap between components
* and between the components and the
* borders of the <code>Container</code>
*/
public FlowLayout(int align, int hgap, int vgap) {
this.hgap = hgap;
this.vgap = vgap;
setAlignment(align);
}
/** {@collect.stats}
* Gets the alignment for this layout.
* Possible values are <code>FlowLayout.LEFT</code>,
* <code>FlowLayout.RIGHT</code>, <code>FlowLayout.CENTER</code>,
* <code>FlowLayout.LEADING</code>,
* or <code>FlowLayout.TRAILING</code>.
* @return the alignment value for this layout
* @see java.awt.FlowLayout#setAlignment
* @since JDK1.1
*/
public int getAlignment() {
return newAlign;
}
/** {@collect.stats}
* Sets the alignment for this layout.
* Possible values are
* <ul>
* <li><code>FlowLayout.LEFT</code>
* <li><code>FlowLayout.RIGHT</code>
* <li><code>FlowLayout.CENTER</code>
* <li><code>FlowLayout.LEADING</code>
* <li><code>FlowLayout.TRAILING</code>
* </ul>
* @param align one of the alignment values shown above
* @see #getAlignment()
* @since JDK1.1
*/
public void setAlignment(int align) {
this.newAlign = align;
// this.align is used only for serialization compatibility,
// so set it to a value compatible with the 1.1 version
// of the class
switch (align) {
case LEADING:
this.align = LEFT;
break;
case TRAILING:
this.align = RIGHT;
break;
default:
this.align = align;
break;
}
}
/** {@collect.stats}
* Gets the horizontal gap between components
* and between the components and the borders
* of the <code>Container</code>
*
* @return the horizontal gap between components
* and between the components and the borders
* of the <code>Container</code>
* @see java.awt.FlowLayout#setHgap
* @since JDK1.1
*/
public int getHgap() {
return hgap;
}
/** {@collect.stats}
* Sets the horizontal gap between components and
* between the components and the borders of the
* <code>Container</code>.
*
* @param hgap the horizontal gap between components
* and between the components and the borders
* of the <code>Container</code>
* @see java.awt.FlowLayout#getHgap
* @since JDK1.1
*/
public void setHgap(int hgap) {
this.hgap = hgap;
}
/** {@collect.stats}
* Gets the vertical gap between components and
* between the components and the borders of the
* <code>Container</code>.
*
* @return the vertical gap between components
* and between the components and the borders
* of the <code>Container</code>
* @see java.awt.FlowLayout#setVgap
* @since JDK1.1
*/
public int getVgap() {
return vgap;
}
/** {@collect.stats}
* Sets the vertical gap between components and between
* the components and the borders of the <code>Container</code>.
*
* @param vgap the vertical gap between components
* and between the components and the borders
* of the <code>Container</code>
* @see java.awt.FlowLayout#getVgap
* @since JDK1.1
*/
public void setVgap(int vgap) {
this.vgap = vgap;
}
/** {@collect.stats}
* Sets whether or not components should be vertically aligned along their
* baseline. Components that do not have a baseline will be centered.
* The default is false.
*
* @param alignOnBaseline whether or not components should be
* vertically aligned on their baseline
* @since 1.6
*/
public void setAlignOnBaseline(boolean alignOnBaseline) {
this.alignOnBaseline = alignOnBaseline;
}
/** {@collect.stats}
* Returns true if components are to be vertically aligned along
* their baseline. The default is false.
*
* @return true if components are to be vertically aligned along
* their baseline
* @since 1.6
*/
public boolean getAlignOnBaseline() {
return alignOnBaseline;
}
/** {@collect.stats}
* Adds the specified component to the layout.
* Not used by this class.
* @param name the name of the component
* @param comp the component to be added
*/
public void addLayoutComponent(String name, Component comp) {
}
/** {@collect.stats}
* Removes the specified component from the layout.
* Not used by this class.
* @param comp the component to remove
* @see java.awt.Container#removeAll
*/
public void removeLayoutComponent(Component comp) {
}
/** {@collect.stats}
* Returns the preferred dimensions for this layout given the
* <i>visible</i> components in the specified target container.
*
* @param target the container that needs to be laid out
* @return the preferred dimensions to lay out the
* subcomponents of the specified container
* @see Container
* @see #minimumLayoutSize
* @see java.awt.Container#getPreferredSize
*/
public Dimension preferredLayoutSize(Container target) {
synchronized (target.getTreeLock()) {
Dimension dim = new Dimension(0, 0);
int nmembers = target.getComponentCount();
boolean firstVisibleComponent = true;
boolean useBaseline = getAlignOnBaseline();
int maxAscent = 0;
int maxDescent = 0;
for (int i = 0 ; i < nmembers ; i++) {
Component m = target.getComponent(i);
if (m.isVisible()) {
Dimension d = m.getPreferredSize();
dim.height = Math.max(dim.height, d.height);
if (firstVisibleComponent) {
firstVisibleComponent = false;
} else {
dim.width += hgap;
}
dim.width += d.width;
if (useBaseline) {
int baseline = m.getBaseline(d.width, d.height);
if (baseline >= 0) {
maxAscent = Math.max(maxAscent, baseline);
maxDescent = Math.max(maxDescent, d.height - baseline);
}
}
}
}
if (useBaseline) {
dim.height = Math.max(maxAscent + maxDescent, dim.height);
}
Insets insets = target.getInsets();
dim.width += insets.left + insets.right + hgap*2;
dim.height += insets.top + insets.bottom + vgap*2;
return dim;
}
}
/** {@collect.stats}
* Returns the minimum dimensions needed to layout the <i>visible</i>
* components contained in the specified target container.
* @param target the container that needs to be laid out
* @return the minimum dimensions to lay out the
* subcomponents of the specified container
* @see #preferredLayoutSize
* @see java.awt.Container
* @see java.awt.Container#doLayout
*/
public Dimension minimumLayoutSize(Container target) {
synchronized (target.getTreeLock()) {
boolean useBaseline = getAlignOnBaseline();
Dimension dim = new Dimension(0, 0);
int nmembers = target.getComponentCount();
int maxAscent = 0;
int maxDescent = 0;
boolean firstVisibleComponent = true;
for (int i = 0 ; i < nmembers ; i++) {
Component m = target.getComponent(i);
if (m.visible) {
Dimension d = m.getMinimumSize();
dim.height = Math.max(dim.height, d.height);
if (firstVisibleComponent) {
firstVisibleComponent = false;
} else {
dim.width += hgap;
}
dim.width += d.width;
if (useBaseline) {
int baseline = m.getBaseline(d.width, d.height);
if (baseline >= 0) {
maxAscent = Math.max(maxAscent, baseline);
maxDescent = Math.max(maxDescent,
dim.height - baseline);
}
}
}
}
if (useBaseline) {
dim.height = Math.max(maxAscent + maxDescent, dim.height);
}
Insets insets = target.getInsets();
dim.width += insets.left + insets.right + hgap*2;
dim.height += insets.top + insets.bottom + vgap*2;
return dim;
}
}
/** {@collect.stats}
* Centers the elements in the specified row, if there is any slack.
* @param target the component which needs to be moved
* @param x the x coordinate
* @param y the y coordinate
* @param width the width dimensions
* @param height the height dimensions
* @param rowStart the beginning of the row
* @param rowEnd the the ending of the row
* @param useBaseline Whether or not to align on baseline.
* @param ascent Ascent for the components. This is only valid if
* useBaseline is true.
* @param descent Ascent for the components. This is only valid if
* useBaseline is true.
* @return actual row height
*/
private int moveComponents(Container target, int x, int y, int width, int height,
int rowStart, int rowEnd, boolean ltr,
boolean useBaseline, int[] ascent,
int[] descent) {
switch (newAlign) {
case LEFT:
x += ltr ? 0 : width;
break;
case CENTER:
x += width / 2;
break;
case RIGHT:
x += ltr ? width : 0;
break;
case LEADING:
break;
case TRAILING:
x += width;
break;
}
int maxAscent = 0;
int nonbaselineHeight = 0;
int baselineOffset = 0;
if (useBaseline) {
int maxDescent = 0;
for (int i = rowStart ; i < rowEnd ; i++) {
Component m = target.getComponent(i);
if (m.visible) {
if (ascent[i] >= 0) {
maxAscent = Math.max(maxAscent, ascent[i]);
maxDescent = Math.max(maxDescent, descent[i]);
}
else {
nonbaselineHeight = Math.max(m.getHeight(),
nonbaselineHeight);
}
}
}
height = Math.max(maxAscent + maxDescent, nonbaselineHeight);
baselineOffset = (height - maxAscent - maxDescent) / 2;
}
for (int i = rowStart ; i < rowEnd ; i++) {
Component m = target.getComponent(i);
if (m.isVisible()) {
int cy;
if (useBaseline && ascent[i] >= 0) {
cy = y + baselineOffset + maxAscent - ascent[i];
}
else {
cy = y + (height - m.height) / 2;
}
if (ltr) {
m.setLocation(x, cy);
} else {
m.setLocation(target.width - x - m.width, cy);
}
x += m.width + hgap;
}
}
return height;
}
/** {@collect.stats}
* Lays out the container. This method lets each
* <i>visible</i> component take
* its preferred size by reshaping the components in the
* target container in order to satisfy the alignment of
* this <code>FlowLayout</code> object.
*
* @param target the specified component being laid out
* @see Container
* @see java.awt.Container#doLayout
*/
public void layoutContainer(Container target) {
synchronized (target.getTreeLock()) {
Insets insets = target.getInsets();
int maxwidth = target.width - (insets.left + insets.right + hgap*2);
int nmembers = target.getComponentCount();
int x = 0, y = insets.top + vgap;
int rowh = 0, start = 0;
boolean ltr = target.getComponentOrientation().isLeftToRight();
boolean useBaseline = getAlignOnBaseline();
int[] ascent = null;
int[] descent = null;
if (useBaseline) {
ascent = new int[nmembers];
descent = new int[nmembers];
}
for (int i = 0 ; i < nmembers ; i++) {
Component m = target.getComponent(i);
if (m.isVisible()) {
Dimension d = m.getPreferredSize();
m.setSize(d.width, d.height);
if (useBaseline) {
int baseline = m.getBaseline(d.width, d.height);
if (baseline >= 0) {
ascent[i] = baseline;
descent[i] = d.height - baseline;
}
else {
ascent[i] = -1;
}
}
if ((x == 0) || ((x + d.width) <= maxwidth)) {
if (x > 0) {
x += hgap;
}
x += d.width;
rowh = Math.max(rowh, d.height);
} else {
rowh = moveComponents(target, insets.left + hgap, y,
maxwidth - x, rowh, start, i, ltr,
useBaseline, ascent, descent);
x = d.width;
y += vgap + rowh;
rowh = d.height;
start = i;
}
}
}
moveComponents(target, insets.left + hgap, y, maxwidth - x, rowh,
start, nmembers, ltr, useBaseline, ascent, descent);
}
}
//
// the internal serial version which says which version was written
// - 0 (default) for versions before the Java 2 platform, v1.2
// - 1 for version >= Java 2 platform v1.2, which includes "newAlign" field
//
private static final int currentSerialVersion = 1;
/** {@collect.stats}
* This represent the <code>currentSerialVersion</code>
* which is bein used. It will be one of two values :
* <code>0</code> versions before Java 2 platform v1.2..
* <code>1</code> versions after Java 2 platform v1.2..
*
* @serial
* @since 1.2
*/
private int serialVersionOnStream = currentSerialVersion;
/** {@collect.stats}
* Reads this object out of a serialization stream, handling
* objects written by older versions of the class that didn't contain all
* of the fields we use now..
*/
private void readObject(ObjectInputStream stream)
throws IOException, ClassNotFoundException
{
stream.defaultReadObject();
if (serialVersionOnStream < 1) {
// "newAlign" field wasn't present, so use the old "align" field.
setAlignment(this.align);
}
serialVersionOnStream = currentSerialVersion;
}
/** {@collect.stats}
* Returns a string representation of this <code>FlowLayout</code>
* object and its values.
* @return a string representation of this layout
*/
public String toString() {
String str = "";
switch (align) {
case LEFT: str = ",align=left"; break;
case CENTER: str = ",align=center"; break;
case RIGHT: str = ",align=right"; break;
case LEADING: str = ",align=leading"; break;
case TRAILING: str = ",align=trailing"; break;
}
return getClass().getName() + "[hgap=" + hgap + ",vgap=" + vgap + str + "]";
}
}
|
Java
|
/*
* Copyright (c) 1995, 2006, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code 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
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package java.awt;
import java.awt.peer.ButtonPeer;
import java.util.EventListener;
import java.awt.event.*;
import java.io.ObjectOutputStream;
import java.io.ObjectInputStream;
import java.io.IOException;
import javax.accessibility.*;
/** {@collect.stats}
* This class creates a labeled button. The application can cause
* some action to happen when the button is pushed. This image
* depicts three views of a "<code>Quit</code>" button as it appears
* under the Solaris operating system:
* <p>
* <img src="doc-files/Button-1.gif" alt="The following context describes the graphic"
* ALIGN=center HSPACE=10 VSPACE=7>
* <p>
* The first view shows the button as it appears normally.
* The second view shows the button
* when it has input focus. Its outline is darkened to let the
* user know that it is an active object. The third view shows the
* button when the user clicks the mouse over the button, and thus
* requests that an action be performed.
* <p>
* The gesture of clicking on a button with the mouse
* is associated with one instance of <code>ActionEvent</code>,
* which is sent out when the mouse is both pressed and released
* over the button. If an application is interested in knowing
* when the button has been pressed but not released, as a separate
* gesture, it can specialize <code>processMouseEvent</code>,
* or it can register itself as a listener for mouse events by
* calling <code>addMouseListener</code>. Both of these methods are
* defined by <code>Component</code>, the abstract superclass of
* all components.
* <p>
* When a button is pressed and released, AWT sends an instance
* of <code>ActionEvent</code> to the button, by calling
* <code>processEvent</code> on the button. The button's
* <code>processEvent</code> method receives all events
* for the button; it passes an action event along by
* calling its own <code>processActionEvent</code> method.
* The latter method passes the action event on to any action
* listeners that have registered an interest in action
* events generated by this button.
* <p>
* If an application wants to perform some action based on
* a button being pressed and released, it should implement
* <code>ActionListener</code> and register the new listener
* to receive events from this button, by calling the button's
* <code>addActionListener</code> method. The application can
* make use of the button's action command as a messaging protocol.
*
* @author Sami Shaio
* @see java.awt.event.ActionEvent
* @see java.awt.event.ActionListener
* @see java.awt.Component#processMouseEvent
* @see java.awt.Component#addMouseListener
* @since JDK1.0
*/
public class Button extends Component implements Accessible {
/** {@collect.stats}
* The button's label. This value may be null.
* @serial
* @see #getLabel()
* @see #setLabel(String)
*/
String label;
/** {@collect.stats}
* The action to be performed once a button has been
* pressed. This value may be null.
* @serial
* @see #getActionCommand()
* @see #setActionCommand(String)
*/
String actionCommand;
transient ActionListener actionListener;
private static final String base = "button";
private static int nameCounter = 0;
/*
* JDK 1.1 serialVersionUID
*/
private static final long serialVersionUID = -8774683716313001058L;
static {
/* ensure that the necessary native libraries are loaded */
Toolkit.loadLibraries();
if (!GraphicsEnvironment.isHeadless()) {
initIDs();
}
}
/** {@collect.stats}
* Initialize JNI field and method IDs for fields that may be
* accessed from C.
*/
private static native void initIDs();
/** {@collect.stats}
* Constructs a button with an empty string for its label.
*
* @exception HeadlessException if GraphicsEnvironment.isHeadless()
* returns true
* @see java.awt.GraphicsEnvironment#isHeadless
*/
public Button() throws HeadlessException {
this("");
}
/** {@collect.stats}
* Constructs a button with the specified label.
*
* @param label a string label for the button, or
* <code>null</code> for no label
* @exception HeadlessException if GraphicsEnvironment.isHeadless()
* returns true
* @see java.awt.GraphicsEnvironment#isHeadless
*/
public Button(String label) throws HeadlessException {
GraphicsEnvironment.checkHeadless();
this.label = label;
}
/** {@collect.stats}
* Construct a name for this component. Called by getName() when the
* name is null.
*/
String constructComponentName() {
synchronized (Button.class) {
return base + nameCounter++;
}
}
/** {@collect.stats}
* Creates the peer of the button. The button's peer allows the
* application to change the look of the button without changing
* its functionality.
*
* @see java.awt.Toolkit#createButton(java.awt.Button)
* @see java.awt.Component#getToolkit()
*/
public void addNotify() {
synchronized(getTreeLock()) {
if (peer == null)
peer = getToolkit().createButton(this);
super.addNotify();
}
}
/** {@collect.stats}
* Gets the label of this button.
*
* @return the button's label, or <code>null</code>
* if the button has no label.
* @see java.awt.Button#setLabel
*/
public String getLabel() {
return label;
}
/** {@collect.stats}
* Sets the button's label to be the specified string.
*
* @param label the new label, or <code>null</code>
* if the button has no label.
* @see java.awt.Button#getLabel
*/
public void setLabel(String label) {
boolean testvalid = false;
synchronized (this) {
if (label != this.label && (this.label == null ||
!this.label.equals(label))) {
this.label = label;
ButtonPeer peer = (ButtonPeer)this.peer;
if (peer != null) {
peer.setLabel(label);
}
testvalid = true;
}
}
// This could change the preferred size of the Component.
if (testvalid && valid) {
invalidate();
}
}
/** {@collect.stats}
* Sets the command name for the action event fired
* by this button. By default this action command is
* set to match the label of the button.
*
* @param command a string used to set the button's
* action command.
* If the string is <code>null</code> then the action command
* is set to match the label of the button.
* @see java.awt.event.ActionEvent
* @since JDK1.1
*/
public void setActionCommand(String command) {
actionCommand = command;
}
/** {@collect.stats}
* Returns the command name of the action event fired by this button.
* If the command name is <code>null</code> (default) then this method
* returns the label of the button.
*/
public String getActionCommand() {
return (actionCommand == null? label : actionCommand);
}
/** {@collect.stats}
* Adds the specified action listener to receive action events from
* this button. Action events occur when a user presses or releases
* the mouse over this button.
* If l is null, no exception is thrown and no action is performed.
* <p>Refer to <a href="doc-files/AWTThreadIssues.html#ListenersThreads"
* >AWT Threading Issues</a> for details on AWT's threading model.
*
* @param l the action listener
* @see #removeActionListener
* @see #getActionListeners
* @see java.awt.event.ActionListener
* @since JDK1.1
*/
public synchronized void addActionListener(ActionListener l) {
if (l == null) {
return;
}
actionListener = AWTEventMulticaster.add(actionListener, l);
newEventsOnly = true;
}
/** {@collect.stats}
* Removes the specified action listener so that it no longer
* receives action events from this button. Action events occur
* when a user presses or releases the mouse over this button.
* If l is null, no exception is thrown and no action is performed.
* <p>Refer to <a href="doc-files/AWTThreadIssues.html#ListenersThreads"
* >AWT Threading Issues</a> for details on AWT's threading model.
*
* @param l the action listener
* @see #addActionListener
* @see #getActionListeners
* @see java.awt.event.ActionListener
* @since JDK1.1
*/
public synchronized void removeActionListener(ActionListener l) {
if (l == null) {
return;
}
actionListener = AWTEventMulticaster.remove(actionListener, l);
}
/** {@collect.stats}
* Returns an array of all the action listeners
* registered on this button.
*
* @return all of this button's <code>ActionListener</code>s
* or an empty array if no action
* listeners are currently registered
*
* @see #addActionListener
* @see #removeActionListener
* @see java.awt.event.ActionListener
* @since 1.4
*/
public synchronized ActionListener[] getActionListeners() {
return (ActionListener[]) (getListeners(ActionListener.class));
}
/** {@collect.stats}
* Returns an array of all the objects currently registered
* as <code><em>Foo</em>Listener</code>s
* upon this <code>Button</code>.
* <code><em>Foo</em>Listener</code>s are registered using the
* <code>add<em>Foo</em>Listener</code> method.
*
* <p>
* You can specify the <code>listenerType</code> argument
* with a class literal, such as
* <code><em>Foo</em>Listener.class</code>.
* For example, you can query a
* <code>Button</code> <code>b</code>
* for its action listeners with the following code:
*
* <pre>ActionListener[] als = (ActionListener[])(b.getListeners(ActionListener.class));</pre>
*
* If no such listeners exist, this method returns an empty array.
*
* @param listenerType the type of listeners requested; this parameter
* should specify an interface that descends from
* <code>java.util.EventListener</code>
* @return an array of all objects registered as
* <code><em>Foo</em>Listener</code>s on this button,
* or an empty array if no such
* listeners have been added
* @exception ClassCastException if <code>listenerType</code>
* doesn't specify a class or interface that implements
* <code>java.util.EventListener</code>
*
* @see #getActionListeners
* @since 1.3
*/
public <T extends EventListener> T[] getListeners(Class<T> listenerType) {
EventListener l = null;
if (listenerType == ActionListener.class) {
l = actionListener;
} else {
return super.getListeners(listenerType);
}
return AWTEventMulticaster.getListeners(l, listenerType);
}
// REMIND: remove when filtering is done at lower level
boolean eventEnabled(AWTEvent e) {
if (e.id == ActionEvent.ACTION_PERFORMED) {
if ((eventMask & AWTEvent.ACTION_EVENT_MASK) != 0 ||
actionListener != null) {
return true;
}
return false;
}
return super.eventEnabled(e);
}
/** {@collect.stats}
* Processes events on this button. If an event is
* an instance of <code>ActionEvent</code>, this method invokes
* the <code>processActionEvent</code> method. Otherwise,
* it invokes <code>processEvent</code> on the superclass.
* <p>Note that if the event parameter is <code>null</code>
* the behavior is unspecified and may result in an
* exception.
*
* @param e the event
* @see java.awt.event.ActionEvent
* @see java.awt.Button#processActionEvent
* @since JDK1.1
*/
protected void processEvent(AWTEvent e) {
if (e instanceof ActionEvent) {
processActionEvent((ActionEvent)e);
return;
}
super.processEvent(e);
}
/** {@collect.stats}
* Processes action events occurring on this button
* by dispatching them to any registered
* <code>ActionListener</code> objects.
* <p>
* This method is not called unless action events are
* enabled for this button. Action events are enabled
* when one of the following occurs:
* <p><ul>
* <li>An <code>ActionListener</code> object is registered
* via <code>addActionListener</code>.
* <li>Action events are enabled via <code>enableEvents</code>.
* </ul>
* <p>Note that if the event parameter is <code>null</code>
* the behavior is unspecified and may result in an
* exception.
*
* @param e the action event
* @see java.awt.event.ActionListener
* @see java.awt.Button#addActionListener
* @see java.awt.Component#enableEvents
* @since JDK1.1
*/
protected void processActionEvent(ActionEvent e) {
ActionListener listener = actionListener;
if (listener != null) {
listener.actionPerformed(e);
}
}
/** {@collect.stats}
* Returns a string representing the state of this <code>Button</code>.
* This method is intended to be used only for debugging purposes, and the
* content and format of the returned string may vary between
* implementations. The returned string may be empty but may not be
* <code>null</code>.
*
* @return the parameter string of this button
*/
protected String paramString() {
return super.paramString() + ",label=" + label;
}
/* Serialization support.
*/
/*
* Button Serial Data Version.
* @serial
*/
private int buttonSerializedDataVersion = 1;
/** {@collect.stats}
* Writes default serializable fields to stream. Writes
* a list of serializable <code>ActionListeners</code>
* as optional data. The non-serializable
* <code>ActionListeners</code> are detected and
* no attempt is made to serialize them.
*
* @serialData <code>null</code> terminated sequence of 0 or
* more pairs: the pair consists of a <code>String</code>
* and an <code>Object</code>; the <code>String</code>
* indicates the type of object and is one of the following:
* <code>actionListenerK</code> indicating an
* <code>ActionListener</code> object
*
* @param s the <code>ObjectOutputStream</code> to write
* @see AWTEventMulticaster#save(ObjectOutputStream, String, EventListener)
* @see java.awt.Component#actionListenerK
* @see #readObject(ObjectInputStream)
*/
private void writeObject(ObjectOutputStream s)
throws IOException
{
s.defaultWriteObject();
AWTEventMulticaster.save(s, actionListenerK, actionListener);
s.writeObject(null);
}
/** {@collect.stats}
* Reads the <code>ObjectInputStream</code> and if
* it isn't <code>null</code> adds a listener to
* receive action events fired by the button.
* Unrecognized keys or values will be ignored.
*
* @param s the <code>ObjectInputStream</code> to read
* @exception HeadlessException if
* <code>GraphicsEnvironment.isHeadless</code> returns
* <code>true</code>
* @serial
* @see #removeActionListener(ActionListener)
* @see #addActionListener(ActionListener)
* @see java.awt.GraphicsEnvironment#isHeadless
* @see #writeObject(ObjectOutputStream)
*/
private void readObject(ObjectInputStream s)
throws ClassNotFoundException, IOException, HeadlessException
{
GraphicsEnvironment.checkHeadless();
s.defaultReadObject();
Object keyOrNull;
while(null != (keyOrNull = s.readObject())) {
String key = ((String)keyOrNull).intern();
if (actionListenerK == key)
addActionListener((ActionListener)(s.readObject()));
else // skip value for unrecognized key
s.readObject();
}
}
/////////////////
// Accessibility support
////////////////
/** {@collect.stats}
* Gets the <code>AccessibleContext</code> associated with
* this <code>Button</code>. For buttons, the
* <code>AccessibleContext</code> takes the form of an
* <code>AccessibleAWTButton</code>.
* A new <code>AccessibleAWTButton</code> instance is
* created if necessary.
*
* @return an <code>AccessibleAWTButton</code> that serves as the
* <code>AccessibleContext</code> of this <code>Button</code>
* @beaninfo
* expert: true
* description: The AccessibleContext associated with this Button.
* @since 1.3
*/
public AccessibleContext getAccessibleContext() {
if (accessibleContext == null) {
accessibleContext = new AccessibleAWTButton();
}
return accessibleContext;
}
/** {@collect.stats}
* This class implements accessibility support for the
* <code>Button</code> class. It provides an implementation of the
* Java Accessibility API appropriate to button user-interface elements.
* @since 1.3
*/
protected class AccessibleAWTButton extends AccessibleAWTComponent
implements AccessibleAction, AccessibleValue
{
/*
* JDK 1.3 serialVersionUID
*/
private static final long serialVersionUID = -5932203980244017102L;
/** {@collect.stats}
* Get the accessible name of this object.
*
* @return the localized name of the object -- can be null if this
* object does not have a name
*/
public String getAccessibleName() {
if (accessibleName != null) {
return accessibleName;
} else {
if (getLabel() == null) {
return super.getAccessibleName();
} else {
return getLabel();
}
}
}
/** {@collect.stats}
* Get the AccessibleAction associated with this object. In the
* implementation of the Java Accessibility API for this class,
* return this object, which is responsible for implementing the
* AccessibleAction interface on behalf of itself.
*
* @return this object
*/
public AccessibleAction getAccessibleAction() {
return this;
}
/** {@collect.stats}
* Get the AccessibleValue associated with this object. In the
* implementation of the Java Accessibility API for this class,
* return this object, which is responsible for implementing the
* AccessibleValue interface on behalf of itself.
*
* @return this object
*/
public AccessibleValue getAccessibleValue() {
return this;
}
/** {@collect.stats}
* Returns the number of Actions available in this object. The
* default behavior of a button is to have one action - toggle
* the button.
*
* @return 1, the number of Actions in this object
*/
public int getAccessibleActionCount() {
return 1;
}
/** {@collect.stats}
* Return a description of the specified action of the object.
*
* @param i zero-based index of the actions
*/
public String getAccessibleActionDescription(int i) {
if (i == 0) {
// [[[PENDING: WDW -- need to provide a localized string]]]
return new String("click");
} else {
return null;
}
}
/** {@collect.stats}
* Perform the specified Action on the object
*
* @param i zero-based index of actions
* @return true if the the action was performed; else false.
*/
public boolean doAccessibleAction(int i) {
if (i == 0) {
// Simulate a button click
Toolkit.getEventQueue().postEvent(
new ActionEvent(Button.this,
ActionEvent.ACTION_PERFORMED,
Button.this.getActionCommand()));
return true;
} else {
return false;
}
}
/** {@collect.stats}
* Get the value of this object as a Number.
*
* @return An Integer of 0 if this isn't selected or an Integer of 1 if
* this is selected.
* @see javax.swing.AbstractButton#isSelected()
*/
public Number getCurrentAccessibleValue() {
return Integer.valueOf(0);
}
/** {@collect.stats}
* Set the value of this object as a Number.
*
* @return True if the value was set.
*/
public boolean setCurrentAccessibleValue(Number n) {
return false;
}
/** {@collect.stats}
* Get the minimum value of this object as a Number.
*
* @return An Integer of 0.
*/
public Number getMinimumAccessibleValue() {
return Integer.valueOf(0);
}
/** {@collect.stats}
* Get the maximum value of this object as a Number.
*
* @return An Integer of 0.
*/
public Number getMaximumAccessibleValue() {
return Integer.valueOf(0);
}
/** {@collect.stats}
* Get the role of this object.
*
* @return an instance of AccessibleRole describing the role of the
* object
* @see AccessibleRole
*/
public AccessibleRole getAccessibleRole() {
return AccessibleRole.PUSH_BUTTON;
}
} // inner class AccessibleAWTButton
}
|
Java
|
/*
* Copyright (c) 1995, 2006, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code 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
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package java.awt;
import java.awt.geom.Rectangle2D;
/** {@collect.stats}
* A <code>Rectangle</code> specifies an area in a coordinate space that is
* enclosed by the <code>Rectangle</code> object's upper-left point
* {@code (x,y)}
* in the coordinate space, its width, and its height.
* <p>
* A <code>Rectangle</code> object's <code>width</code> and
* <code>height</code> are <code>public</code> fields. The constructors
* that create a <code>Rectangle</code>, and the methods that can modify
* one, do not prevent setting a negative value for width or height.
* <p>
* <a name="Empty">
* A {@code Rectangle} whose width or height is exactly zero has location
* along those axes with zero dimension, but is otherwise considered empty.
* The {@link #isEmpty} method will return true for such a {@code Rectangle}.
* Methods which test if an empty {@code Rectangle} contains or intersects
* a point or rectangle will always return false if either dimension is zero.
* Methods which combine such a {@code Rectangle} with a point or rectangle
* will include the location of the {@code Rectangle} on that axis in the
* result as if the {@link #add(Point)} method were being called.
* </a>
* <p>
* <a name="NonExistant">
* A {@code Rectangle} whose width or height is negative has neither
* location nor dimension along those axes with negative dimensions.
* Such a {@code Rectangle} is treated as non-existant along those axes.
* Such a {@code Rectangle} is also empty with respect to containment
* calculations and methods which test if it contains or intersects a
* point or rectangle will always return false.
* Methods which combine such a {@code Rectangle} with a point or rectangle
* will ignore the {@code Rectangle} entirely in generating the result.
* If two {@code Rectangle} objects are combined and each has a negative
* dimension, the result will have at least one negative dimension.
* </a>
* <p>
* Methods which affect only the location of a {@code Rectangle} will
* operate on its location regardless of whether or not it has a negative
* or zero dimension along either axis.
* <p>
* Note that a {@code Rectangle} constructed with the default no-argument
* constructor will have dimensions of {@code 0x0} and therefore be empty.
* That {@code Rectangle} will still have a location of {@code (0,0)} and
* will contribute that location to the union and add operations.
* Code attempting to accumulate the bounds of a set of points should
* therefore initially construct the {@code Rectangle} with a specifically
* negative width and height or it should use the first point in the set
* to construct the {@code Rectangle}.
* For example:
* <pre>
* Rectangle bounds = new Rectangle(0, 0, -1, -1);
* for (int i = 0; i < points.length; i++) {
* bounds.add(points[i]);
* }
* </pre>
* or if we know that the points array contains at least one point:
* <pre>
* Rectangle bounds = new Rectangle(points[0]);
* for (int i = 1; i < points.length; i++) {
* bounds.add(points[i]);
* }
* </pre>
* <p>
* This class uses 32-bit integers to store its location and dimensions.
* Frequently operations may produce a result that exceeds the range of
* a 32-bit integer.
* The methods will calculate their results in a way that avoids any
* 32-bit overflow for intermediate results and then choose the best
* representation to store the final results back into the 32-bit fields
* which hold the location and dimensions.
* The location of the result will be stored into the {@link #x} and
* {@link #y} fields by clipping the true result to the nearest 32-bit value.
* The values stored into the {@link #width} and {@link #height} dimension
* fields will be chosen as the 32-bit values that encompass the largest
* part of the true result as possible.
* Generally this means that the dimension will be clipped independently
* to the range of 32-bit integers except that if the location had to be
* moved to store it into its pair of 32-bit fields then the dimensions
* will be adjusted relative to the "best representation" of the location.
* If the true result had a negative dimension and was therefore
* non-existant along one or both axes, the stored dimensions will be
* negative numbers in those axes.
* If the true result had a location that could be represented within
* the range of 32-bit integers, but zero dimension along one or both
* axes, then the stored dimensions will be zero in those axes.
*
* @author Sami Shaio
* @since 1.0
*/
public class Rectangle extends Rectangle2D
implements Shape, java.io.Serializable
{
/** {@collect.stats}
* The X coordinate of the upper-left corner of the <code>Rectangle</code>.
*
* @serial
* @see #setLocation(int, int)
* @see #getLocation()
* @since 1.0
*/
public int x;
/** {@collect.stats}
* The Y coordinate of the upper-left corner of the <code>Rectangle</code>.
*
* @serial
* @see #setLocation(int, int)
* @see #getLocation()
* @since 1.0
*/
public int y;
/** {@collect.stats}
* The width of the <code>Rectangle</code>.
* @serial
* @see #setSize(int, int)
* @see #getSize()
* @since 1.0
*/
public int width;
/** {@collect.stats}
* The height of the <code>Rectangle</code>.
*
* @serial
* @see #setSize(int, int)
* @see #getSize()
* @since 1.0
*/
public int height;
/*
* JDK 1.1 serialVersionUID
*/
private static final long serialVersionUID = -4345857070255674764L;
/** {@collect.stats}
* Initialize JNI field and method IDs
*/
private static native void initIDs();
static {
/* ensure that the necessary native libraries are loaded */
Toolkit.loadLibraries();
if (!GraphicsEnvironment.isHeadless()) {
initIDs();
}
}
/** {@collect.stats}
* Constructs a new <code>Rectangle</code> whose upper-left corner
* is at (0, 0) in the coordinate space, and whose width and
* height are both zero.
*/
public Rectangle() {
this(0, 0, 0, 0);
}
/** {@collect.stats}
* Constructs a new <code>Rectangle</code>, initialized to match
* the values of the specified <code>Rectangle</code>.
* @param r the <code>Rectangle</code> from which to copy initial values
* to a newly constructed <code>Rectangle</code>
* @since 1.1
*/
public Rectangle(Rectangle r) {
this(r.x, r.y, r.width, r.height);
}
/** {@collect.stats}
* Constructs a new <code>Rectangle</code> whose upper-left corner is
* specified as
* {@code (x,y)} and whose width and height
* are specified by the arguments of the same name.
* @param x the specified X coordinate
* @param y the specified Y coordinate
* @param width the width of the <code>Rectangle</code>
* @param height the height of the <code>Rectangle</code>
* @since 1.0
*/
public Rectangle(int x, int y, int width, int height) {
this.x = x;
this.y = y;
this.width = width;
this.height = height;
}
/** {@collect.stats}
* Constructs a new <code>Rectangle</code> whose upper-left corner
* is at (0, 0) in the coordinate space, and whose width and
* height are specified by the arguments of the same name.
* @param width the width of the <code>Rectangle</code>
* @param height the height of the <code>Rectangle</code>
*/
public Rectangle(int width, int height) {
this(0, 0, width, height);
}
/** {@collect.stats}
* Constructs a new <code>Rectangle</code> whose upper-left corner is
* specified by the {@link Point} argument, and
* whose width and height are specified by the
* {@link Dimension} argument.
* @param p a <code>Point</code> that is the upper-left corner of
* the <code>Rectangle</code>
* @param d a <code>Dimension</code>, representing the
* width and height of the <code>Rectangle</code>
*/
public Rectangle(Point p, Dimension d) {
this(p.x, p.y, d.width, d.height);
}
/** {@collect.stats}
* Constructs a new <code>Rectangle</code> whose upper-left corner is the
* specified <code>Point</code>, and whose width and height are both zero.
* @param p a <code>Point</code> that is the top left corner
* of the <code>Rectangle</code>
*/
public Rectangle(Point p) {
this(p.x, p.y, 0, 0);
}
/** {@collect.stats}
* Constructs a new <code>Rectangle</code> whose top left corner is
* (0, 0) and whose width and height are specified
* by the <code>Dimension</code> argument.
* @param d a <code>Dimension</code>, specifying width and height
*/
public Rectangle(Dimension d) {
this(0, 0, d.width, d.height);
}
/** {@collect.stats}
* Returns the X coordinate of the bounding <code>Rectangle</code> in
* <code>double</code> precision.
* @return the X coordinate of the bounding <code>Rectangle</code>.
*/
public double getX() {
return x;
}
/** {@collect.stats}
* Returns the Y coordinate of the bounding <code>Rectangle</code> in
* <code>double</code> precision.
* @return the Y coordinate of the bounding <code>Rectangle</code>.
*/
public double getY() {
return y;
}
/** {@collect.stats}
* Returns the width of the bounding <code>Rectangle</code> in
* <code>double</code> precision.
* @return the width of the bounding <code>Rectangle</code>.
*/
public double getWidth() {
return width;
}
/** {@collect.stats}
* Returns the height of the bounding <code>Rectangle</code> in
* <code>double</code> precision.
* @return the height of the bounding <code>Rectangle</code>.
*/
public double getHeight() {
return height;
}
/** {@collect.stats}
* Gets the bounding <code>Rectangle</code> of this <code>Rectangle</code>.
* <p>
* This method is included for completeness, to parallel the
* <code>getBounds</code> method of
* {@link Component}.
* @return a new <code>Rectangle</code>, equal to the
* bounding <code>Rectangle</code> for this <code>Rectangle</code>.
* @see java.awt.Component#getBounds
* @see #setBounds(Rectangle)
* @see #setBounds(int, int, int, int)
* @since 1.1
*/
public Rectangle getBounds() {
return new Rectangle(x, y, width, height);
}
/** {@collect.stats}
* {@inheritDoc}
* @since 1.2
*/
public Rectangle2D getBounds2D() {
return new Rectangle(x, y, width, height);
}
/** {@collect.stats}
* Sets the bounding <code>Rectangle</code> of this <code>Rectangle</code>
* to match the specified <code>Rectangle</code>.
* <p>
* This method is included for completeness, to parallel the
* <code>setBounds</code> method of <code>Component</code>.
* @param r the specified <code>Rectangle</code>
* @see #getBounds
* @see java.awt.Component#setBounds(java.awt.Rectangle)
* @since 1.1
*/
public void setBounds(Rectangle r) {
setBounds(r.x, r.y, r.width, r.height);
}
/** {@collect.stats}
* Sets the bounding <code>Rectangle</code> of this
* <code>Rectangle</code> to the specified
* <code>x</code>, <code>y</code>, <code>width</code>,
* and <code>height</code>.
* <p>
* This method is included for completeness, to parallel the
* <code>setBounds</code> method of <code>Component</code>.
* @param x the new X coordinate for the upper-left
* corner of this <code>Rectangle</code>
* @param y the new Y coordinate for the upper-left
* corner of this <code>Rectangle</code>
* @param width the new width for this <code>Rectangle</code>
* @param height the new height for this <code>Rectangle</code>
* @see #getBounds
* @see java.awt.Component#setBounds(int, int, int, int)
* @since 1.1
*/
public void setBounds(int x, int y, int width, int height) {
reshape(x, y, width, height);
}
/** {@collect.stats}
* Sets the bounds of this {@code Rectangle} to the integer bounds
* which encompass the specified {@code x}, {@code y}, {@code width},
* and {@code height}.
* If the parameters specify a {@code Rectangle} that exceeds the
* maximum range of integers, the result will be the best
* representation of the specified {@code Rectangle} intersected
* with the maximum integer bounds.
* @param x the X coordinate of the upper-left corner of
* the specified rectangle
* @param y the Y coordinate of the upper-left corner of
* the specified rectangle
* @param width the width of the specified rectangle
* @param height the new height of the specified rectangle
*/
public void setRect(double x, double y, double width, double height) {
int newx, newy, neww, newh;
if (x > 2.0 * Integer.MAX_VALUE) {
// Too far in positive X direction to represent...
// We cannot even reach the left side of the specified
// rectangle even with both x & width set to MAX_VALUE.
// The intersection with the "maximal integer rectangle"
// is non-existant so we should use a width < 0.
// REMIND: Should we try to determine a more "meaningful"
// adjusted value for neww than just "-1"?
newx = Integer.MAX_VALUE;
neww = -1;
} else {
newx = clip(x, false);
if (width >= 0) width += x-newx;
neww = clip(width, width >= 0);
}
if (y > 2.0 * Integer.MAX_VALUE) {
// Too far in positive Y direction to represent...
newy = Integer.MAX_VALUE;
newh = -1;
} else {
newy = clip(y, false);
if (height >= 0) height += y-newy;
newh = clip(height, height >= 0);
}
reshape(newx, newy, neww, newh);
}
// Return best integer representation for v, clipped to integer
// range and floor-ed or ceiling-ed, depending on the boolean.
private static int clip(double v, boolean doceil) {
if (v <= Integer.MIN_VALUE) {
return Integer.MIN_VALUE;
}
if (v >= Integer.MAX_VALUE) {
return Integer.MAX_VALUE;
}
return (int) (doceil ? Math.ceil(v) : Math.floor(v));
}
/** {@collect.stats}
* Sets the bounding <code>Rectangle</code> of this
* <code>Rectangle</code> to the specified
* <code>x</code>, <code>y</code>, <code>width</code>,
* and <code>height</code>.
* <p>
* @param x the new X coordinate for the upper-left
* corner of this <code>Rectangle</code>
* @param y the new Y coordinate for the upper-left
* corner of this <code>Rectangle</code>
* @param width the new width for this <code>Rectangle</code>
* @param height the new height for this <code>Rectangle</code>
* @deprecated As of JDK version 1.1,
* replaced by <code>setBounds(int, int, int, int)</code>.
*/
@Deprecated
public void reshape(int x, int y, int width, int height) {
this.x = x;
this.y = y;
this.width = width;
this.height = height;
}
/** {@collect.stats}
* Returns the location of this <code>Rectangle</code>.
* <p>
* This method is included for completeness, to parallel the
* <code>getLocation</code> method of <code>Component</code>.
* @return the <code>Point</code> that is the upper-left corner of
* this <code>Rectangle</code>.
* @see java.awt.Component#getLocation
* @see #setLocation(Point)
* @see #setLocation(int, int)
* @since 1.1
*/
public Point getLocation() {
return new Point(x, y);
}
/** {@collect.stats}
* Moves this <code>Rectangle</code> to the specified location.
* <p>
* This method is included for completeness, to parallel the
* <code>setLocation</code> method of <code>Component</code>.
* @param p the <code>Point</code> specifying the new location
* for this <code>Rectangle</code>
* @see java.awt.Component#setLocation(java.awt.Point)
* @see #getLocation
* @since 1.1
*/
public void setLocation(Point p) {
setLocation(p.x, p.y);
}
/** {@collect.stats}
* Moves this <code>Rectangle</code> to the specified location.
* <p>
* This method is included for completeness, to parallel the
* <code>setLocation</code> method of <code>Component</code>.
* @param x the X coordinate of the new location
* @param y the Y coordinate of the new location
* @see #getLocation
* @see java.awt.Component#setLocation(int, int)
* @since 1.1
*/
public void setLocation(int x, int y) {
move(x, y);
}
/** {@collect.stats}
* Moves this <code>Rectangle</code> to the specified location.
* <p>
* @param x the X coordinate of the new location
* @param y the Y coordinate of the new location
* @deprecated As of JDK version 1.1,
* replaced by <code>setLocation(int, int)</code>.
*/
@Deprecated
public void move(int x, int y) {
this.x = x;
this.y = y;
}
/** {@collect.stats}
* Translates this <code>Rectangle</code> the indicated distance,
* to the right along the X coordinate axis, and
* downward along the Y coordinate axis.
* @param dx the distance to move this <code>Rectangle</code>
* along the X axis
* @param dy the distance to move this <code>Rectangle</code>
* along the Y axis
* @see java.awt.Rectangle#setLocation(int, int)
* @see java.awt.Rectangle#setLocation(java.awt.Point)
*/
public void translate(int dx, int dy) {
int oldv = this.x;
int newv = oldv + dx;
if (dx < 0) {
// moving leftward
if (newv > oldv) {
// negative overflow
// Only adjust width if it was valid (>= 0).
if (width >= 0) {
// The right edge is now conceptually at
// newv+width, but we may move newv to prevent
// overflow. But we want the right edge to
// remain at its new location in spite of the
// clipping. Think of the following adjustment
// conceptually the same as:
// width += newv; newv = MIN_VALUE; width -= newv;
width += newv - Integer.MIN_VALUE;
// width may go negative if the right edge went past
// MIN_VALUE, but it cannot overflow since it cannot
// have moved more than MIN_VALUE and any non-negative
// number + MIN_VALUE does not overflow.
}
newv = Integer.MIN_VALUE;
}
} else {
// moving rightward (or staying still)
if (newv < oldv) {
// positive overflow
if (width >= 0) {
// Conceptually the same as:
// width += newv; newv = MAX_VALUE; width -= newv;
width += newv - Integer.MAX_VALUE;
// With large widths and large displacements
// we may overflow so we need to check it.
if (width < 0) width = Integer.MAX_VALUE;
}
newv = Integer.MAX_VALUE;
}
}
this.x = newv;
oldv = this.y;
newv = oldv + dy;
if (dy < 0) {
// moving upward
if (newv > oldv) {
// negative overflow
if (height >= 0) {
height += newv - Integer.MIN_VALUE;
// See above comment about no overflow in this case
}
newv = Integer.MIN_VALUE;
}
} else {
// moving downward (or staying still)
if (newv < oldv) {
// positive overflow
if (height >= 0) {
height += newv - Integer.MAX_VALUE;
if (height < 0) height = Integer.MAX_VALUE;
}
newv = Integer.MAX_VALUE;
}
}
this.y = newv;
}
/** {@collect.stats}
* Gets the size of this <code>Rectangle</code>, represented by
* the returned <code>Dimension</code>.
* <p>
* This method is included for completeness, to parallel the
* <code>getSize</code> method of <code>Component</code>.
* @return a <code>Dimension</code>, representing the size of
* this <code>Rectangle</code>.
* @see java.awt.Component#getSize
* @see #setSize(Dimension)
* @see #setSize(int, int)
* @since 1.1
*/
public Dimension getSize() {
return new Dimension(width, height);
}
/** {@collect.stats}
* Sets the size of this <code>Rectangle</code> to match the
* specified <code>Dimension</code>.
* <p>
* This method is included for completeness, to parallel the
* <code>setSize</code> method of <code>Component</code>.
* @param d the new size for the <code>Dimension</code> object
* @see java.awt.Component#setSize(java.awt.Dimension)
* @see #getSize
* @since 1.1
*/
public void setSize(Dimension d) {
setSize(d.width, d.height);
}
/** {@collect.stats}
* Sets the size of this <code>Rectangle</code> to the specified
* width and height.
* <p>
* This method is included for completeness, to parallel the
* <code>setSize</code> method of <code>Component</code>.
* @param width the new width for this <code>Rectangle</code>
* @param height the new height for this <code>Rectangle</code>
* @see java.awt.Component#setSize(int, int)
* @see #getSize
* @since 1.1
*/
public void setSize(int width, int height) {
resize(width, height);
}
/** {@collect.stats}
* Sets the size of this <code>Rectangle</code> to the specified
* width and height.
* <p>
* @param width the new width for this <code>Rectangle</code>
* @param height the new height for this <code>Rectangle</code>
* @deprecated As of JDK version 1.1,
* replaced by <code>setSize(int, int)</code>.
*/
@Deprecated
public void resize(int width, int height) {
this.width = width;
this.height = height;
}
/** {@collect.stats}
* Checks whether or not this <code>Rectangle</code> contains the
* specified <code>Point</code>.
* @param p the <code>Point</code> to test
* @return <code>true</code> if the specified <code>Point</code>
* is inside this <code>Rectangle</code>;
* <code>false</code> otherwise.
* @since 1.1
*/
public boolean contains(Point p) {
return contains(p.x, p.y);
}
/** {@collect.stats}
* Checks whether or not this <code>Rectangle</code> contains the
* point at the specified location {@code (x,y)}.
*
* @param x the specified X coordinate
* @param y the specified Y coordinate
* @return <code>true</code> if the point
* {@code (x,y)} is inside this
* <code>Rectangle</code>;
* <code>false</code> otherwise.
* @since 1.1
*/
public boolean contains(int x, int y) {
return inside(x, y);
}
/** {@collect.stats}
* Checks whether or not this <code>Rectangle</code> entirely contains
* the specified <code>Rectangle</code>.
*
* @param r the specified <code>Rectangle</code>
* @return <code>true</code> if the <code>Rectangle</code>
* is contained entirely inside this <code>Rectangle</code>;
* <code>false</code> otherwise
* @since 1.2
*/
public boolean contains(Rectangle r) {
return contains(r.x, r.y, r.width, r.height);
}
/** {@collect.stats}
* Checks whether this <code>Rectangle</code> entirely contains
* the <code>Rectangle</code>
* at the specified location {@code (X,Y)} with the
* specified dimensions {@code (W,H)}.
* @param X the specified X coordinate
* @param Y the specified Y coordinate
* @param W the width of the <code>Rectangle</code>
* @param H the height of the <code>Rectangle</code>
* @return <code>true</code> if the <code>Rectangle</code> specified by
* {@code (X, Y, W, H)}
* is entirely enclosed inside this <code>Rectangle</code>;
* <code>false</code> otherwise.
* @since 1.1
*/
public boolean contains(int X, int Y, int W, int H) {
int w = this.width;
int h = this.height;
if ((w | h | W | H) < 0) {
// At least one of the dimensions is negative...
return false;
}
// Note: if any dimension is zero, tests below must return false...
int x = this.x;
int y = this.y;
if (X < x || Y < y) {
return false;
}
w += x;
W += X;
if (W <= X) {
// X+W overflowed or W was zero, return false if...
// either original w or W was zero or
// x+w did not overflow or
// the overflowed x+w is smaller than the overflowed X+W
if (w >= x || W > w) return false;
} else {
// X+W did not overflow and W was not zero, return false if...
// original w was zero or
// x+w did not overflow and x+w is smaller than X+W
if (w >= x && W > w) return false;
}
h += y;
H += Y;
if (H <= Y) {
if (h >= y || H > h) return false;
} else {
if (h >= y && H > h) return false;
}
return true;
}
/** {@collect.stats}
* Checks whether or not this <code>Rectangle</code> contains the
* point at the specified location {@code (X,Y)}.
*
* @param X the specified X coordinate
* @param Y the specified Y coordinate
* @return <code>true</code> if the point
* {@code (X,Y)} is inside this
* <code>Rectangle</code>;
* <code>false</code> otherwise.
* @deprecated As of JDK version 1.1,
* replaced by <code>contains(int, int)</code>.
*/
@Deprecated
public boolean inside(int X, int Y) {
int w = this.width;
int h = this.height;
if ((w | h) < 0) {
// At least one of the dimensions is negative...
return false;
}
// Note: if either dimension is zero, tests below must return false...
int x = this.x;
int y = this.y;
if (X < x || Y < y) {
return false;
}
w += x;
h += y;
// overflow || intersect
return ((w < x || w > X) &&
(h < y || h > Y));
}
/** {@collect.stats}
* Determines whether or not this <code>Rectangle</code> and the specified
* <code>Rectangle</code> intersect. Two rectangles intersect if
* their intersection is nonempty.
*
* @param r the specified <code>Rectangle</code>
* @return <code>true</code> if the specified <code>Rectangle</code>
* and this <code>Rectangle</code> intersect;
* <code>false</code> otherwise.
*/
public boolean intersects(Rectangle r) {
int tw = this.width;
int th = this.height;
int rw = r.width;
int rh = r.height;
if (rw <= 0 || rh <= 0 || tw <= 0 || th <= 0) {
return false;
}
int tx = this.x;
int ty = this.y;
int rx = r.x;
int ry = r.y;
rw += rx;
rh += ry;
tw += tx;
th += ty;
// overflow || intersect
return ((rw < rx || rw > tx) &&
(rh < ry || rh > ty) &&
(tw < tx || tw > rx) &&
(th < ty || th > ry));
}
/** {@collect.stats}
* Computes the intersection of this <code>Rectangle</code> with the
* specified <code>Rectangle</code>. Returns a new <code>Rectangle</code>
* that represents the intersection of the two rectangles.
* If the two rectangles do not intersect, the result will be
* an empty rectangle.
*
* @param r the specified <code>Rectangle</code>
* @return the largest <code>Rectangle</code> contained in both the
* specified <code>Rectangle</code> and in
* this <code>Rectangle</code>; or if the rectangles
* do not intersect, an empty rectangle.
*/
public Rectangle intersection(Rectangle r) {
int tx1 = this.x;
int ty1 = this.y;
int rx1 = r.x;
int ry1 = r.y;
long tx2 = tx1; tx2 += this.width;
long ty2 = ty1; ty2 += this.height;
long rx2 = rx1; rx2 += r.width;
long ry2 = ry1; ry2 += r.height;
if (tx1 < rx1) tx1 = rx1;
if (ty1 < ry1) ty1 = ry1;
if (tx2 > rx2) tx2 = rx2;
if (ty2 > ry2) ty2 = ry2;
tx2 -= tx1;
ty2 -= ty1;
// tx2,ty2 will never overflow (they will never be
// larger than the smallest of the two source w,h)
// they might underflow, though...
if (tx2 < Integer.MIN_VALUE) tx2 = Integer.MIN_VALUE;
if (ty2 < Integer.MIN_VALUE) ty2 = Integer.MIN_VALUE;
return new Rectangle(tx1, ty1, (int) tx2, (int) ty2);
}
/** {@collect.stats}
* Computes the union of this <code>Rectangle</code> with the
* specified <code>Rectangle</code>. Returns a new
* <code>Rectangle</code> that
* represents the union of the two rectangles.
* <p>
* If either {@code Rectangle} has any dimension less than zero
* the rules for <a href=#NonExistant>non-existant</a> rectangles
* apply.
* If only one has a dimension less than zero, then the result
* will be a copy of the other {@code Rectangle}.
* If both have dimension less than zero, then the result will
* have at least one dimension less than zero.
* <p>
* If the resulting {@code Rectangle} would have a dimension
* too large to be expressed as an {@code int}, the result
* will have a dimension of {@code Integer.MAX_VALUE} along
* that dimension.
* @param r the specified <code>Rectangle</code>
* @return the smallest <code>Rectangle</code> containing both
* the specified <code>Rectangle</code> and this
* <code>Rectangle</code>.
*/
public Rectangle union(Rectangle r) {
long tx2 = this.width;
long ty2 = this.height;
if ((tx2 | ty2) < 0) {
// This rectangle has negative dimensions...
// If r has non-negative dimensions then it is the answer.
// If r is non-existant (has a negative dimension), then both
// are non-existant and we can return any non-existant rectangle
// as an answer. Thus, returning r meets that criterion.
// Either way, r is our answer.
return new Rectangle(r);
}
long rx2 = r.width;
long ry2 = r.height;
if ((rx2 | ry2) < 0) {
return new Rectangle(this);
}
int tx1 = this.x;
int ty1 = this.y;
tx2 += tx1;
ty2 += ty1;
int rx1 = r.x;
int ry1 = r.y;
rx2 += rx1;
ry2 += ry1;
if (tx1 > rx1) tx1 = rx1;
if (ty1 > ry1) ty1 = ry1;
if (tx2 < rx2) tx2 = rx2;
if (ty2 < ry2) ty2 = ry2;
tx2 -= tx1;
ty2 -= ty1;
// tx2,ty2 will never underflow since both original rectangles
// were already proven to be non-empty
// they might overflow, though...
if (tx2 > Integer.MAX_VALUE) tx2 = Integer.MAX_VALUE;
if (ty2 > Integer.MAX_VALUE) ty2 = Integer.MAX_VALUE;
return new Rectangle(tx1, ty1, (int) tx2, (int) ty2);
}
/** {@collect.stats}
* Adds a point, specified by the integer arguments {@code newx,newy}
* to the bounds of this {@code Rectangle}.
* <p>
* If this {@code Rectangle} has any dimension less than zero,
* the rules for <a href=#NonExistant>non-existant</a>
* rectangles apply.
* In that case, the new bounds of this {@code Rectangle} will
* have a location equal to the specified coordinates and
* width and height equal to zero.
* <p>
* After adding a point, a call to <code>contains</code> with the
* added point as an argument does not necessarily return
* <code>true</code>. The <code>contains</code> method does not
* return <code>true</code> for points on the right or bottom
* edges of a <code>Rectangle</code>. Therefore, if the added point
* falls on the right or bottom edge of the enlarged
* <code>Rectangle</code>, <code>contains</code> returns
* <code>false</code> for that point.
* If the specified point must be contained within the new
* {@code Rectangle}, a 1x1 rectangle should be added instead:
* <pre>
* r.add(newx, newy, 1, 1);
* </pre>
* @param newx the X coordinate of the new point
* @param newy the Y coordinate of the new point
*/
public void add(int newx, int newy) {
if ((width | height) < 0) {
this.x = newx;
this.y = newy;
this.width = this.height = 0;
return;
}
int x1 = this.x;
int y1 = this.y;
long x2 = this.width;
long y2 = this.height;
x2 += x1;
y2 += y1;
if (x1 > newx) x1 = newx;
if (y1 > newy) y1 = newy;
if (x2 < newx) x2 = newx;
if (y2 < newy) y2 = newy;
x2 -= x1;
y2 -= y1;
if (x2 > Integer.MAX_VALUE) x2 = Integer.MAX_VALUE;
if (y2 > Integer.MAX_VALUE) y2 = Integer.MAX_VALUE;
reshape(x1, y1, (int) x2, (int) y2);
}
/** {@collect.stats}
* Adds the specified {@code Point} to the bounds of this
* {@code Rectangle}.
* <p>
* If this {@code Rectangle} has any dimension less than zero,
* the rules for <a href=#NonExistant>non-existant</a>
* rectangles apply.
* In that case, the new bounds of this {@code Rectangle} will
* have a location equal to the coordinates of the specified
* {@code Point} and width and height equal to zero.
* <p>
* After adding a <code>Point</code>, a call to <code>contains</code>
* with the added <code>Point</code> as an argument does not
* necessarily return <code>true</code>. The <code>contains</code>
* method does not return <code>true</code> for points on the right
* or bottom edges of a <code>Rectangle</code>. Therefore if the added
* <code>Point</code> falls on the right or bottom edge of the
* enlarged <code>Rectangle</code>, <code>contains</code> returns
* <code>false</code> for that <code>Point</code>.
* If the specified point must be contained within the new
* {@code Rectangle}, a 1x1 rectangle should be added instead:
* <pre>
* r.add(pt.x, pt.y, 1, 1);
* </pre>
* @param pt the new <code>Point</code> to add to this
* <code>Rectangle</code>
*/
public void add(Point pt) {
add(pt.x, pt.y);
}
/** {@collect.stats}
* Adds a <code>Rectangle</code> to this <code>Rectangle</code>.
* The resulting <code>Rectangle</code> is the union of the two
* rectangles.
* <p>
* If either {@code Rectangle} has any dimension less than 0, the
* result will have the dimensions of the other {@code Rectangle}.
* If both {@code Rectangle}s have at least one dimension less
* than 0, the result will have at least one dimension less than 0.
* <p>
* If either {@code Rectangle} has one or both dimensions equal
* to 0, the result along those axes with 0 dimensions will be
* equivalent to the results obtained by adding the corresponding
* origin coordinate to the result rectangle along that axis,
* similar to the operation of the {@link #add(Point)} method,
* but contribute no further dimension beyond that.
* <p>
* If the resulting {@code Rectangle} would have a dimension
* too large to be expressed as an {@code int}, the result
* will have a dimension of {@code Integer.MAX_VALUE} along
* that dimension.
* @param r the specified <code>Rectangle</code>
*/
public void add(Rectangle r) {
long tx2 = this.width;
long ty2 = this.height;
if ((tx2 | ty2) < 0) {
reshape(r.x, r.y, r.width, r.height);
}
long rx2 = r.width;
long ry2 = r.height;
if ((rx2 | ry2) < 0) {
return;
}
int tx1 = this.x;
int ty1 = this.y;
tx2 += tx1;
ty2 += ty1;
int rx1 = r.x;
int ry1 = r.y;
rx2 += rx1;
ry2 += ry1;
if (tx1 > rx1) tx1 = rx1;
if (ty1 > ry1) ty1 = ry1;
if (tx2 < rx2) tx2 = rx2;
if (ty2 < ry2) ty2 = ry2;
tx2 -= tx1;
ty2 -= ty1;
// tx2,ty2 will never underflow since both original
// rectangles were non-empty
// they might overflow, though...
if (tx2 > Integer.MAX_VALUE) tx2 = Integer.MAX_VALUE;
if (ty2 > Integer.MAX_VALUE) ty2 = Integer.MAX_VALUE;
reshape(tx1, ty1, (int) tx2, (int) ty2);
}
/** {@collect.stats}
* Resizes the <code>Rectangle</code> both horizontally and vertically.
* <p>
* This method modifies the <code>Rectangle</code> so that it is
* <code>h</code> units larger on both the left and right side,
* and <code>v</code> units larger at both the top and bottom.
* <p>
* The new <code>Rectangle</code> has {@code (x - h, y - v)}
* as its upper-left corner,
* width of {@code (width + 2h)},
* and a height of {@code (height + 2v)}.
* <p>
* If negative values are supplied for <code>h</code> and
* <code>v</code>, the size of the <code>Rectangle</code>
* decreases accordingly.
* The {@code grow} method will check for integer overflow
* and underflow, but does not check whether the resulting
* values of {@code width} and {@code height} grow
* from negative to non-negative or shrink from non-negative
* to negative.
* @param h the horizontal expansion
* @param v the vertical expansion
*/
public void grow(int h, int v) {
long x0 = this.x;
long y0 = this.y;
long x1 = this.width;
long y1 = this.height;
x1 += x0;
y1 += y0;
x0 -= h;
y0 -= v;
x1 += h;
y1 += v;
if (x1 < x0) {
// Non-existant in X direction
// Final width must remain negative so subtract x0 before
// it is clipped so that we avoid the risk that the clipping
// of x0 will reverse the ordering of x0 and x1.
x1 -= x0;
if (x1 < Integer.MIN_VALUE) x1 = Integer.MIN_VALUE;
if (x0 < Integer.MIN_VALUE) x0 = Integer.MIN_VALUE;
else if (x0 > Integer.MAX_VALUE) x0 = Integer.MAX_VALUE;
} else { // (x1 >= x0)
// Clip x0 before we subtract it from x1 in case the clipping
// affects the representable area of the rectangle.
if (x0 < Integer.MIN_VALUE) x0 = Integer.MIN_VALUE;
else if (x0 > Integer.MAX_VALUE) x0 = Integer.MAX_VALUE;
x1 -= x0;
// The only way x1 can be negative now is if we clipped
// x0 against MIN and x1 is less than MIN - in which case
// we want to leave the width negative since the result
// did not intersect the representable area.
if (x1 < Integer.MIN_VALUE) x1 = Integer.MIN_VALUE;
else if (x1 > Integer.MAX_VALUE) x1 = Integer.MAX_VALUE;
}
if (y1 < y0) {
// Non-existant in Y direction
y1 -= y0;
if (y1 < Integer.MIN_VALUE) y1 = Integer.MIN_VALUE;
if (y0 < Integer.MIN_VALUE) y0 = Integer.MIN_VALUE;
else if (y0 > Integer.MAX_VALUE) y0 = Integer.MAX_VALUE;
} else { // (y1 >= y0)
if (y0 < Integer.MIN_VALUE) y0 = Integer.MIN_VALUE;
else if (y0 > Integer.MAX_VALUE) y0 = Integer.MAX_VALUE;
y1 -= y0;
if (y1 < Integer.MIN_VALUE) y1 = Integer.MIN_VALUE;
else if (y1 > Integer.MAX_VALUE) y1 = Integer.MAX_VALUE;
}
reshape((int) x0, (int) y0, (int) x1, (int) y1);
}
/** {@collect.stats}
* {@inheritDoc}
* @since 1.2
*/
public boolean isEmpty() {
return (width <= 0) || (height <= 0);
}
/** {@collect.stats}
* {@inheritDoc}
* @since 1.2
*/
public int outcode(double x, double y) {
/*
* Note on casts to double below. If the arithmetic of
* x+w or y+h is done in int, then we may get integer
* overflow. By converting to double before the addition
* we force the addition to be carried out in double to
* avoid overflow in the comparison.
*
* See bug 4320890 for problems that this can cause.
*/
int out = 0;
if (this.width <= 0) {
out |= OUT_LEFT | OUT_RIGHT;
} else if (x < this.x) {
out |= OUT_LEFT;
} else if (x > this.x + (double) this.width) {
out |= OUT_RIGHT;
}
if (this.height <= 0) {
out |= OUT_TOP | OUT_BOTTOM;
} else if (y < this.y) {
out |= OUT_TOP;
} else if (y > this.y + (double) this.height) {
out |= OUT_BOTTOM;
}
return out;
}
/** {@collect.stats}
* {@inheritDoc}
* @since 1.2
*/
public Rectangle2D createIntersection(Rectangle2D r) {
if (r instanceof Rectangle) {
return intersection((Rectangle) r);
}
Rectangle2D dest = new Rectangle2D.Double();
Rectangle2D.intersect(this, r, dest);
return dest;
}
/** {@collect.stats}
* {@inheritDoc}
* @since 1.2
*/
public Rectangle2D createUnion(Rectangle2D r) {
if (r instanceof Rectangle) {
return union((Rectangle) r);
}
Rectangle2D dest = new Rectangle2D.Double();
Rectangle2D.union(this, r, dest);
return dest;
}
/** {@collect.stats}
* Checks whether two rectangles are equal.
* <p>
* The result is <code>true</code> if and only if the argument is not
* <code>null</code> and is a <code>Rectangle</code> object that has the
* same upper-left corner, width, and height as
* this <code>Rectangle</code>.
* @param obj the <code>Object</code> to compare with
* this <code>Rectangle</code>
* @return <code>true</code> if the objects are equal;
* <code>false</code> otherwise.
*/
public boolean equals(Object obj) {
if (obj instanceof Rectangle) {
Rectangle r = (Rectangle)obj;
return ((x == r.x) &&
(y == r.y) &&
(width == r.width) &&
(height == r.height));
}
return super.equals(obj);
}
/** {@collect.stats}
* Returns a <code>String</code> representing this
* <code>Rectangle</code> and its values.
* @return a <code>String</code> representing this
* <code>Rectangle</code> object's coordinate and size values.
*/
public String toString() {
return getClass().getName() + "[x=" + x + ",y=" + y + ",width=" + width + ",height=" + height + "]";
}
}
|
Java
|
/*
* Copyright (c) 2003, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code 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
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package java.awt;
import sun.security.util.SecurityConstants;
/** {@collect.stats}
* <code>MouseInfo</code> provides methods for getting information about the mouse,
* such as mouse pointer location and the number of mouse buttons.
*
* @author Roman Poborchiy
* @since 1.5
*/
public class MouseInfo {
/** {@collect.stats}
* Private constructor to prevent instantiation.
*/
private MouseInfo() {
}
/** {@collect.stats}
* Returns a <code>PointerInfo</code> instance that represents the current
* location of the mouse pointer.
* The <code>GraphicsDevice</code> stored in this <code>PointerInfo</code>
* contains the mouse pointer. The coordinate system used for the mouse position
* depends on whether or not the <code>GraphicsDevice</code> is part of a virtual
* screen device.
* For virtual screen devices, the coordinates are given in the virtual
* coordinate system, otherwise they are returned in the coordinate system
* of the <code>GraphicsDevice</code>. See {@link GraphicsConfiguration}
* for more information about the virtual screen devices.
* On systems without a mouse, returns <code>null</code>.
* <p>
* If there is a security manager, its <code>checkPermission</code> method
* is called with an <code>AWTPermission("watchMousePointer")</code>
* permission before creating and returning a <code>PointerInfo</code>
* object. This may result in a <code>SecurityException</code>.
*
* @exception HeadlessException if GraphicsEnvironment.isHeadless() returns true
* @exception SecurityException if a security manager exists and its
* <code>checkPermission</code> method doesn't allow the operation
* @see GraphicsConfiguration
* @see SecurityManager#checkPermission
* @see java.awt.AWTPermission
* @return location of the mouse pointer
* @since 1.5
*/
public static PointerInfo getPointerInfo() throws HeadlessException {
if (GraphicsEnvironment.isHeadless()) {
throw new HeadlessException();
}
SecurityManager security = System.getSecurityManager();
if (security != null) {
security.checkPermission(SecurityConstants.WATCH_MOUSE_PERMISSION);
}
Point point = new Point(0, 0);
int deviceNum = Toolkit.getDefaultToolkit().getMouseInfoPeer().fillPointWithCoords(point);
GraphicsDevice[] gds = GraphicsEnvironment.getLocalGraphicsEnvironment().
getScreenDevices();
PointerInfo retval = null;
if (areScreenDevicesIndependent(gds)) {
retval = new PointerInfo(gds[deviceNum], point);
} else {
for (int i = 0; i < gds.length; i++) {
GraphicsConfiguration gc = gds[i].getDefaultConfiguration();
Rectangle bounds = gc.getBounds();
if (bounds.contains(point)) {
retval = new PointerInfo(gds[i], point);
}
}
}
return retval;
}
private static boolean areScreenDevicesIndependent(GraphicsDevice[] gds) {
for (int i = 0; i < gds.length; i++) {
Rectangle bounds = gds[i].getDefaultConfiguration().getBounds();
if (bounds.x != 0 || bounds.y != 0) {
return false;
}
}
return true;
}
/** {@collect.stats}
* Returns the number of buttons on the mouse.
* On systems without a mouse, returns <code>-1</code>.
*
* @exception HeadlessException if GraphicsEnvironment.isHeadless() returns true
* @return number of buttons on the mouse
* @since 1.5
*/
public static int getNumberOfButtons() throws HeadlessException {
if (GraphicsEnvironment.isHeadless()) {
throw new HeadlessException();
}
Object prop = Toolkit.getDefaultToolkit().
getDesktopProperty("awt.mouse.numButtons");
if (prop instanceof Integer) {
return ((Integer)prop).intValue();
}
// This should never happen.
assert false : "awt.mouse.numButtons is not an integer property";
return 0;
}
}
|
Java
|
/*
* Copyright (c) 2006, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code 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
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package java.awt;
import java.awt.MultipleGradientPaint.CycleMethod;
import java.awt.MultipleGradientPaint.ColorSpaceType;
import java.awt.geom.AffineTransform;
import java.awt.geom.Point2D;
import java.awt.geom.Rectangle2D;
import java.awt.image.ColorModel;
/** {@collect.stats}
* Provides the actual implementation for the LinearGradientPaint.
* This is where the pixel processing is done.
*
* @see java.awt.LinearGradientPaint
* @see java.awt.PaintContext
* @see java.awt.Paint
* @author Nicholas Talian, Vincent Hardy, Jim Graham, Jerry Evans
*/
final class LinearGradientPaintContext extends MultipleGradientPaintContext {
/** {@collect.stats}
* The following invariants are used to process the gradient value from
* a device space coordinate, (X, Y):
* g(X, Y) = dgdX*X + dgdY*Y + gc
*/
private float dgdX, dgdY, gc;
/** {@collect.stats}
* Constructor for LinearGradientPaintContext.
*
* @param paint the {@code LinearGradientPaint} from which this context
* is created
* @param cm {@code ColorModel} that receives
* the <code>Paint</code> data. This is used only as a hint.
* @param deviceBounds the device space bounding box of the
* graphics primitive being rendered
* @param userBounds the user space bounding box of the
* graphics primitive being rendered
* @param t the {@code AffineTransform} from user
* space into device space (gradientTransform should be
* concatenated with this)
* @param hints the hints that the context object uses to choose
* between rendering alternatives
* @param dStart gradient start point, in user space
* @param dEnd gradient end point, in user space
* @param fractions the fractions specifying the gradient distribution
* @param colors the gradient colors
* @param cycleMethod either NO_CYCLE, REFLECT, or REPEAT
* @param colorSpace which colorspace to use for interpolation,
* either SRGB or LINEAR_RGB
*/
LinearGradientPaintContext(LinearGradientPaint paint,
ColorModel cm,
Rectangle deviceBounds,
Rectangle2D userBounds,
AffineTransform t,
RenderingHints hints,
Point2D start,
Point2D end,
float[] fractions,
Color[] colors,
CycleMethod cycleMethod,
ColorSpaceType colorSpace)
{
super(paint, cm, deviceBounds, userBounds, t, hints, fractions,
colors, cycleMethod, colorSpace);
// A given point in the raster should take on the same color as its
// projection onto the gradient vector.
// Thus, we want the projection of the current position vector
// onto the gradient vector, then normalized with respect to the
// length of the gradient vector, giving a value which can be mapped
// into the range 0-1.
// projection =
// currentVector dot gradientVector / length(gradientVector)
// normalized = projection / length(gradientVector)
float startx = (float)start.getX();
float starty = (float)start.getY();
float endx = (float)end.getX();
float endy = (float)end.getY();
float dx = endx - startx; // change in x from start to end
float dy = endy - starty; // change in y from start to end
float dSq = dx*dx + dy*dy; // total distance squared
// avoid repeated calculations by doing these divides once
float constX = dx/dSq;
float constY = dy/dSq;
// incremental change along gradient for +x
dgdX = a00*constX + a10*constY;
// incremental change along gradient for +y
dgdY = a01*constX + a11*constY;
// constant, incorporates the translation components from the matrix
gc = (a02-startx)*constX + (a12-starty)*constY;
}
/** {@collect.stats}
* Return a Raster containing the colors generated for the graphics
* operation. This is where the area is filled with colors distributed
* linearly.
*
* @param x,y,w,h the area in device space for which colors are
* generated.
*/
protected void fillRaster(int[] pixels, int off, int adjust,
int x, int y, int w, int h)
{
// current value for row gradients
float g = 0;
// used to end iteration on rows
int rowLimit = off + w;
// constant which can be pulled out of the inner loop
float initConst = (dgdX*x) + gc;
for (int i = 0; i < h; i++) { // for every row
// initialize current value to be start
g = initConst + dgdY*(y+i);
while (off < rowLimit) { // for every pixel in this row
// get the color
pixels[off++] = indexIntoGradientsArrays(g);
// incremental change in g
g += dgdX;
}
// change in off from row to row
off += adjust;
//rowlimit is width + offset
rowLimit = off + w;
}
}
}
|
Java
|
/*
* Copyright (c) 2000, 2001, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code 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
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package java.awt;
/** {@collect.stats}
* Capabilities and properties of images.
* @author Michael Martak
* @since 1.4
*/
public class ImageCapabilities implements Cloneable {
private boolean accelerated = false;
/** {@collect.stats}
* Creates a new object for specifying image capabilities.
* @param accelerated whether or not an accelerated image is desired
*/
public ImageCapabilities(boolean accelerated) {
this.accelerated = accelerated;
}
/** {@collect.stats}
* Returns <code>true</code> if the object whose capabilities are
* encapsulated in this <code>ImageCapabilities</code> can be or is
* accelerated.
* @return whether or not an image can be, or is, accelerated. There are
* various platform-specific ways to accelerate an image, including
* pixmaps, VRAM, AGP. This is the general acceleration method (as
* opposed to residing in system memory).
*/
public boolean isAccelerated() {
return accelerated;
}
/** {@collect.stats}
* Returns <code>true</code> if the <code>VolatileImage</code>
* described by this <code>ImageCapabilities</code> can lose
* its surfaces.
* @return whether or not a volatile image is subject to losing its surfaces
* at the whim of the operating system.
*/
public boolean isTrueVolatile() {
return false;
}
/** {@collect.stats}
* @return a copy of this ImageCapabilities object.
*/
public Object clone() {
try {
return super.clone();
} catch (CloneNotSupportedException e) {
// Since we implement Cloneable, this should never happen
throw new InternalError();
}
}
}
|
Java
|
/*
* Copyright (c) 2000, 2006, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code 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
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package java.awt;
import java.awt.event.AdjustmentEvent;
import java.awt.event.AdjustmentListener;
import java.awt.peer.ScrollPanePeer;
import java.io.Serializable;
/** {@collect.stats}
* This class represents the state of a horizontal or vertical
* scrollbar of a <code>ScrollPane</code>. Objects of this class are
* returned by <code>ScrollPane</code> methods.
*
* @since 1.4
*/
public class ScrollPaneAdjustable implements Adjustable, Serializable {
/** {@collect.stats}
* The <code>ScrollPane</code> this object is a scrollbar of.
* @serial
*/
private ScrollPane sp;
/** {@collect.stats}
* Orientation of this scrollbar.
*
* @serial
* @see #getOrientation
* @see java.awt.Adjustable#HORIZONTAL
* @see java.awt.Adjustable#VERTICAL
*/
private int orientation;
/** {@collect.stats}
* The value of this scrollbar.
* <code>value</code> should be greater than <code>minimum</code>
* and less than <code>maximum</code>
*
* @serial
* @see #getValue
* @see #setValue
*/
private int value;
/** {@collect.stats}
* The minimum value of this scrollbar.
* This value can only be set by the <code>ScrollPane</code>.
* <p>
* <strong>ATTN:</strong> In current implementation
* <code>minimum</code> is always <code>0</code>. This field can
* only be altered via <code>setSpan</code> method and
* <code>ScrollPane</code> always calls that method with
* <code>0</code> for the minimum. <code>getMinimum</code> method
* always returns <code>0</code> without checking this field.
*
* @serial
* @see #getMinimum
* @see #setSpan(int, int, int)
*/
private int minimum;
/** {@collect.stats}
* The maximum value of this scrollbar.
* This value can only be set by the <code>ScrollPane</code>.
*
* @serial
* @see #getMaximum
* @see #setSpan(int, int, int)
*/
private int maximum;
/** {@collect.stats}
* The size of the visible portion of this scrollbar.
* This value can only be set by the <code>ScrollPane</code>.
*
* @serial
* @see #getVisibleAmount
* @see #setSpan(int, int, int)
*/
private int visibleAmount;
/** {@collect.stats}
* The adjusting status of the <code>Scrollbar</code>.
* True if the value is in the process of changing as a result of
* actions being taken by the user.
*
* @see #getValueIsAdjusting
* @see #setValueIsAdjusting
* @since 1.4
*/
private transient boolean isAdjusting;
/** {@collect.stats}
* The amount by which the scrollbar value will change when going
* up or down by a line.
* This value should be a non negative integer.
*
* @serial
* @see #getUnitIncrement
* @see #setUnitIncrement
*/
private int unitIncrement = 1;
/** {@collect.stats}
* The amount by which the scrollbar value will change when going
* up or down by a page.
* This value should be a non negative integer.
*
* @serial
* @see #getBlockIncrement
* @see #setBlockIncrement
*/
private int blockIncrement = 1;
private AdjustmentListener adjustmentListener;
/** {@collect.stats}
* Error message for <code>AWTError</code> reported when one of
* the public but unsupported methods is called.
*/
private static final String SCROLLPANE_ONLY =
"Can be set by scrollpane only";
/** {@collect.stats}
* Initialize JNI field and method ids.
*/
private static native void initIDs();
static {
Toolkit.loadLibraries();
if (!GraphicsEnvironment.isHeadless()) {
initIDs();
}
}
/** {@collect.stats}
* JDK 1.1 serialVersionUID.
*/
private static final long serialVersionUID = -3359745691033257079L;
/** {@collect.stats}
* Constructs a new object to represent specified scrollabar
* of the specified <code>ScrollPane</code>.
* Only ScrollPane creates instances of this class.
* @param sp <code>ScrollPane</code>
* @param l <code>AdjustmentListener</code> to add upon creation.
* @param orientation specifies which scrollbar this object represents,
* can be either <code>Adjustable.HORIZONTAL</code>
* or <code>Adjustable.VERTICAL</code>.
*/
ScrollPaneAdjustable(ScrollPane sp, AdjustmentListener l, int orientation) {
this.sp = sp;
this.orientation = orientation;
addAdjustmentListener(l);
}
/** {@collect.stats}
* This is called by the scrollpane itself to update the
* <code>minimum</code>, <code>maximum</code> and
* <code>visible</code> values. The scrollpane is the only one
* that should be changing these since it is the source of these
* values.
*/
void setSpan(int min, int max, int visible) {
// adjust the values to be reasonable
minimum = min;
maximum = Math.max(max, minimum + 1);
visibleAmount = Math.min(visible, maximum - minimum);
visibleAmount = Math.max(visibleAmount, 1);
blockIncrement = Math.max((int)(visible * .90), 1);
setValue(value);
}
/** {@collect.stats}
* Returns the orientation of this scrollbar.
* @return the orientation of this scrollbar, either
* <code>Adjustable.HORIZONTAL</code> or
* <code>Adjustable.VERTICAL</code>
*/
public int getOrientation() {
return orientation;
}
/** {@collect.stats}
* This method should <strong>NOT</strong> be called by user code.
* This method is public for this class to properly implement
* <code>Adjustable</code> interface.
*
* @throws <code>AWTError</code> Always throws an error when called.
*/
public void setMinimum(int min) {
throw new AWTError(SCROLLPANE_ONLY);
}
public int getMinimum() {
// XXX: This relies on setSpan always being called with 0 for
// the minimum (which is currently true).
return 0;
}
/** {@collect.stats}
* This method should <strong>NOT</strong> be called by user code.
* This method is public for this class to properly implement
* <code>Adjustable</code> interface.
*
* @throws <code>AWTError</code> Always throws an error when called.
*/
public void setMaximum(int max) {
throw new AWTError(SCROLLPANE_ONLY);
}
public int getMaximum() {
return maximum;
}
public synchronized void setUnitIncrement(int u) {
if (u != unitIncrement) {
unitIncrement = u;
if (sp.peer != null) {
ScrollPanePeer peer = (ScrollPanePeer) sp.peer;
peer.setUnitIncrement(this, u);
}
}
}
public int getUnitIncrement() {
return unitIncrement;
}
public synchronized void setBlockIncrement(int b) {
blockIncrement = b;
}
public int getBlockIncrement() {
return blockIncrement;
}
/** {@collect.stats}
* This method should <strong>NOT</strong> be called by user code.
* This method is public for this class to properly implement
* <code>Adjustable</code> interface.
*
* @throws <code>AWTError</code> Always throws an error when called.
*/
public void setVisibleAmount(int v) {
throw new AWTError(SCROLLPANE_ONLY);
}
public int getVisibleAmount() {
return visibleAmount;
}
/** {@collect.stats}
* Sets the <code>valueIsAdjusting</code> property.
*
* @param b new adjustment-in-progress status
* @see #getValueIsAdjusting
* @since 1.4
*/
public void setValueIsAdjusting(boolean b) {
if (isAdjusting != b) {
isAdjusting = b;
AdjustmentEvent e =
new AdjustmentEvent(this,
AdjustmentEvent.ADJUSTMENT_VALUE_CHANGED,
AdjustmentEvent.TRACK, value, b);
adjustmentListener.adjustmentValueChanged(e);
}
}
/** {@collect.stats}
* Returns true if the value is in the process of changing as a
* result of actions being taken by the user.
*
* @return the value of the <code>valueIsAdjusting</code> property
* @see #setValueIsAdjusting
*/
public boolean getValueIsAdjusting() {
return isAdjusting;
}
/** {@collect.stats}
* Sets the value of this scrollbar to the specified value.
* <p>
* If the value supplied is less than the current minimum or
* greater than the current maximum, then one of those values is
* substituted, as appropriate.
*
* @param v the new value of the scrollbar
*/
public void setValue(int v) {
setTypedValue(v, AdjustmentEvent.TRACK);
}
/** {@collect.stats}
* Sets the value of this scrollbar to the specified value.
* <p>
* If the value supplied is less than the current minimum or
* greater than the current maximum, then one of those values is
* substituted, as appropriate. Also, creates and dispatches
* the AdjustementEvent with specified type and value.
*
* @param v the new value of the scrollbar
* @param type the type of the scrolling operation occured
*/
private void setTypedValue(int v, int type) {
v = Math.max(v, minimum);
v = Math.min(v, maximum - visibleAmount);
if (v != value) {
value = v;
// Synchronously notify the listeners so that they are
// guaranteed to be up-to-date with the Adjustable before
// it is mutated again.
AdjustmentEvent e =
new AdjustmentEvent(this,
AdjustmentEvent.ADJUSTMENT_VALUE_CHANGED,
type, value, isAdjusting);
adjustmentListener.adjustmentValueChanged(e);
}
}
public int getValue() {
return value;
}
/** {@collect.stats}
* Adds the specified adjustment listener to receive adjustment
* events from this <code>ScrollPaneAdjustable</code>.
* If <code>l</code> is <code>null</code>, no exception is thrown
* and no action is performed.
* <p>Refer to <a href="doc-files/AWTThreadIssues.html#ListenersThreads"
* >AWT Threading Issues</a> for details on AWT's threading model.
*
* @param l the adjustment listener.
* @see #removeAdjustmentListener
* @see #getAdjustmentListeners
* @see java.awt.event.AdjustmentListener
* @see java.awt.event.AdjustmentEvent
*/
public synchronized void addAdjustmentListener(AdjustmentListener l) {
if (l == null) {
return;
}
adjustmentListener = AWTEventMulticaster.add(adjustmentListener, l);
}
/** {@collect.stats}
* Removes the specified adjustment listener so that it no longer
* receives adjustment events from this <code>ScrollPaneAdjustable</code>.
* If <code>l</code> is <code>null</code>, no exception is thrown
* and no action is performed.
* <p>Refer to <a href="doc-files/AWTThreadIssues.html#ListenersThreads"
* >AWT Threading Issues</a> for details on AWT's threading model.
*
* @param l the adjustment listener.
* @see #addAdjustmentListener
* @see #getAdjustmentListeners
* @see java.awt.event.AdjustmentListener
* @see java.awt.event.AdjustmentEvent
* @since JDK1.1
*/
public synchronized void removeAdjustmentListener(AdjustmentListener l){
if (l == null) {
return;
}
adjustmentListener = AWTEventMulticaster.remove(adjustmentListener, l);
}
/** {@collect.stats}
* Returns an array of all the adjustment listeners
* registered on this <code>ScrollPaneAdjustable</code>.
*
* @return all of this <code>ScrollPaneAdjustable</code>'s
* <code>AdjustmentListener</code>s
* or an empty array if no adjustment
* listeners are currently registered
*
* @see #addAdjustmentListener
* @see #removeAdjustmentListener
* @see java.awt.event.AdjustmentListener
* @see java.awt.event.AdjustmentEvent
* @since 1.4
*/
public synchronized AdjustmentListener[] getAdjustmentListeners() {
return (AdjustmentListener[])(AWTEventMulticaster.getListeners(
adjustmentListener,
AdjustmentListener.class));
}
/** {@collect.stats}
* Returns a string representation of this scrollbar and its values.
* @return a string representation of this scrollbar.
*/
public String toString() {
return getClass().getName() + "[" + paramString() + "]";
}
/** {@collect.stats}
* Returns a string representing the state of this scrollbar.
* This method is intended to be used only for debugging purposes,
* and the content and format of the returned string may vary
* between implementations. The returned string may be empty but
* may not be <code>null</code>.
*
* @return the parameter string of this scrollbar.
*/
public String paramString() {
return ((orientation == Adjustable.VERTICAL ? "vertical,"
:"horizontal,")
+ "[0.."+maximum+"]"
+ ",val=" + value
+ ",vis=" + visibleAmount
+ ",unit=" + unitIncrement
+ ",block=" + blockIncrement
+ ",isAdjusting=" + isAdjusting);
}
}
|
Java
|
/*
* Copyright (c) 1998, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code 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
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package java.awt;
/** {@collect.stats}
* Conditional is used by the EventDispatchThread's message pumps to
* determine if a given pump should continue to run, or should instead exit
* and yield control to the parent pump.
*
* @author David Mendenhall
*/
interface Conditional {
boolean evaluate();
}
|
Java
|
/*
* Copyright (c) 1995, 2010, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code 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
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package java.awt;
import java.awt.font.FontRenderContext;
import java.awt.font.GlyphVector;
import java.awt.font.LineMetrics;
import java.awt.font.TextAttribute;
import java.awt.font.TextLayout;
import java.awt.font.TransformAttribute;
import java.awt.geom.AffineTransform;
import java.awt.geom.Point2D;
import java.awt.geom.Rectangle2D;
import java.awt.peer.FontPeer;
import java.io.*;
import java.lang.ref.SoftReference;
import java.security.AccessController;
import java.security.PrivilegedExceptionAction;
import java.text.AttributedCharacterIterator.Attribute;
import java.text.CharacterIterator;
import java.text.StringCharacterIterator;
import java.util.HashMap;
import java.util.Hashtable;
import java.util.Locale;
import java.util.Map;
import sun.font.StandardGlyphVector;
import sun.java2d.FontSupport;
import sun.font.AttributeMap;
import sun.font.AttributeValues;
import sun.font.EAttribute;
import sun.font.CompositeFont;
import sun.font.CreatedFontTracker;
import sun.font.Font2D;
import sun.font.Font2DHandle;
import sun.font.FontManager;
import sun.font.GlyphLayout;
import sun.font.FontLineMetrics;
import sun.font.CoreMetrics;
import static sun.font.EAttribute.*;
/** {@collect.stats}
* The <code>Font</code> class represents fonts, which are used to
* render text in a visible way.
* A font provides the information needed to map sequences of
* <em>characters</em> to sequences of <em>glyphs</em>
* and to render sequences of glyphs on <code>Graphics</code> and
* <code>Component</code> objects.
*
* <h4>Characters and Glyphs</h4>
*
* A <em>character</em> is a symbol that represents an item such as a letter,
* a digit, or punctuation in an abstract way. For example, <code>'g'</code>,
* <font size=-1>LATIN SMALL LETTER G</font>, is a character.
* <p>
* A <em>glyph</em> is a shape used to render a character or a sequence of
* characters. In simple writing systems, such as Latin, typically one glyph
* represents one character. In general, however, characters and glyphs do not
* have one-to-one correspondence. For example, the character 'á'
* <font size=-1>LATIN SMALL LETTER A WITH ACUTE</font>, can be represented by
* two glyphs: one for 'a' and one for '´'. On the other hand, the
* two-character string "fi" can be represented by a single glyph, an
* "fi" ligature. In complex writing systems, such as Arabic or the South
* and South-East Asian writing systems, the relationship between characters
* and glyphs can be more complicated and involve context-dependent selection
* of glyphs as well as glyph reordering.
*
* A font encapsulates the collection of glyphs needed to render a selected set
* of characters as well as the tables needed to map sequences of characters to
* corresponding sequences of glyphs.
*
* <h4>Physical and Logical Fonts</h4>
*
* The Java Platform distinguishes between two kinds of fonts:
* <em>physical</em> fonts and <em>logical</em> fonts.
* <p>
* <em>Physical</em> fonts are the actual font libraries containing glyph data
* and tables to map from character sequences to glyph sequences, using a font
* technology such as TrueType or PostScript Type 1.
* All implementations of the Java Platform must support TrueType fonts;
* support for other font technologies is implementation dependent.
* Physical fonts may use names such as Helvetica, Palatino, HonMincho, or
* any number of other font names.
* Typically, each physical font supports only a limited set of writing
* systems, for example, only Latin characters or only Japanese and Basic
* Latin.
* The set of available physical fonts varies between configurations.
* Applications that require specific fonts can bundle them and instantiate
* them using the {@link #createFont createFont} method.
* <p>
* <em>Logical</em> fonts are the five font families defined by the Java
* platform which must be supported by any Java runtime environment:
* Serif, SansSerif, Monospaced, Dialog, and DialogInput.
* These logical fonts are not actual font libraries. Instead, the logical
* font names are mapped to physical fonts by the Java runtime environment.
* The mapping is implementation and usually locale dependent, so the look
* and the metrics provided by them vary.
* Typically, each logical font name maps to several physical fonts in order to
* cover a large range of characters.
* <p>
* Peered AWT components, such as {@link Label Label} and
* {@link TextField TextField}, can only use logical fonts.
* <p>
* For a discussion of the relative advantages and disadvantages of using
* physical or logical fonts, see the
* <a href="http://java.sun.com/j2se/corejava/intl/reference/faqs/index.html#desktop-rendering">Internationalization FAQ</a>
* document.
*
* <h4>Font Faces and Names</h4>
*
* A <code>Font</code>
* can have many faces, such as heavy, medium, oblique, gothic and
* regular. All of these faces have similar typographic design.
* <p>
* There are three different names that you can get from a
* <code>Font</code> object. The <em>logical font name</em> is simply the
* name that was used to construct the font.
* The <em>font face name</em>, or just <em>font name</em> for
* short, is the name of a particular font face, like Helvetica Bold. The
* <em>family name</em> is the name of the font family that determines the
* typographic design across several faces, like Helvetica.
* <p>
* The <code>Font</code> class represents an instance of a font face from
* a collection of font faces that are present in the system resources
* of the host system. As examples, Arial Bold and Courier Bold Italic
* are font faces. There can be several <code>Font</code> objects
* associated with a font face, each differing in size, style, transform
* and font features.
* <p>
* The {@link GraphicsEnvironment#getAllFonts() getAllFonts} method
* of the <code>GraphicsEnvironment</code> class returns an
* array of all font faces available in the system. These font faces are
* returned as <code>Font</code> objects with a size of 1, identity
* transform and default font features. These
* base fonts can then be used to derive new <code>Font</code> objects
* with varying sizes, styles, transforms and font features via the
* <code>deriveFont</code> methods in this class.
*
* <h4>Font and TextAttribute</h4>
*
* <p><code>Font</code> supports most
* <code>TextAttribute</code>s. This makes some operations, such as
* rendering underlined text, convenient since it is not
* necessary to explicitly construct a <code>TextLayout</code> object.
* Attributes can be set on a Font by constructing or deriving it
* using a <code>Map</code> of <code>TextAttribute</code> values.
*
* <p>The values of some <code>TextAttributes</code> are not
* serializable, and therefore attempting to serialize an instance of
* <code>Font</code> that has such values will not serialize them.
* This means a Font deserialized from such a stream will not compare
* equal to the original Font that contained the non-serializable
* attributes. This should very rarely pose a problem
* since these attributes are typically used only in special
* circumstances and are unlikely to be serialized.
*
* <ul>
* <li><code>FOREGROUND</code> and <code>BACKGROUND</code> use
* <code>Paint</code> values. The subclass <code>Color</code> is
* serializable, while <code>GradientPaint</code> and
* <code>TexturePaint</code> are not.</li>
* <li><code>CHAR_REPLACEMENT</code> uses
* <code>GraphicAttribute</code> values. The subclasses
* <code>ShapeGraphicAttribute</code> and
* <code>ImageGraphicAttribute</code> are not serializable.</li>
* <li><code>INPUT_METHOD_HIGHLIGHT</code> uses
* <code>InputMethodHighlight</code> values, which are
* not serializable. See {@link java.awt.im.InputMethodHighlight}.</li>
* </ul>
*
* Clients who create custom subclasses of <code>Paint</code> and
* <code>GraphicAttribute</code> can make them serializable and
* avoid this problem. Clients who use input method highlights can
* convert these to the platform-specific attributes for that
* highlight on the current platform and set them on the Font as
* a workaround.</p>
*
* <p>The <code>Map</code>-based constructor and
* <code>deriveFont</code> APIs ignore the FONT attribute, and it is
* not retained by the Font; the static {@link #getFont} method should
* be used if the FONT attribute might be present. See {@link
* java.awt.font.TextAttribute#FONT} for more information.</p>
*
* <p>Several attributes will cause additional rendering overhead
* and potentially invoke layout. If a <code>Font</code> has such
* attributes, the <code>{@link #hasLayoutAttributes()}</code> method
* will return true.</p>
*
* <p>Note: Font rotations can cause text baselines to be rotated. In
* order to account for this (rare) possibility, font APIs are
* specified to return metrics and take parameters 'in
* baseline-relative coordinates'. This maps the 'x' coordinate to
* the advance along the baseline, (positive x is forward along the
* baseline), and the 'y' coordinate to a distance along the
* perpendicular to the baseline at 'x' (positive y is 90 degrees
* clockwise from the baseline vector). APIs for which this is
* especially important are called out as having 'baseline-relative
* coordinates.'
*/
public class Font implements java.io.Serializable
{
static {
/* ensure that the necessary native libraries are loaded */
Toolkit.loadLibraries();
initIDs();
}
/** {@collect.stats}
* This is now only used during serialization. Typically
* it is null.
*
* @serial
* @see #getAttributes()
*/
private Hashtable fRequestedAttributes;
/*
* Constants to be used for logical font family names.
*/
/** {@collect.stats}
* A String constant for the canonical family name of the
* logical font "Dialog". It is useful in Font construction
* to provide compile-time verification of the name.
* @since 1.6
*/
public static final String DIALOG = "Dialog";
/** {@collect.stats}
* A String constant for the canonical family name of the
* logical font "DialogInput". It is useful in Font construction
* to provide compile-time verification of the name.
* @since 1.6
*/
public static final String DIALOG_INPUT = "DialogInput";
/** {@collect.stats}
* A String constant for the canonical family name of the
* logical font "SansSerif". It is useful in Font construction
* to provide compile-time verification of the name.
* @since 1.6
*/
public static final String SANS_SERIF = "SansSerif";
/** {@collect.stats}
* A String constant for the canonical family name of the
* logical font "Serif". It is useful in Font construction
* to provide compile-time verification of the name.
* @since 1.6
*/
public static final String SERIF = "Serif";
/** {@collect.stats}
* A String constant for the canonical family name of the
* logical font "Monospaced". It is useful in Font construction
* to provide compile-time verification of the name.
* @since 1.6
*/
public static final String MONOSPACED = "Monospaced";
/*
* Constants to be used for styles. Can be combined to mix
* styles.
*/
/** {@collect.stats}
* The plain style constant.
*/
public static final int PLAIN = 0;
/** {@collect.stats}
* The bold style constant. This can be combined with the other style
* constants (except PLAIN) for mixed styles.
*/
public static final int BOLD = 1;
/** {@collect.stats}
* The italicized style constant. This can be combined with the other
* style constants (except PLAIN) for mixed styles.
*/
public static final int ITALIC = 2;
/** {@collect.stats}
* The baseline used in most Roman scripts when laying out text.
*/
public static final int ROMAN_BASELINE = 0;
/** {@collect.stats}
* The baseline used in ideographic scripts like Chinese, Japanese,
* and Korean when laying out text.
*/
public static final int CENTER_BASELINE = 1;
/** {@collect.stats}
* The baseline used in Devanigiri and similar scripts when laying
* out text.
*/
public static final int HANGING_BASELINE = 2;
/** {@collect.stats}
* Identify a font resource of type TRUETYPE.
* Used to specify a TrueType font resource to the
* {@link #createFont} method.
* The TrueType format was extended to become the OpenType
* format, which adds support for fonts with Postscript outlines,
* this tag therefore references these fonts, as well as those
* with TrueType outlines.
* @since 1.3
*/
public static final int TRUETYPE_FONT = 0;
/** {@collect.stats}
* Identify a font resource of type TYPE1.
* Used to specify a Type1 font resource to the
* {@link #createFont} method.
* @since 1.5
*/
public static final int TYPE1_FONT = 1;
/** {@collect.stats}
* The logical name of this <code>Font</code>, as passed to the
* constructor.
* @since JDK1.0
*
* @serial
* @see #getName
*/
protected String name;
/** {@collect.stats}
* The style of this <code>Font</code>, as passed to the constructor.
* This style can be PLAIN, BOLD, ITALIC, or BOLD+ITALIC.
* @since JDK1.0
*
* @serial
* @see #getStyle()
*/
protected int style;
/** {@collect.stats}
* The point size of this <code>Font</code>, rounded to integer.
* @since JDK1.0
*
* @serial
* @see #getSize()
*/
protected int size;
/** {@collect.stats}
* The point size of this <code>Font</code> in <code>float</code>.
*
* @serial
* @see #getSize()
* @see #getSize2D()
*/
protected float pointSize;
/** {@collect.stats}
* The platform specific font information.
*/
private transient FontPeer peer;
private transient long pData; // native JDK1.1 font pointer
private transient Font2DHandle font2DHandle;
private transient AttributeValues values;
private transient boolean hasLayoutAttributes;
/*
* If the origin of a Font is a created font then this attribute
* must be set on all derived fonts too.
*/
private transient boolean createdFont = false;
/*
* This is true if the font transform is not identity. It
* is used to avoid unnecessary instantiation of an AffineTransform.
*/
private transient boolean nonIdentityTx;
/*
* A cached value used when a transform is required for internal
* use. This must not be exposed to callers since AffineTransform
* is mutable.
*/
private static final AffineTransform identityTx = new AffineTransform();
/*
* JDK 1.1 serialVersionUID
*/
private static final long serialVersionUID = -4206021311591459213L;
/** {@collect.stats}
* Gets the peer of this <code>Font</code>.
* @return the peer of the <code>Font</code>.
* @since JDK1.1
* @deprecated Font rendering is now platform independent.
*/
@Deprecated
public FontPeer getPeer(){
return getPeer_NoClientCode();
}
// NOTE: This method is called by privileged threads.
// We implement this functionality in a package-private method
// to insure that it cannot be overridden by client subclasses.
// DO NOT INVOKE CLIENT CODE ON THIS THREAD!
final FontPeer getPeer_NoClientCode() {
if(peer == null) {
Toolkit tk = Toolkit.getDefaultToolkit();
this.peer = tk.getFontPeer(name, style);
}
return peer;
}
/** {@collect.stats}
* Return the AttributeValues object associated with this
* font. Most of the time, the internal object is null.
* If required, it will be created from the 'standard'
* state on the font. Only non-default values will be
* set in the AttributeValues object.
*
* <p>Since the AttributeValues object is mutable, and it
* is cached in the font, care must be taken to ensure that
* it is not mutated.
*/
private AttributeValues getAttributeValues() {
if (values == null) {
values = new AttributeValues();
values.setFamily(name);
values.setSize(pointSize); // expects the float value.
if ((style & BOLD) != 0) {
values.setWeight(2); // WEIGHT_BOLD
}
if ((style & ITALIC) != 0) {
values.setPosture(.2f); // POSTURE_OBLIQUE
}
values.defineAll(PRIMARY_MASK); // for streaming compatibility
}
return values;
}
private Font2D getFont2D() {
if (FontManager.usingPerAppContextComposites &&
font2DHandle != null &&
font2DHandle.font2D instanceof CompositeFont &&
((CompositeFont)(font2DHandle.font2D)).isStdComposite()) {
return FontManager.findFont2D(name, style,
FontManager.LOGICAL_FALLBACK);
} else if (font2DHandle == null) {
font2DHandle =
FontManager.findFont2D(name, style,
FontManager.LOGICAL_FALLBACK).handle;
}
/* Do not cache the de-referenced font2D. It must be explicitly
* de-referenced to pick up a valid font in the event that the
* original one is marked invalid
*/
return font2DHandle.font2D;
}
/** {@collect.stats}
* Creates a new <code>Font</code> from the specified name, style and
* point size.
* <p>
* The font name can be a font face name or a font family name.
* It is used together with the style to find an appropriate font face.
* When a font family name is specified, the style argument is used to
* select the most appropriate face from the family. When a font face
* name is specified, the face's style and the style argument are
* merged to locate the best matching font from the same family.
* For example if face name "Arial Bold" is specified with style
* <code>Font.ITALIC</code>, the font system looks for a face in the
* "Arial" family that is bold and italic, and may associate the font
* instance with the physical font face "Arial Bold Italic".
* The style argument is merged with the specified face's style, not
* added or subtracted.
* This means, specifying a bold face and a bold style does not
* double-embolden the font, and specifying a bold face and a plain
* style does not lighten the font.
* <p>
* If no face for the requested style can be found, the font system
* may apply algorithmic styling to achieve the desired style.
* For example, if <code>ITALIC</code> is requested, but no italic
* face is available, glyphs from the plain face may be algorithmically
* obliqued (slanted).
* <p>
* Font name lookup is case insensitive, using the case folding
* rules of the US locale.
* <p>
* If the <code>name</code> parameter represents something other than a
* logical font, i.e. is interpreted as a physical font face or family, and
* this cannot be mapped by the implementation to a physical font or a
* compatible alternative, then the font system will map the Font
* instance to "Dialog", such that for example, the family as reported
* by {@link #getFamily() getFamily} will be "Dialog".
* <p>
*
* @param name the font name. This can be a font face name or a font
* family name, and may represent either a logical font or a physical
* font found in this {@code GraphicsEnvironment}.
* The family names for logical fonts are: Dialog, DialogInput,
* Monospaced, Serif, or SansSerif. Pre-defined String constants exist
* for all of these names, for example, {@code DIALOG}. If {@code name} is
* {@code null}, the <em>logical font name</em> of the new
* {@code Font} as returned by {@code getName()} is set to
* the name "Default".
* @param style the style constant for the {@code Font}
* The style argument is an integer bitmask that may
* be {@code PLAIN}, or a bitwise union of {@code BOLD} and/or
* {@code ITALIC} (for example, {@code ITALIC} or {@code BOLD|ITALIC}).
* If the style argument does not conform to one of the expected
* integer bitmasks then the style is set to {@code PLAIN}.
* @param size the point size of the {@code Font}
* @see GraphicsEnvironment#getAllFonts
* @see GraphicsEnvironment#getAvailableFontFamilyNames
* @since JDK1.0
*/
public Font(String name, int style, int size) {
this.name = (name != null) ? name : "Default";
this.style = (style & ~0x03) == 0 ? style : 0;
this.size = size;
this.pointSize = size;
}
private Font(String name, int style, float sizePts) {
this.name = (name != null) ? name : "Default";
this.style = (style & ~0x03) == 0 ? style : 0;
this.size = (int)(sizePts + 0.5);
this.pointSize = sizePts;
}
/* This constructor is used by deriveFont when attributes is null */
private Font(String name, int style, float sizePts,
boolean created, Font2DHandle handle) {
this(name, style, sizePts);
this.createdFont = created;
/* Fonts created from a stream will use the same font2D instance
* as the parent.
* One exception is that if the derived font is requested to be
* in a different style, then also check if its a CompositeFont
* and if so build a new CompositeFont from components of that style.
* CompositeFonts can only be marked as "created" if they are used
* to add fall backs to a physical font. And non-composites are
* always from "Font.createFont()" and shouldn't get this treatment.
*/
if (created) {
if (handle.font2D instanceof CompositeFont &&
handle.font2D.getStyle() != style) {
this.font2DHandle =
FontManager.getNewComposite(null, style, handle);
} else {
this.font2DHandle = handle;
}
}
}
/* used to implement Font.createFont */
private Font(File fontFile, int fontFormat,
boolean isCopy, CreatedFontTracker tracker)
throws FontFormatException {
this.createdFont = true;
/* Font2D instances created by this method track their font file
* so that when the Font2D is GC'd it can also remove the file.
*/
this.font2DHandle =
FontManager.createFont2D(fontFile, fontFormat,
isCopy, tracker).handle;
this.name = this.font2DHandle.font2D.getFontName(Locale.getDefault());
this.style = Font.PLAIN;
this.size = 1;
this.pointSize = 1f;
}
/* This constructor is used when one font is derived from another.
* Fonts created from a stream will use the same font2D instance as the
* parent. They can be distinguished because the "created" argument
* will be "true". Since there is no way to recreate these fonts they
* need to have the handle to the underlying font2D passed in.
* "created" is also true when a special composite is referenced by the
* handle for essentially the same reasons.
* But when deriving a font in these cases two particular attributes
* need special attention: family/face and style.
* The "composites" in these cases need to be recreated with optimal
* fonts for the new values of family and style.
* For fonts created with createFont() these are treated differently.
* JDK can often synthesise a different style (bold from plain
* for example). For fonts created with "createFont" this is a reasonable
* solution but its also possible (although rare) to derive a font with a
* different family attribute. In this case JDK needs
* to break the tie with the original Font2D and find a new Font.
* The oldName and oldStyle are supplied so they can be compared with
* what the Font2D and the values. To speed things along :
* oldName == null will be interpreted as the name is unchanged.
* oldStyle = -1 will be interpreted as the style is unchanged.
* In these cases there is no need to interrogate "values".
*/
private Font(AttributeValues values, String oldName, int oldStyle,
boolean created, Font2DHandle handle) {
this.createdFont = created;
if (created) {
this.font2DHandle = handle;
String newName = null;
if (oldName != null) {
newName = values.getFamily();
if (oldName.equals(newName)) newName = null;
}
int newStyle = 0;
if (oldStyle == -1) {
newStyle = -1;
} else {
if (values.getWeight() >= 2f) newStyle = BOLD;
if (values.getPosture() >= .2f) newStyle |= ITALIC;
if (oldStyle == newStyle) newStyle = -1;
}
if (handle.font2D instanceof CompositeFont) {
if (newStyle != -1 || newName != null) {
this.font2DHandle =
FontManager.getNewComposite(newName, newStyle, handle);
}
} else if (newName != null) {
this.createdFont = false;
this.font2DHandle = null;
}
}
initFromValues(values);
}
/** {@collect.stats}
* Creates a new <code>Font</code> with the specified attributes.
* Only keys defined in {@link java.awt.font.TextAttribute TextAttribute}
* are recognized. In addition the FONT attribute is
* not recognized by this constructor
* (see {@link #getAvailableAttributes}). Only attributes that have
* values of valid types will affect the new <code>Font</code>.
* <p>
* If <code>attributes</code> is <code>null</code>, a new
* <code>Font</code> is initialized with default values.
* @see java.awt.font.TextAttribute
* @param attributes the attributes to assign to the new
* <code>Font</code>, or <code>null</code>
*/
public Font(Map<? extends Attribute, ?> attributes) {
initFromValues(AttributeValues.fromMap(attributes, RECOGNIZED_MASK));
}
/** {@collect.stats}
* Creates a new <code>Font</code> from the specified <code>font</code>.
* This constructor is intended for use by subclasses.
* @param font from which to create this <code>Font</code>.
* @throws NullPointerException if <code>font</code> is null
* @since 1.6
*/
protected Font(Font font) {
if (font.values != null) {
initFromValues(font.getAttributeValues().clone());
} else {
this.name = font.name;
this.style = font.style;
this.size = font.size;
this.pointSize = font.pointSize;
}
this.font2DHandle = font.font2DHandle;
this.createdFont = font.createdFont;
}
/** {@collect.stats}
* Font recognizes all attributes except FONT.
*/
private static final int RECOGNIZED_MASK = AttributeValues.MASK_ALL
& ~AttributeValues.getMask(EFONT);
/** {@collect.stats}
* These attributes are considered primary by the FONT attribute.
*/
private static final int PRIMARY_MASK =
AttributeValues.getMask(EFAMILY, EWEIGHT, EWIDTH, EPOSTURE, ESIZE,
ETRANSFORM, ESUPERSCRIPT, ETRACKING);
/** {@collect.stats}
* These attributes are considered secondary by the FONT attribute.
*/
private static final int SECONDARY_MASK =
RECOGNIZED_MASK & ~PRIMARY_MASK;
/** {@collect.stats}
* These attributes are handled by layout.
*/
private static final int LAYOUT_MASK =
AttributeValues.getMask(ECHAR_REPLACEMENT, EFOREGROUND, EBACKGROUND,
EUNDERLINE, ESTRIKETHROUGH, ERUN_DIRECTION,
EBIDI_EMBEDDING, EJUSTIFICATION,
EINPUT_METHOD_HIGHLIGHT, EINPUT_METHOD_UNDERLINE,
ESWAP_COLORS, ENUMERIC_SHAPING, EKERNING,
ELIGATURES, ETRACKING);
private static final int EXTRA_MASK =
AttributeValues.getMask(ETRANSFORM, ESUPERSCRIPT, EWIDTH);
/** {@collect.stats}
* Initialize the standard Font fields from the values object.
*/
private void initFromValues(AttributeValues values) {
this.values = values;
values.defineAll(PRIMARY_MASK); // for 1.5 streaming compatibility
this.name = values.getFamily();
this.pointSize = values.getSize();
this.size = (int)(values.getSize() + 0.5);
if (values.getWeight() >= 2f) this.style |= BOLD; // not == 2f
if (values.getPosture() >= .2f) this.style |= ITALIC; // not == .2f
this.nonIdentityTx = values.anyNonDefault(EXTRA_MASK);
this.hasLayoutAttributes = values.anyNonDefault(LAYOUT_MASK);
}
/** {@collect.stats}
* Returns a <code>Font</code> appropriate to the attributes.
* If <code>attributes</code>contains a <code>FONT</code> attribute
* with a valid <code>Font</code> as its value, it will be
* merged with any remaining attributes. See
* {@link java.awt.font.TextAttribute#FONT} for more
* information.
*
* @param attributes the attributes to assign to the new
* <code>Font</code>
* @return a new <code>Font</code> created with the specified
* attributes
* @throws NullPointerException if <code>attributes</code> is null.
* @since 1.2
* @see java.awt.font.TextAttribute
*/
public static Font getFont(Map<? extends Attribute, ?> attributes) {
// optimize for two cases:
// 1) FONT attribute, and nothing else
// 2) attributes, but no FONT
// avoid turning the attributemap into a regular map for no reason
if (attributes instanceof AttributeMap &&
((AttributeMap)attributes).getValues() != null) {
AttributeValues values = ((AttributeMap)attributes).getValues();
if (values.isNonDefault(EFONT)) {
Font font = values.getFont();
if (!values.anyDefined(SECONDARY_MASK)) {
return font;
}
// merge
values = font.getAttributeValues().clone();
values.merge(attributes, SECONDARY_MASK);
return new Font(values, font.name, font.style,
font.createdFont, font.font2DHandle);
}
return new Font(attributes);
}
Font font = (Font)attributes.get(TextAttribute.FONT);
if (font != null) {
if (attributes.size() > 1) { // oh well, check for anything else
AttributeValues values = font.getAttributeValues().clone();
values.merge(attributes, SECONDARY_MASK);
return new Font(values, font.name, font.style,
font.createdFont, font.font2DHandle);
}
return font;
}
return new Font(attributes);
}
/** {@collect.stats}
* Used with the byte count tracker for fonts created from streams.
* If a thread can create temp files anyway, no point in counting
* font bytes.
*/
private static boolean hasTempPermission() {
if (System.getSecurityManager() == null) {
return true;
}
File f = null;
boolean hasPerm = false;
try {
f = File.createTempFile("+~JT", ".tmp", null);
f.delete();
f = null;
hasPerm = true;
} catch (Throwable t) {
/* inc. any kind of SecurityException */
}
return hasPerm;
}
/** {@collect.stats}
* Returns a new <code>Font</code> using the specified font type
* and input data. The new <code>Font</code> is
* created with a point size of 1 and style {@link #PLAIN PLAIN}.
* This base font can then be used with the <code>deriveFont</code>
* methods in this class to derive new <code>Font</code> objects with
* varying sizes, styles, transforms and font features. This
* method does not close the {@link InputStream}.
* <p>
* To make the <code>Font</code> available to Font constructors the
* returned <code>Font</code> must be registered in the
* <code>GraphicsEnviroment</code> by calling
* {@link GraphicsEnvironment#registerFont(Font) registerFont(Font)}.
* @param fontFormat the type of the <code>Font</code>, which is
* {@link #TRUETYPE_FONT TRUETYPE_FONT} if a TrueType resource is specified.
* or {@link #TYPE1_FONT TYPE1_FONT} if a Type 1 resource is specified.
* @param fontStream an <code>InputStream</code> object representing the
* input data for the font.
* @return a new <code>Font</code> created with the specified font type.
* @throws IllegalArgumentException if <code>fontFormat</code> is not
* <code>TRUETYPE_FONT</code>or<code>TYPE1_FONT</code>.
* @throws FontFormatException if the <code>fontStream</code> data does
* not contain the required font tables for the specified format.
* @throws IOException if the <code>fontStream</code>
* cannot be completely read.
* @see GraphicsEnvironment#registerFont(Font)
* @since 1.3
*/
public static Font createFont(int fontFormat, InputStream fontStream)
throws java.awt.FontFormatException, java.io.IOException {
if (fontFormat != Font.TRUETYPE_FONT &&
fontFormat != Font.TYPE1_FONT) {
throw new IllegalArgumentException ("font format not recognized");
}
boolean copiedFontData = false;
try {
final File tFile = AccessController.doPrivileged(
new PrivilegedExceptionAction<File>() {
public File run() throws IOException {
return File.createTempFile("+~JF", ".tmp", null);
}
}
);
int totalSize = 0;
CreatedFontTracker tracker = null;
try {
final OutputStream outStream =
AccessController.doPrivileged(
new PrivilegedExceptionAction<OutputStream>() {
public OutputStream run() throws IOException {
return new FileOutputStream(tFile);
}
}
);
if (!hasTempPermission()) {
tracker = CreatedFontTracker.getTracker();
}
try {
byte[] buf = new byte[8192];
for (;;) {
int bytesRead = fontStream.read(buf);
if (bytesRead < 0) {
break;
}
if (tracker != null) {
if (totalSize+bytesRead > tracker.MAX_FILE_SIZE) {
throw new IOException("File too big.");
}
if (totalSize+tracker.getNumBytes() >
tracker.MAX_TOTAL_BYTES)
{
throw new IOException("Total files too big.");
}
totalSize += bytesRead;
tracker.addBytes(bytesRead);
}
outStream.write(buf, 0, bytesRead);
}
/* don't close the input stream */
} finally {
outStream.close();
}
/* After all references to a Font2D are dropped, the file
* will be removed. To support long-lived AppContexts,
* we need to then decrement the byte count by the size
* of the file.
* If the data isn't a valid font, the implementation will
* delete the tmp file and decrement the byte count
* in the tracker object before returning from the
* constructor, so we can set 'copiedFontData' to true here
* without waiting for the results of that constructor.
*/
copiedFontData = true;
Font font = new Font(tFile, fontFormat, true, tracker);
return font;
} finally {
if (!copiedFontData) {
if (tracker != null) {
tracker.subBytes(totalSize);
}
AccessController.doPrivileged(
new PrivilegedExceptionAction<Void>() {
public Void run() {
tFile.delete();
return null;
}
}
);
}
}
} catch (Throwable t) {
if (t instanceof FontFormatException) {
throw (FontFormatException)t;
}
if (t instanceof IOException) {
throw (IOException)t;
}
Throwable cause = t.getCause();
if (cause instanceof FontFormatException) {
throw (FontFormatException)cause;
}
throw new IOException("Problem reading font data.");
}
}
/** {@collect.stats}
* Returns a new <code>Font</code> using the specified font type
* and the specified font file. The new <code>Font</code> is
* created with a point size of 1 and style {@link #PLAIN PLAIN}.
* This base font can then be used with the <code>deriveFont</code>
* methods in this class to derive new <code>Font</code> objects with
* varying sizes, styles, transforms and font features.
* @param fontFormat the type of the <code>Font</code>, which is
* {@link #TRUETYPE_FONT TRUETYPE_FONT} if a TrueType resource is
* specified or {@link #TYPE1_FONT TYPE1_FONT} if a Type 1 resource is
* specified.
* So long as the returned font, or its derived fonts are referenced
* the implementation may continue to access <code>fontFile</code>
* to retrieve font data. Thus the results are undefined if the file
* is changed, or becomes inaccessible.
* <p>
* To make the <code>Font</code> available to Font constructors the
* returned <code>Font</code> must be registered in the
* <code>GraphicsEnviroment</code> by calling
* {@link GraphicsEnvironment#registerFont(Font) registerFont(Font)}.
* @param fontFile a <code>File</code> object representing the
* input data for the font.
* @return a new <code>Font</code> created with the specified font type.
* @throws IllegalArgumentException if <code>fontFormat</code> is not
* <code>TRUETYPE_FONT</code>or<code>TYPE1_FONT</code>.
* @throws NullPointerException if <code>fontFile</code> is null.
* @throws IOException if the <code>fontFile</code> cannot be read.
* @throws FontFormatException if <code>fontFile</code> does
* not contain the required font tables for the specified format.
* @throws SecurityException if the executing code does not have
* permission to read from the file.
* @see GraphicsEnvironment#registerFont(Font)
* @since 1.5
*/
public static Font createFont(int fontFormat, File fontFile)
throws java.awt.FontFormatException, java.io.IOException {
fontFile = new File(fontFile.getPath());
if (fontFormat != Font.TRUETYPE_FONT &&
fontFormat != Font.TYPE1_FONT) {
throw new IllegalArgumentException ("font format not recognized");
}
SecurityManager sm = System.getSecurityManager();
if (sm != null) {
FilePermission filePermission =
new FilePermission(fontFile.getPath(), "read");
sm.checkPermission(filePermission);
}
if (!fontFile.canRead()) {
throw new IOException("Can't read " + fontFile);
}
return new Font(fontFile, fontFormat, false, null);
}
/** {@collect.stats}
* Returns a copy of the transform associated with this
* <code>Font</code>. This transform is not necessarily the one
* used to construct the font. If the font has algorithmic
* superscripting or width adjustment, this will be incorporated
* into the returned <code>AffineTransform</code>.
* <p>
* Typically, fonts will not be transformed. Clients generally
* should call {@link #isTransformed} first, and only call this
* method if <code>isTransformed</code> returns true.
*
* @return an {@link AffineTransform} object representing the
* transform attribute of this <code>Font</code> object.
*/
public AffineTransform getTransform() {
/* The most common case is the identity transform. Most callers
* should call isTransformed() first, to decide if they need to
* get the transform, but some may not. Here we check to see
* if we have a nonidentity transform, and only do the work to
* fetch and/or compute it if so, otherwise we return a new
* identity transform.
*
* Note that the transform is _not_ necessarily the same as
* the transform passed in as an Attribute in a Map, as the
* transform returned will also reflect the effects of WIDTH and
* SUPERSCRIPT attributes. Clients who want the actual transform
* need to call getRequestedAttributes.
*/
if (nonIdentityTx) {
AttributeValues values = getAttributeValues();
AffineTransform at = values.isNonDefault(ETRANSFORM)
? new AffineTransform(values.getTransform())
: new AffineTransform();
if (values.getSuperscript() != 0) {
// can't get ascent and descent here, recursive call to this fn,
// so use pointsize
// let users combine super- and sub-scripting
int superscript = values.getSuperscript();
double trans = 0;
int n = 0;
boolean up = superscript > 0;
int sign = up ? -1 : 1;
int ss = up ? superscript : -superscript;
while ((ss & 7) > n) {
int newn = ss & 7;
trans += sign * (ssinfo[newn] - ssinfo[n]);
ss >>= 3;
sign = -sign;
n = newn;
}
trans *= pointSize;
double scale = Math.pow(2./3., n);
at.preConcatenate(AffineTransform.getTranslateInstance(0, trans));
at.scale(scale, scale);
// note on placement and italics
// We preconcatenate the transform because we don't want to translate along
// the italic angle, but purely perpendicular to the baseline. While this
// looks ok for superscripts, it can lead subscripts to stack on each other
// and bring the following text too close. The way we deal with potential
// collisions that can occur in the case of italics is by adjusting the
// horizontal spacing of the adjacent glyphvectors. Examine the italic
// angle of both vectors, if one is non-zero, compute the minimum ascent
// and descent, and then the x position at each for each vector along its
// italic angle starting from its (offset) baseline. Compute the difference
// between the x positions and use the maximum difference to adjust the
// position of the right gv.
}
if (values.isNonDefault(EWIDTH)) {
at.scale(values.getWidth(), 1f);
}
return at;
}
return new AffineTransform();
}
// x = r^0 + r^1 + r^2... r^n
// rx = r^1 + r^2 + r^3... r^(n+1)
// x - rx = r^0 - r^(n+1)
// x (1 - r) = r^0 - r^(n+1)
// x = (r^0 - r^(n+1)) / (1 - r)
// x = (1 - r^(n+1)) / (1 - r)
// scale ratio is 2/3
// trans = 1/2 of ascent * x
// assume ascent is 3/4 of point size
private static final float[] ssinfo = {
0.0f,
0.375f,
0.625f,
0.7916667f,
0.9027778f,
0.9768519f,
1.0262346f,
1.0591564f,
};
/** {@collect.stats}
* Returns the family name of this <code>Font</code>.
*
* <p>The family name of a font is font specific. Two fonts such as
* Helvetica Italic and Helvetica Bold have the same family name,
* <i>Helvetica</i>, whereas their font face names are
* <i>Helvetica Bold</i> and <i>Helvetica Italic</i>. The list of
* available family names may be obtained by using the
* {@link GraphicsEnvironment#getAvailableFontFamilyNames()} method.
*
* <p>Use <code>getName</code> to get the logical name of the font.
* Use <code>getFontName</code> to get the font face name of the font.
* @return a <code>String</code> that is the family name of this
* <code>Font</code>.
*
* @see #getName
* @see #getFontName
* @since JDK1.1
*/
public String getFamily() {
return getFamily_NoClientCode();
}
// NOTE: This method is called by privileged threads.
// We implement this functionality in a package-private
// method to insure that it cannot be overridden by client
// subclasses.
// DO NOT INVOKE CLIENT CODE ON THIS THREAD!
final String getFamily_NoClientCode() {
return getFamily(Locale.getDefault());
}
/** {@collect.stats}
* Returns the family name of this <code>Font</code>, localized for
* the specified locale.
*
* <p>The family name of a font is font specific. Two fonts such as
* Helvetica Italic and Helvetica Bold have the same family name,
* <i>Helvetica</i>, whereas their font face names are
* <i>Helvetica Bold</i> and <i>Helvetica Italic</i>. The list of
* available family names may be obtained by using the
* {@link GraphicsEnvironment#getAvailableFontFamilyNames()} method.
*
* <p>Use <code>getFontName</code> to get the font face name of the font.
* @param l locale for which to get the family name
* @return a <code>String</code> representing the family name of the
* font, localized for the specified locale.
* @see #getFontName
* @see java.util.Locale
* @since 1.2
*/
public String getFamily(Locale l) {
if (l == null) {
throw new NullPointerException("null locale doesn't mean default");
}
return getFont2D().getFamilyName(l);
}
/** {@collect.stats}
* Returns the postscript name of this <code>Font</code>.
* Use <code>getFamily</code> to get the family name of the font.
* Use <code>getFontName</code> to get the font face name of the font.
* @return a <code>String</code> representing the postscript name of
* this <code>Font</code>.
* @since 1.2
*/
public String getPSName() {
return getFont2D().getPostscriptName();
}
/** {@collect.stats}
* Returns the logical name of this <code>Font</code>.
* Use <code>getFamily</code> to get the family name of the font.
* Use <code>getFontName</code> to get the font face name of the font.
* @return a <code>String</code> representing the logical name of
* this <code>Font</code>.
* @see #getFamily
* @see #getFontName
* @since JDK1.0
*/
public String getName() {
return name;
}
/** {@collect.stats}
* Returns the font face name of this <code>Font</code>. For example,
* Helvetica Bold could be returned as a font face name.
* Use <code>getFamily</code> to get the family name of the font.
* Use <code>getName</code> to get the logical name of the font.
* @return a <code>String</code> representing the font face name of
* this <code>Font</code>.
* @see #getFamily
* @see #getName
* @since 1.2
*/
public String getFontName() {
return getFontName(Locale.getDefault());
}
/** {@collect.stats}
* Returns the font face name of the <code>Font</code>, localized
* for the specified locale. For example, Helvetica Fett could be
* returned as the font face name.
* Use <code>getFamily</code> to get the family name of the font.
* @param l a locale for which to get the font face name
* @return a <code>String</code> representing the font face name,
* localized for the specified locale.
* @see #getFamily
* @see java.util.Locale
*/
public String getFontName(Locale l) {
if (l == null) {
throw new NullPointerException("null locale doesn't mean default");
}
return getFont2D().getFontName(l);
}
/** {@collect.stats}
* Returns the style of this <code>Font</code>. The style can be
* PLAIN, BOLD, ITALIC, or BOLD+ITALIC.
* @return the style of this <code>Font</code>
* @see #isPlain
* @see #isBold
* @see #isItalic
* @since JDK1.0
*/
public int getStyle() {
return style;
}
/** {@collect.stats}
* Returns the point size of this <code>Font</code>, rounded to
* an integer.
* Most users are familiar with the idea of using <i>point size</i> to
* specify the size of glyphs in a font. This point size defines a
* measurement between the baseline of one line to the baseline of the
* following line in a single spaced text document. The point size is
* based on <i>typographic points</i>, approximately 1/72 of an inch.
* <p>
* The Java(tm)2D API adopts the convention that one point is
* equivalent to one unit in user coordinates. When using a
* normalized transform for converting user space coordinates to
* device space coordinates 72 user
* space units equal 1 inch in device space. In this case one point
* is 1/72 of an inch.
* @return the point size of this <code>Font</code> in 1/72 of an
* inch units.
* @see #getSize2D
* @see GraphicsConfiguration#getDefaultTransform
* @see GraphicsConfiguration#getNormalizingTransform
* @since JDK1.0
*/
public int getSize() {
return size;
}
/** {@collect.stats}
* Returns the point size of this <code>Font</code> in
* <code>float</code> value.
* @return the point size of this <code>Font</code> as a
* <code>float</code> value.
* @see #getSize
* @since 1.2
*/
public float getSize2D() {
return pointSize;
}
/** {@collect.stats}
* Indicates whether or not this <code>Font</code> object's style is
* PLAIN.
* @return <code>true</code> if this <code>Font</code> has a
* PLAIN sytle;
* <code>false</code> otherwise.
* @see java.awt.Font#getStyle
* @since JDK1.0
*/
public boolean isPlain() {
return style == 0;
}
/** {@collect.stats}
* Indicates whether or not this <code>Font</code> object's style is
* BOLD.
* @return <code>true</code> if this <code>Font</code> object's
* style is BOLD;
* <code>false</code> otherwise.
* @see java.awt.Font#getStyle
* @since JDK1.0
*/
public boolean isBold() {
return (style & BOLD) != 0;
}
/** {@collect.stats}
* Indicates whether or not this <code>Font</code> object's style is
* ITALIC.
* @return <code>true</code> if this <code>Font</code> object's
* style is ITALIC;
* <code>false</code> otherwise.
* @see java.awt.Font#getStyle
* @since JDK1.0
*/
public boolean isItalic() {
return (style & ITALIC) != 0;
}
/** {@collect.stats}
* Indicates whether or not this <code>Font</code> object has a
* transform that affects its size in addition to the Size
* attribute.
* @return <code>true</code> if this <code>Font</code> object
* has a non-identity AffineTransform attribute.
* <code>false</code> otherwise.
* @see java.awt.Font#getTransform
* @since 1.4
*/
public boolean isTransformed() {
return nonIdentityTx;
}
/** {@collect.stats}
* Return true if this Font contains attributes that require extra
* layout processing.
* @return true if the font has layout attributes
* @since 1.6
*/
public boolean hasLayoutAttributes() {
return hasLayoutAttributes;
}
/** {@collect.stats}
* Returns a <code>Font</code> object from the system properties list.
* <code>nm</code> is treated as the name of a system property to be
* obtained. The <code>String</code> value of this property is then
* interpreted as a <code>Font</code> object according to the
* specification of <code>Font.decode(String)</code>
* If the specified property is not found, or the executing code does
* not have permission to read the property, null is returned instead.
*
* @param nm the property name
* @return a <code>Font</code> object that the property name
* describes, or null if no such property exists.
* @throws NullPointerException if nm is null.
* @since 1.2
* @see #decode(String)
*/
public static Font getFont(String nm) {
return getFont(nm, null);
}
/** {@collect.stats}
* Returns the <code>Font</code> that the <code>str</code>
* argument describes.
* To ensure that this method returns the desired Font,
* format the <code>str</code> parameter in
* one of these ways
* <p>
* <ul>
* <li><em>fontname-style-pointsize</em>
* <li><em>fontname-pointsize</em>
* <li><em>fontname-style</em>
* <li><em>fontname</em>
* <li><em>fontname style pointsize</em>
* <li><em>fontname pointsize</em>
* <li><em>fontname style</em>
* <li><em>fontname</em>
* </ul>
* in which <i>style</i> is one of the four
* case-insensitive strings:
* <code>"PLAIN"</code>, <code>"BOLD"</code>, <code>"BOLDITALIC"</code>, or
* <code>"ITALIC"</code>, and pointsize is a positive decimal integer
* representation of the point size.
* For example, if you want a font that is Arial, bold, with
* a point size of 18, you would call this method with:
* "Arial-BOLD-18".
* This is equivalent to calling the Font constructor :
* <code>new Font("Arial", Font.BOLD, 18);</code>
* and the values are interpreted as specified by that constructor.
* <p>
* A valid trailing decimal field is always interpreted as the pointsize.
* Therefore a fontname containing a trailing decimal value should not
* be used in the fontname only form.
* <p>
* If a style name field is not one of the valid style strings, it is
* interpreted as part of the font name, and the default style is used.
* <p>
* Only one of ' ' or '-' may be used to separate fields in the input.
* The identified separator is the one closest to the end of the string
* which separates a valid pointsize, or a valid style name from
* the rest of the string.
* Null (empty) pointsize and style fields are treated
* as valid fields with the default value for that field.
*<p>
* Some font names may include the separator characters ' ' or '-'.
* If <code>str</code> is not formed with 3 components, e.g. such that
* <code>style</code> or <code>pointsize</code> fields are not present in
* <code>str</code>, and <code>fontname</code> also contains a
* character determined to be the separator character
* then these characters where they appear as intended to be part of
* <code>fontname</code> may instead be interpreted as separators
* so the font name may not be properly recognised.
*
* <p>
* The default size is 12 and the default style is PLAIN.
* If <code>str</code> does not specify a valid size, the returned
* <code>Font</code> has a size of 12. If <code>str</code> does not
* specify a valid style, the returned Font has a style of PLAIN.
* If you do not specify a valid font name in
* the <code>str</code> argument, this method will return
* a font with the family name "Dialog".
* To determine what font family names are available on
* your system, use the
* {@link GraphicsEnvironment#getAvailableFontFamilyNames()} method.
* If <code>str</code> is <code>null</code>, a new <code>Font</code>
* is returned with the family name "Dialog", a size of 12 and a
* PLAIN style.
* @param str the name of the font, or <code>null</code>
* @return the <code>Font</code> object that <code>str</code>
* describes, or a new default <code>Font</code> if
* <code>str</code> is <code>null</code>.
* @see #getFamily
* @since JDK1.1
*/
public static Font decode(String str) {
String fontName = str;
String styleName = "";
int fontSize = 12;
int fontStyle = Font.PLAIN;
if (str == null) {
return new Font(DIALOG, fontStyle, fontSize);
}
int lastHyphen = str.lastIndexOf('-');
int lastSpace = str.lastIndexOf(' ');
char sepChar = (lastHyphen > lastSpace) ? '-' : ' ';
int sizeIndex = str.lastIndexOf(sepChar);
int styleIndex = str.lastIndexOf(sepChar, sizeIndex-1);
int strlen = str.length();
if (sizeIndex > 0 && sizeIndex+1 < strlen) {
try {
fontSize =
Integer.valueOf(str.substring(sizeIndex+1)).intValue();
if (fontSize <= 0) {
fontSize = 12;
}
} catch (NumberFormatException e) {
/* It wasn't a valid size, if we didn't also find the
* start of the style string perhaps this is the style */
styleIndex = sizeIndex;
sizeIndex = strlen;
if (str.charAt(sizeIndex-1) == sepChar) {
sizeIndex--;
}
}
}
if (styleIndex >= 0 && styleIndex+1 < strlen) {
styleName = str.substring(styleIndex+1, sizeIndex);
styleName = styleName.toLowerCase(Locale.ENGLISH);
if (styleName.equals("bolditalic")) {
fontStyle = Font.BOLD | Font.ITALIC;
} else if (styleName.equals("italic")) {
fontStyle = Font.ITALIC;
} else if (styleName.equals("bold")) {
fontStyle = Font.BOLD;
} else if (styleName.equals("plain")) {
fontStyle = Font.PLAIN;
} else {
/* this string isn't any of the expected styles, so
* assume its part of the font name
*/
styleIndex = sizeIndex;
if (str.charAt(styleIndex-1) == sepChar) {
styleIndex--;
}
}
fontName = str.substring(0, styleIndex);
} else {
int fontEnd = strlen;
if (styleIndex > 0) {
fontEnd = styleIndex;
} else if (sizeIndex > 0) {
fontEnd = sizeIndex;
}
if (fontEnd > 0 && str.charAt(fontEnd-1) == sepChar) {
fontEnd--;
}
fontName = str.substring(0, fontEnd);
}
return new Font(fontName, fontStyle, fontSize);
}
/** {@collect.stats}
* Gets the specified <code>Font</code> from the system properties
* list. As in the <code>getProperty</code> method of
* <code>System</code>, the first
* argument is treated as the name of a system property to be
* obtained. The <code>String</code> value of this property is then
* interpreted as a <code>Font</code> object.
* <p>
* The property value should be one of the forms accepted by
* <code>Font.decode(String)</code>
* If the specified property is not found, or the executing code does not
* have permission to read the property, the <code>font</code>
* argument is returned instead.
* @param nm the case-insensitive property name
* @param font a default <code>Font</code> to return if property
* <code>nm</code> is not defined
* @return the <code>Font</code> value of the property.
* @throws NullPointerException if nm is null.
* @see #decode(String)
*/
public static Font getFont(String nm, Font font) {
String str = null;
try {
str =System.getProperty(nm);
} catch(SecurityException e) {
}
if (str == null) {
return font;
}
return decode ( str );
}
transient int hash;
/** {@collect.stats}
* Returns a hashcode for this <code>Font</code>.
* @return a hashcode value for this <code>Font</code>.
* @since JDK1.0
*/
public int hashCode() {
if (hash == 0) {
hash = name.hashCode() ^ style ^ size;
/* It is possible many fonts differ only in transform.
* So include the transform in the hash calculation.
* nonIdentityTx is set whenever there is a transform in
* 'values'. The tests for null are required because it can
* also be set for other reasons.
*/
if (nonIdentityTx &&
values != null && values.getTransform() != null) {
hash ^= values.getTransform().hashCode();
}
}
return hash;
}
/** {@collect.stats}
* Compares this <code>Font</code> object to the specified
* <code>Object</code>.
* @param obj the <code>Object</code> to compare
* @return <code>true</code> if the objects are the same
* or if the argument is a <code>Font</code> object
* describing the same font as this object;
* <code>false</code> otherwise.
* @since JDK1.0
*/
public boolean equals(Object obj) {
if (obj == this) {
return true;
}
if (obj != null) {
try {
Font font = (Font)obj;
if (size == font.size &&
style == font.style &&
nonIdentityTx == font.nonIdentityTx &&
hasLayoutAttributes == font.hasLayoutAttributes &&
pointSize == font.pointSize &&
name.equals(font.name)) {
/* 'values' is usually initialized lazily, except when
* the font is constructed from a Map, or derived using
* a Map or other values. So if only one font has
* the field initialized we need to initialize it in
* the other instance and compare.
*/
if (values == null) {
if (font.values == null) {
return true;
} else {
return getAttributeValues().equals(font.values);
}
} else {
return values.equals(font.getAttributeValues());
}
}
}
catch (ClassCastException e) {
}
}
return false;
}
/** {@collect.stats}
* Converts this <code>Font</code> object to a <code>String</code>
* representation.
* @return a <code>String</code> representation of this
* <code>Font</code> object.
* @since JDK1.0
*/
// NOTE: This method may be called by privileged threads.
// DO NOT INVOKE CLIENT CODE ON THIS THREAD!
public String toString() {
String strStyle;
if (isBold()) {
strStyle = isItalic() ? "bolditalic" : "bold";
} else {
strStyle = isItalic() ? "italic" : "plain";
}
return getClass().getName() + "[family=" + getFamily() + ",name=" + name + ",style=" +
strStyle + ",size=" + size + "]";
} // toString()
/** {@collect.stats} Serialization support. A <code>readObject</code>
* method is neccessary because the constructor creates
* the font's peer, and we can't serialize the peer.
* Similarly the computed font "family" may be different
* at <code>readObject</code> time than at
* <code>writeObject</code> time. An integer version is
* written so that future versions of this class will be
* able to recognize serialized output from this one.
*/
/** {@collect.stats}
* The <code>Font</code> Serializable Data Form.
*
* @serial
*/
private int fontSerializedDataVersion = 1;
/** {@collect.stats}
* Writes default serializable fields to a stream.
*
* @param s the <code>ObjectOutputStream</code> to write
* @see AWTEventMulticaster#save(ObjectOutputStream, String, EventListener)
* @see #readObject(java.io.ObjectInputStream)
*/
private void writeObject(java.io.ObjectOutputStream s)
throws java.lang.ClassNotFoundException,
java.io.IOException
{
if (values != null) {
synchronized(values) {
// transient
fRequestedAttributes = values.toSerializableHashtable();
s.defaultWriteObject();
fRequestedAttributes = null;
}
} else {
s.defaultWriteObject();
}
}
/** {@collect.stats}
* Reads the <code>ObjectInputStream</code>.
* Unrecognized keys or values will be ignored.
*
* @param s the <code>ObjectInputStream</code> to read
* @serial
* @see #writeObject(java.io.ObjectOutputStream)
*/
private void readObject(java.io.ObjectInputStream s)
throws java.lang.ClassNotFoundException,
java.io.IOException
{
s.defaultReadObject();
if (pointSize == 0) {
pointSize = (float)size;
}
// Handle fRequestedAttributes.
// in 1.5, we always streamed out the font values plus
// TRANSFORM, SUPERSCRIPT, and WIDTH, regardless of whether the
// values were default or not. In 1.6 we only stream out
// defined values. So, 1.6 streams in from a 1.5 stream,
// it check each of these values and 'undefines' it if the
// value is the default.
if (fRequestedAttributes != null) {
values = getAttributeValues(); // init
AttributeValues extras =
AttributeValues.fromSerializableHashtable(fRequestedAttributes);
if (!AttributeValues.is16Hashtable(fRequestedAttributes)) {
extras.unsetDefault(); // if legacy stream, undefine these
}
values = getAttributeValues().merge(extras);
this.nonIdentityTx = values.anyNonDefault(EXTRA_MASK);
this.hasLayoutAttributes = values.anyNonDefault(LAYOUT_MASK);
fRequestedAttributes = null; // don't need it any more
}
}
/** {@collect.stats}
* Returns the number of glyphs in this <code>Font</code>. Glyph codes
* for this <code>Font</code> range from 0 to
* <code>getNumGlyphs()</code> - 1.
* @return the number of glyphs in this <code>Font</code>.
* @since 1.2
*/
public int getNumGlyphs() {
return getFont2D().getNumGlyphs();
}
/** {@collect.stats}
* Returns the glyphCode which is used when this <code>Font</code>
* does not have a glyph for a specified unicode code point.
* @return the glyphCode of this <code>Font</code>.
* @since 1.2
*/
public int getMissingGlyphCode() {
return getFont2D().getMissingGlyphCode();
}
/** {@collect.stats}
* Returns the baseline appropriate for displaying this character.
* <p>
* Large fonts can support different writing systems, and each system can
* use a different baseline.
* The character argument determines the writing system to use. Clients
* should not assume all characters use the same baseline.
*
* @param c a character used to identify the writing system
* @return the baseline appropriate for the specified character.
* @see LineMetrics#getBaselineOffsets
* @see #ROMAN_BASELINE
* @see #CENTER_BASELINE
* @see #HANGING_BASELINE
* @since 1.2
*/
public byte getBaselineFor(char c) {
return getFont2D().getBaselineFor(c);
}
/** {@collect.stats}
* Returns a map of font attributes available in this
* <code>Font</code>. Attributes include things like ligatures and
* glyph substitution.
* @return the attributes map of this <code>Font</code>.
*/
public Map<TextAttribute,?> getAttributes(){
return new AttributeMap(getAttributeValues());
}
/** {@collect.stats}
* Returns the keys of all the attributes supported by this
* <code>Font</code>. These attributes can be used to derive other
* fonts.
* @return an array containing the keys of all the attributes
* supported by this <code>Font</code>.
* @since 1.2
*/
public Attribute[] getAvailableAttributes() {
// FONT is not supported by Font
Attribute attributes[] = {
TextAttribute.FAMILY,
TextAttribute.WEIGHT,
TextAttribute.WIDTH,
TextAttribute.POSTURE,
TextAttribute.SIZE,
TextAttribute.TRANSFORM,
TextAttribute.SUPERSCRIPT,
TextAttribute.CHAR_REPLACEMENT,
TextAttribute.FOREGROUND,
TextAttribute.BACKGROUND,
TextAttribute.UNDERLINE,
TextAttribute.STRIKETHROUGH,
TextAttribute.RUN_DIRECTION,
TextAttribute.BIDI_EMBEDDING,
TextAttribute.JUSTIFICATION,
TextAttribute.INPUT_METHOD_HIGHLIGHT,
TextAttribute.INPUT_METHOD_UNDERLINE,
TextAttribute.SWAP_COLORS,
TextAttribute.NUMERIC_SHAPING,
TextAttribute.KERNING,
TextAttribute.LIGATURES,
TextAttribute.TRACKING,
};
return attributes;
}
/** {@collect.stats}
* Creates a new <code>Font</code> object by replicating this
* <code>Font</code> object and applying a new style and size.
* @param style the style for the new <code>Font</code>
* @param size the size for the new <code>Font</code>
* @return a new <code>Font</code> object.
* @since 1.2
*/
public Font deriveFont(int style, float size){
if (values == null) {
return new Font(name, style, size, createdFont, font2DHandle);
}
AttributeValues newValues = getAttributeValues().clone();
int oldStyle = (this.style != style) ? this.style : -1;
applyStyle(style, newValues);
newValues.setSize(size);
return new Font(newValues, null, oldStyle, createdFont, font2DHandle);
}
/** {@collect.stats}
* Creates a new <code>Font</code> object by replicating this
* <code>Font</code> object and applying a new style and transform.
* @param style the style for the new <code>Font</code>
* @param trans the <code>AffineTransform</code> associated with the
* new <code>Font</code>
* @return a new <code>Font</code> object.
* @throws IllegalArgumentException if <code>trans</code> is
* <code>null</code>
* @since 1.2
*/
public Font deriveFont(int style, AffineTransform trans){
AttributeValues newValues = getAttributeValues().clone();
int oldStyle = (this.style != style) ? this.style : -1;
applyStyle(style, newValues);
applyTransform(trans, newValues);
return new Font(newValues, null, oldStyle, createdFont, font2DHandle);
}
/** {@collect.stats}
* Creates a new <code>Font</code> object by replicating the current
* <code>Font</code> object and applying a new size to it.
* @param size the size for the new <code>Font</code>.
* @return a new <code>Font</code> object.
* @since 1.2
*/
public Font deriveFont(float size){
if (values == null) {
return new Font(name, style, size, createdFont, font2DHandle);
}
AttributeValues newValues = getAttributeValues().clone();
newValues.setSize(size);
return new Font(newValues, null, -1, createdFont, font2DHandle);
}
/** {@collect.stats}
* Creates a new <code>Font</code> object by replicating the current
* <code>Font</code> object and applying a new transform to it.
* @param trans the <code>AffineTransform</code> associated with the
* new <code>Font</code>
* @return a new <code>Font</code> object.
* @throws IllegalArgumentException if <code>trans</code> is
* <code>null</code>
* @since 1.2
*/
public Font deriveFont(AffineTransform trans){
AttributeValues newValues = getAttributeValues().clone();
applyTransform(trans, newValues);
return new Font(newValues, null, -1, createdFont, font2DHandle);
}
/** {@collect.stats}
* Creates a new <code>Font</code> object by replicating the current
* <code>Font</code> object and applying a new style to it.
* @param style the style for the new <code>Font</code>
* @return a new <code>Font</code> object.
* @since 1.2
*/
public Font deriveFont(int style){
if (values == null) {
return new Font(name, style, size, createdFont, font2DHandle);
}
AttributeValues newValues = getAttributeValues().clone();
int oldStyle = (this.style != style) ? this.style : -1;
applyStyle(style, newValues);
return new Font(newValues, null, oldStyle, createdFont, font2DHandle);
}
/** {@collect.stats}
* Creates a new <code>Font</code> object by replicating the current
* <code>Font</code> object and applying a new set of font attributes
* to it.
*
* @param attributes a map of attributes enabled for the new
* <code>Font</code>
* @return a new <code>Font</code> object.
* @since 1.2
*/
public Font deriveFont(Map<? extends Attribute, ?> attributes) {
if (attributes == null) {
return this;
}
AttributeValues newValues = getAttributeValues().clone();
newValues.merge(attributes, RECOGNIZED_MASK);
return new Font(newValues, name, style, createdFont, font2DHandle);
}
/** {@collect.stats}
* Checks if this <code>Font</code> has a glyph for the specified
* character.
*
* <p> <b>Note:</b> This method cannot handle <a
* href="../../java/lang/Character.html#supplementary"> supplementary
* characters</a>. To support all Unicode characters, including
* supplementary characters, use the {@link #canDisplay(int)}
* method or <code>canDisplayUpTo</code> methods.
*
* @param c the character for which a glyph is needed
* @return <code>true</code> if this <code>Font</code> has a glyph for this
* character; <code>false</code> otherwise.
* @since 1.2
*/
public boolean canDisplay(char c){
return getFont2D().canDisplay(c);
}
/** {@collect.stats}
* Checks if this <code>Font</code> has a glyph for the specified
* character.
*
* @param codePoint the character (Unicode code point) for which a glyph
* is needed.
* @return <code>true</code> if this <code>Font</code> has a glyph for the
* character; <code>false</code> otherwise.
* @throws IllegalArgumentException if the code point is not a valid Unicode
* code point.
* @see Character#isValidCodePoint(int)
* @since 1.5
*/
public boolean canDisplay(int codePoint) {
if (!Character.isValidCodePoint(codePoint)) {
throw new IllegalArgumentException("invalid code point: " +
Integer.toHexString(codePoint));
}
return getFont2D().canDisplay(codePoint);
}
/** {@collect.stats}
* Indicates whether or not this <code>Font</code> can display a
* specified <code>String</code>. For strings with Unicode encoding,
* it is important to know if a particular font can display the
* string. This method returns an offset into the <code>String</code>
* <code>str</code> which is the first character this
* <code>Font</code> cannot display without using the missing glyph
* code. If the <code>Font</code> can display all characters, -1 is
* returned.
* @param str a <code>String</code> object
* @return an offset into <code>str</code> that points
* to the first character in <code>str</code> that this
* <code>Font</code> cannot display; or <code>-1</code> if
* this <code>Font</code> can display all characters in
* <code>str</code>.
* @since 1.2
*/
public int canDisplayUpTo(String str) {
return canDisplayUpTo(new StringCharacterIterator(str), 0,
str.length());
}
/** {@collect.stats}
* Indicates whether or not this <code>Font</code> can display
* the characters in the specified <code>text</code>
* starting at <code>start</code> and ending at
* <code>limit</code>. This method is a convenience overload.
* @param text the specified array of <code>char</code> values
* @param start the specified starting offset (in
* <code>char</code>s) into the specified array of
* <code>char</code> values
* @param limit the specified ending offset (in
* <code>char</code>s) into the specified array of
* <code>char</code> values
* @return an offset into <code>text</code> that points
* to the first character in <code>text</code> that this
* <code>Font</code> cannot display; or <code>-1</code> if
* this <code>Font</code> can display all characters in
* <code>text</code>.
* @since 1.2
*/
public int canDisplayUpTo(char[] text, int start, int limit) {
while (start < limit && canDisplay(text[start])) {
++start;
}
return start == limit ? -1 : start;
}
/** {@collect.stats}
* Indicates whether or not this <code>Font</code> can display the
* text specified by the <code>iter</code> starting at
* <code>start</code> and ending at <code>limit</code>.
*
* @param iter a {@link CharacterIterator} object
* @param start the specified starting offset into the specified
* <code>CharacterIterator</code>.
* @param limit the specified ending offset into the specified
* <code>CharacterIterator</code>.
* @return an offset into <code>iter</code> that points
* to the first character in <code>iter</code> that this
* <code>Font</code> cannot display; or <code>-1</code> if
* this <code>Font</code> can display all characters in
* <code>iter</code>.
* @since 1.2
*/
public int canDisplayUpTo(CharacterIterator iter, int start, int limit) {
for (char c = iter.setIndex(start);
iter.getIndex() < limit && canDisplay(c);
c = iter.next()) {
}
int result = iter.getIndex();
return result == limit ? -1 : result;
}
/** {@collect.stats}
* Returns the italic angle of this <code>Font</code>. The italic angle
* is the inverse slope of the caret which best matches the posture of this
* <code>Font</code>.
* @see TextAttribute#POSTURE
* @return the angle of the ITALIC style of this <code>Font</code>.
*/
public float getItalicAngle() {
return getItalicAngle(null);
}
/* The FRC hints don't affect the value of the italic angle but
* we need to pass them in to look up a strike.
* If we can pass in ones already being used it can prevent an extra
* strike from being allocated. Note that since italic angle is
* a property of the font, the font transform is needed not the
* device transform. Finally, this is private but the only caller of this
* in the JDK - and the only likely caller - is in this same class.
*/
private float getItalicAngle(FontRenderContext frc) {
AffineTransform at = (isTransformed()) ? getTransform() : identityTx;
Object aa, fm;
if (frc == null) {
aa = RenderingHints.VALUE_TEXT_ANTIALIAS_OFF;
fm = RenderingHints.VALUE_FRACTIONALMETRICS_OFF;
} else {
aa = frc.getAntiAliasingHint();
fm = frc.getFractionalMetricsHint();
}
return getFont2D().getItalicAngle(this, at, aa, fm);
}
/** {@collect.stats}
* Checks whether or not this <code>Font</code> has uniform
* line metrics. A logical <code>Font</code> might be a
* composite font, which means that it is composed of different
* physical fonts to cover different code ranges. Each of these
* fonts might have different <code>LineMetrics</code>. If the
* logical <code>Font</code> is a single
* font then the metrics would be uniform.
* @return <code>true</code> if this <code>Font</code> has
* uniform line metrics; <code>false</code> otherwise.
*/
public boolean hasUniformLineMetrics() {
return false; // REMIND always safe, but prevents caller optimize
}
private transient SoftReference flmref;
private FontLineMetrics defaultLineMetrics(FontRenderContext frc) {
FontLineMetrics flm = null;
if (flmref == null
|| (flm = (FontLineMetrics)flmref.get()) == null
|| !flm.frc.equals(frc)) {
/* The device transform in the frc is not used in obtaining line
* metrics, although it probably should be: REMIND find why not?
* The font transform is used but its applied in getFontMetrics, so
* just pass identity here
*/
float [] metrics = new float[8];
getFont2D().getFontMetrics(this, identityTx,
frc.getAntiAliasingHint(),
frc.getFractionalMetricsHint(),
metrics);
float ascent = metrics[0];
float descent = metrics[1];
float leading = metrics[2];
float ssOffset = 0;
if (values != null && values.getSuperscript() != 0) {
ssOffset = (float)getTransform().getTranslateY();
ascent -= ssOffset;
descent += ssOffset;
}
float height = ascent + descent + leading;
int baselineIndex = 0; // need real index, assumes roman for everything
// need real baselines eventually
float[] baselineOffsets = { 0, (descent/2f - ascent) / 2f, -ascent };
float strikethroughOffset = metrics[4];
float strikethroughThickness = metrics[5];
float underlineOffset = metrics[6];
float underlineThickness = metrics[7];
float italicAngle = getItalicAngle(frc);
if (isTransformed()) {
AffineTransform ctx = values.getCharTransform(); // extract rotation
if (ctx != null) {
Point2D.Float pt = new Point2D.Float();
pt.setLocation(0, strikethroughOffset);
ctx.deltaTransform(pt, pt);
strikethroughOffset = pt.y;
pt.setLocation(0, strikethroughThickness);
ctx.deltaTransform(pt, pt);
strikethroughThickness = pt.y;
pt.setLocation(0, underlineOffset);
ctx.deltaTransform(pt, pt);
underlineOffset = pt.y;
pt.setLocation(0, underlineThickness);
ctx.deltaTransform(pt, pt);
underlineThickness = pt.y;
}
}
strikethroughOffset += ssOffset;
underlineOffset += ssOffset;
CoreMetrics cm = new CoreMetrics(ascent, descent, leading, height,
baselineIndex, baselineOffsets,
strikethroughOffset, strikethroughThickness,
underlineOffset, underlineThickness,
ssOffset, italicAngle);
flm = new FontLineMetrics(0, cm, frc);
flmref = new SoftReference(flm);
}
return (FontLineMetrics)flm.clone();
}
/** {@collect.stats}
* Returns a {@link LineMetrics} object created with the specified
* <code>String</code> and {@link FontRenderContext}.
* @param str the specified <code>String</code>
* @param frc the specified <code>FontRenderContext</code>
* @return a <code>LineMetrics</code> object created with the
* specified <code>String</code> and {@link FontRenderContext}.
*/
public LineMetrics getLineMetrics( String str, FontRenderContext frc) {
FontLineMetrics flm = defaultLineMetrics(frc);
flm.numchars = str.length();
return flm;
}
/** {@collect.stats}
* Returns a <code>LineMetrics</code> object created with the
* specified arguments.
* @param str the specified <code>String</code>
* @param beginIndex the initial offset of <code>str</code>
* @param limit the end offset of <code>str</code>
* @param frc the specified <code>FontRenderContext</code>
* @return a <code>LineMetrics</code> object created with the
* specified arguments.
*/
public LineMetrics getLineMetrics( String str,
int beginIndex, int limit,
FontRenderContext frc) {
FontLineMetrics flm = defaultLineMetrics(frc);
int numChars = limit - beginIndex;
flm.numchars = (numChars < 0)? 0: numChars;
return flm;
}
/** {@collect.stats}
* Returns a <code>LineMetrics</code> object created with the
* specified arguments.
* @param chars an array of characters
* @param beginIndex the initial offset of <code>chars</code>
* @param limit the end offset of <code>chars</code>
* @param frc the specified <code>FontRenderContext</code>
* @return a <code>LineMetrics</code> object created with the
* specified arguments.
*/
public LineMetrics getLineMetrics(char [] chars,
int beginIndex, int limit,
FontRenderContext frc) {
FontLineMetrics flm = defaultLineMetrics(frc);
int numChars = limit - beginIndex;
flm.numchars = (numChars < 0)? 0: numChars;
return flm;
}
/** {@collect.stats}
* Returns a <code>LineMetrics</code> object created with the
* specified arguments.
* @param ci the specified <code>CharacterIterator</code>
* @param beginIndex the initial offset in <code>ci</code>
* @param limit the end offset of <code>ci</code>
* @param frc the specified <code>FontRenderContext</code>
* @return a <code>LineMetrics</code> object created with the
* specified arguments.
*/
public LineMetrics getLineMetrics(CharacterIterator ci,
int beginIndex, int limit,
FontRenderContext frc) {
FontLineMetrics flm = defaultLineMetrics(frc);
int numChars = limit - beginIndex;
flm.numchars = (numChars < 0)? 0: numChars;
return flm;
}
/** {@collect.stats}
* Returns the logical bounds of the specified <code>String</code> in
* the specified <code>FontRenderContext</code>. The logical bounds
* contains the origin, ascent, advance, and height, which includes
* the leading. The logical bounds does not always enclose all the
* text. For example, in some languages and in some fonts, accent
* marks can be positioned above the ascent or below the descent.
* To obtain a visual bounding box, which encloses all the text,
* use the {@link TextLayout#getBounds() getBounds} method of
* <code>TextLayout</code>.
* <p>Note: The returned bounds is in baseline-relative coordinates
* (see {@link java.awt.Font class notes}).
* @param str the specified <code>String</code>
* @param frc the specified <code>FontRenderContext</code>
* @return a {@link Rectangle2D} that is the bounding box of the
* specified <code>String</code> in the specified
* <code>FontRenderContext</code>.
* @see FontRenderContext
* @see Font#createGlyphVector
* @since 1.2
*/
public Rectangle2D getStringBounds( String str, FontRenderContext frc) {
char[] array = str.toCharArray();
return getStringBounds(array, 0, array.length, frc);
}
/** {@collect.stats}
* Returns the logical bounds of the specified <code>String</code> in
* the specified <code>FontRenderContext</code>. The logical bounds
* contains the origin, ascent, advance, and height, which includes
* the leading. The logical bounds does not always enclose all the
* text. For example, in some languages and in some fonts, accent
* marks can be positioned above the ascent or below the descent.
* To obtain a visual bounding box, which encloses all the text,
* use the {@link TextLayout#getBounds() getBounds} method of
* <code>TextLayout</code>.
* <p>Note: The returned bounds is in baseline-relative coordinates
* (see {@link java.awt.Font class notes}).
* @param str the specified <code>String</code>
* @param beginIndex the initial offset of <code>str</code>
* @param limit the end offset of <code>str</code>
* @param frc the specified <code>FontRenderContext</code>
* @return a <code>Rectangle2D</code> that is the bounding box of the
* specified <code>String</code> in the specified
* <code>FontRenderContext</code>.
* @throws IndexOutOfBoundsException if <code>beginIndex</code> is
* less than zero, or <code>limit</code> is greater than the
* length of <code>str</code>, or <code>beginIndex</code>
* is greater than <code>limit</code>.
* @see FontRenderContext
* @see Font#createGlyphVector
* @since 1.2
*/
public Rectangle2D getStringBounds( String str,
int beginIndex, int limit,
FontRenderContext frc) {
String substr = str.substring(beginIndex, limit);
return getStringBounds(substr, frc);
}
/** {@collect.stats}
* Returns the logical bounds of the specified array of characters
* in the specified <code>FontRenderContext</code>. The logical
* bounds contains the origin, ascent, advance, and height, which
* includes the leading. The logical bounds does not always enclose
* all the text. For example, in some languages and in some fonts,
* accent marks can be positioned above the ascent or below the
* descent. To obtain a visual bounding box, which encloses all the
* text, use the {@link TextLayout#getBounds() getBounds} method of
* <code>TextLayout</code>.
* <p>Note: The returned bounds is in baseline-relative coordinates
* (see {@link java.awt.Font class notes}).
* @param chars an array of characters
* @param beginIndex the initial offset in the array of
* characters
* @param limit the end offset in the array of characters
* @param frc the specified <code>FontRenderContext</code>
* @return a <code>Rectangle2D</code> that is the bounding box of the
* specified array of characters in the specified
* <code>FontRenderContext</code>.
* @throws IndexOutOfBoundsException if <code>beginIndex</code> is
* less than zero, or <code>limit</code> is greater than the
* length of <code>chars</code>, or <code>beginIndex</code>
* is greater than <code>limit</code>.
* @see FontRenderContext
* @see Font#createGlyphVector
* @since 1.2
*/
public Rectangle2D getStringBounds(char [] chars,
int beginIndex, int limit,
FontRenderContext frc) {
if (beginIndex < 0) {
throw new IndexOutOfBoundsException("beginIndex: " + beginIndex);
}
if (limit > chars.length) {
throw new IndexOutOfBoundsException("limit: " + limit);
}
if (beginIndex > limit) {
throw new IndexOutOfBoundsException("range length: " +
(limit - beginIndex));
}
// this code should be in textlayout
// quick check for simple text, assume GV ok to use if simple
boolean simple = values == null ||
(values.getKerning() == 0 && values.getLigatures() == 0 &&
values.getBaselineTransform() == null);
if (simple) {
simple = !FontManager.isComplexText(chars, beginIndex, limit);
}
if (simple) {
GlyphVector gv = new StandardGlyphVector(this, chars, beginIndex,
limit - beginIndex, frc);
return gv.getLogicalBounds();
} else {
// need char array constructor on textlayout
String str = new String(chars, beginIndex, limit - beginIndex);
TextLayout tl = new TextLayout(str, this, frc);
return new Rectangle2D.Float(0, -tl.getAscent(), tl.getAdvance(),
tl.getAscent() + tl.getDescent() +
tl.getLeading());
}
}
/** {@collect.stats}
* Returns the logical bounds of the characters indexed in the
* specified {@link CharacterIterator} in the
* specified <code>FontRenderContext</code>. The logical bounds
* contains the origin, ascent, advance, and height, which includes
* the leading. The logical bounds does not always enclose all the
* text. For example, in some languages and in some fonts, accent
* marks can be positioned above the ascent or below the descent.
* To obtain a visual bounding box, which encloses all the text,
* use the {@link TextLayout#getBounds() getBounds} method of
* <code>TextLayout</code>.
* <p>Note: The returned bounds is in baseline-relative coordinates
* (see {@link java.awt.Font class notes}).
* @param ci the specified <code>CharacterIterator</code>
* @param beginIndex the initial offset in <code>ci</code>
* @param limit the end offset in <code>ci</code>
* @param frc the specified <code>FontRenderContext</code>
* @return a <code>Rectangle2D</code> that is the bounding box of the
* characters indexed in the specified <code>CharacterIterator</code>
* in the specified <code>FontRenderContext</code>.
* @see FontRenderContext
* @see Font#createGlyphVector
* @since 1.2
* @throws IndexOutOfBoundsException if <code>beginIndex</code> is
* less than the start index of <code>ci</code>, or
* <code>limit</code> is greater than the end index of
* <code>ci</code>, or <code>beginIndex</code> is greater
* than <code>limit</code>
*/
public Rectangle2D getStringBounds(CharacterIterator ci,
int beginIndex, int limit,
FontRenderContext frc) {
int start = ci.getBeginIndex();
int end = ci.getEndIndex();
if (beginIndex < start) {
throw new IndexOutOfBoundsException("beginIndex: " + beginIndex);
}
if (limit > end) {
throw new IndexOutOfBoundsException("limit: " + limit);
}
if (beginIndex > limit) {
throw new IndexOutOfBoundsException("range length: " +
(limit - beginIndex));
}
char[] arr = new char[limit - beginIndex];
ci.setIndex(beginIndex);
for(int idx = 0; idx < arr.length; idx++) {
arr[idx] = ci.current();
ci.next();
}
return getStringBounds(arr,0,arr.length,frc);
}
/** {@collect.stats}
* Returns the bounds for the character with the maximum
* bounds as defined in the specified <code>FontRenderContext</code>.
* <p>Note: The returned bounds is in baseline-relative coordinates
* (see {@link java.awt.Font class notes}).
* @param frc the specified <code>FontRenderContext</code>
* @return a <code>Rectangle2D</code> that is the bounding box
* for the character with the maximum bounds.
*/
public Rectangle2D getMaxCharBounds(FontRenderContext frc) {
float [] metrics = new float[4];
getFont2D().getFontMetrics(this, frc, metrics);
return new Rectangle2D.Float(0, -metrics[0],
metrics[3],
metrics[0] + metrics[1] + metrics[2]);
}
/** {@collect.stats}
* Creates a {@link java.awt.font.GlyphVector GlyphVector} by
* mapping characters to glyphs one-to-one based on the
* Unicode cmap in this <code>Font</code>. This method does no other
* processing besides the mapping of glyphs to characters. This
* means that this method is not useful for some scripts, such
* as Arabic, Hebrew, Thai, and Indic, that require reordering,
* shaping, or ligature substitution.
* @param frc the specified <code>FontRenderContext</code>
* @param str the specified <code>String</code>
* @return a new <code>GlyphVector</code> created with the
* specified <code>String</code> and the specified
* <code>FontRenderContext</code>.
*/
public GlyphVector createGlyphVector(FontRenderContext frc, String str)
{
return (GlyphVector)new StandardGlyphVector(this, str, frc);
}
/** {@collect.stats}
* Creates a {@link java.awt.font.GlyphVector GlyphVector} by
* mapping characters to glyphs one-to-one based on the
* Unicode cmap in this <code>Font</code>. This method does no other
* processing besides the mapping of glyphs to characters. This
* means that this method is not useful for some scripts, such
* as Arabic, Hebrew, Thai, and Indic, that require reordering,
* shaping, or ligature substitution.
* @param frc the specified <code>FontRenderContext</code>
* @param chars the specified array of characters
* @return a new <code>GlyphVector</code> created with the
* specified array of characters and the specified
* <code>FontRenderContext</code>.
*/
public GlyphVector createGlyphVector(FontRenderContext frc, char[] chars)
{
return (GlyphVector)new StandardGlyphVector(this, chars, frc);
}
/** {@collect.stats}
* Creates a {@link java.awt.font.GlyphVector GlyphVector} by
* mapping the specified characters to glyphs one-to-one based on the
* Unicode cmap in this <code>Font</code>. This method does no other
* processing besides the mapping of glyphs to characters. This
* means that this method is not useful for some scripts, such
* as Arabic, Hebrew, Thai, and Indic, that require reordering,
* shaping, or ligature substitution.
* @param frc the specified <code>FontRenderContext</code>
* @param ci the specified <code>CharacterIterator</code>
* @return a new <code>GlyphVector</code> created with the
* specified <code>CharacterIterator</code> and the specified
* <code>FontRenderContext</code>.
*/
public GlyphVector createGlyphVector( FontRenderContext frc,
CharacterIterator ci)
{
return (GlyphVector)new StandardGlyphVector(this, ci, frc);
}
/** {@collect.stats}
* Creates a {@link java.awt.font.GlyphVector GlyphVector} by
* mapping characters to glyphs one-to-one based on the
* Unicode cmap in this <code>Font</code>. This method does no other
* processing besides the mapping of glyphs to characters. This
* means that this method is not useful for some scripts, such
* as Arabic, Hebrew, Thai, and Indic, that require reordering,
* shaping, or ligature substitution.
* @param frc the specified <code>FontRenderContext</code>
* @param glyphCodes the specified integer array
* @return a new <code>GlyphVector</code> created with the
* specified integer array and the specified
* <code>FontRenderContext</code>.
*/
public GlyphVector createGlyphVector( FontRenderContext frc,
int [] glyphCodes)
{
return (GlyphVector)new StandardGlyphVector(this, glyphCodes, frc);
}
/** {@collect.stats}
* Returns a new <code>GlyphVector</code> object, performing full
* layout of the text if possible. Full layout is required for
* complex text, such as Arabic or Hindi. Support for different
* scripts depends on the font and implementation.
* <p>
* Layout requires bidi analysis, as performed by
* <code>Bidi</code>, and should only be performed on text that
* has a uniform direction. The direction is indicated in the
* flags parameter,by using LAYOUT_RIGHT_TO_LEFT to indicate a
* right-to-left (Arabic and Hebrew) run direction, or
* LAYOUT_LEFT_TO_RIGHT to indicate a left-to-right (English)
* run direction.
* <p>
* In addition, some operations, such as Arabic shaping, require
* context, so that the characters at the start and limit can have
* the proper shapes. Sometimes the data in the buffer outside
* the provided range does not have valid data. The values
* LAYOUT_NO_START_CONTEXT and LAYOUT_NO_LIMIT_CONTEXT can be
* added to the flags parameter to indicate that the text before
* start, or after limit, respectively, should not be examined
* for context.
* <p>
* All other values for the flags parameter are reserved.
*
* @param frc the specified <code>FontRenderContext</code>
* @param text the text to layout
* @param start the start of the text to use for the <code>GlyphVector</code>
* @param limit the limit of the text to use for the <code>GlyphVector</code>
* @param flags control flags as described above
* @return a new <code>GlyphVector</code> representing the text between
* start and limit, with glyphs chosen and positioned so as to best represent
* the text
* @throws ArrayIndexOutOfBoundsException if start or limit is
* out of bounds
* @see java.text.Bidi
* @see #LAYOUT_LEFT_TO_RIGHT
* @see #LAYOUT_RIGHT_TO_LEFT
* @see #LAYOUT_NO_START_CONTEXT
* @see #LAYOUT_NO_LIMIT_CONTEXT
* @since 1.4
*/
public GlyphVector layoutGlyphVector(FontRenderContext frc,
char[] text,
int start,
int limit,
int flags) {
GlyphLayout gl = GlyphLayout.get(null); // !!! no custom layout engines
StandardGlyphVector gv = gl.layout(this, frc, text,
start, limit-start, flags, null);
GlyphLayout.done(gl);
return gv;
}
/** {@collect.stats}
* A flag to layoutGlyphVector indicating that text is left-to-right as
* determined by Bidi analysis.
*/
public static final int LAYOUT_LEFT_TO_RIGHT = 0;
/** {@collect.stats}
* A flag to layoutGlyphVector indicating that text is right-to-left as
* determined by Bidi analysis.
*/
public static final int LAYOUT_RIGHT_TO_LEFT = 1;
/** {@collect.stats}
* A flag to layoutGlyphVector indicating that text in the char array
* before the indicated start should not be examined.
*/
public static final int LAYOUT_NO_START_CONTEXT = 2;
/** {@collect.stats}
* A flag to layoutGlyphVector indicating that text in the char array
* after the indicated limit should not be examined.
*/
public static final int LAYOUT_NO_LIMIT_CONTEXT = 4;
private static void applyTransform(AffineTransform trans, AttributeValues values) {
if (trans == null) {
throw new IllegalArgumentException("transform must not be null");
}
values.setTransform(trans);
}
private static void applyStyle(int style, AttributeValues values) {
// WEIGHT_BOLD, WEIGHT_REGULAR
values.setWeight((style & BOLD) != 0 ? 2f : 1f);
// POSTURE_OBLIQUE, POSTURE_REGULAR
values.setPosture((style & ITALIC) != 0 ? .2f : 0f);
}
/*
* Initialize JNI field and method IDs
*/
private static native void initIDs();
/*
* Disposes the native <code>Font</code> object.
*/
protected void finalize() throws Throwable {
/* Yes, its empty, yes, that's OK :-)
* The 2D disposer thread now releases font resources,
* and because this method is empty it does not in fact
* trigger object finalization.
*/
}
}
|
Java
|
/*
* Copyright (c) 1999, 2006, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code 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
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package java.awt;
/** {@collect.stats}
* A set of attributes which control a print job.
* <p>
* Instances of this class control the number of copies, default selection,
* destination, print dialog, file and printer names, page ranges, multiple
* document handling (including collation), and multi-page imposition (such
* as duplex) of every print job which uses the instance. Attribute names are
* compliant with the Internet Printing Protocol (IPP) 1.1 where possible.
* Attribute values are partially compliant where possible.
* <p>
* To use a method which takes an inner class type, pass a reference to
* one of the constant fields of the inner class. Client code cannot create
* new instances of the inner class types because none of those classes
* has a public constructor. For example, to set the print dialog type to
* the cross-platform, pure Java print dialog, use the following code:
* <pre>
* import java.awt.JobAttributes;
*
* public class PureJavaPrintDialogExample {
* public void setPureJavaPrintDialog(JobAttributes jobAttributes) {
* jobAttributes.setDialog(JobAttributes.DialogType.COMMON);
* }
* }
* </pre>
* <p>
* Every IPP attribute which supports an <i>attributeName</i>-default value
* has a corresponding <code>set<i>attributeName</i>ToDefault</code> method.
* Default value fields are not provided.
*
* @author David Mendenhall
* @since 1.3
*/
public final class JobAttributes implements Cloneable {
/** {@collect.stats}
* A type-safe enumeration of possible default selection states.
* @since 1.3
*/
public static final class DefaultSelectionType extends AttributeValue {
private static final int I_ALL = 0;
private static final int I_RANGE = 1;
private static final int I_SELECTION = 2;
private static final String NAMES[] = {
"all", "range", "selection"
};
/** {@collect.stats}
* The <code>DefaultSelectionType</code> instance to use for
* specifying that all pages of the job should be printed.
*/
public static final DefaultSelectionType ALL =
new DefaultSelectionType(I_ALL);
/** {@collect.stats}
* The <code>DefaultSelectionType</code> instance to use for
* specifying that a range of pages of the job should be printed.
*/
public static final DefaultSelectionType RANGE =
new DefaultSelectionType(I_RANGE);
/** {@collect.stats}
* The <code>DefaultSelectionType</code> instance to use for
* specifying that the current selection should be printed.
*/
public static final DefaultSelectionType SELECTION =
new DefaultSelectionType(I_SELECTION);
private DefaultSelectionType(int type) {
super(type, NAMES);
}
}
/** {@collect.stats}
* A type-safe enumeration of possible job destinations.
* @since 1.3
*/
public static final class DestinationType extends AttributeValue {
private static final int I_FILE = 0;
private static final int I_PRINTER = 1;
private static final String NAMES[] = {
"file", "printer"
};
/** {@collect.stats}
* The <code>DestinationType</code> instance to use for
* specifying print to file.
*/
public static final DestinationType FILE =
new DestinationType(I_FILE);
/** {@collect.stats}
* The <code>DestinationType</code> instance to use for
* specifying print to printer.
*/
public static final DestinationType PRINTER =
new DestinationType(I_PRINTER);
private DestinationType(int type) {
super(type, NAMES);
}
}
/** {@collect.stats}
* A type-safe enumeration of possible dialogs to display to the user.
* @since 1.3
*/
public static final class DialogType extends AttributeValue {
private static final int I_COMMON = 0;
private static final int I_NATIVE = 1;
private static final int I_NONE = 2;
private static final String NAMES[] = {
"common", "native", "none"
};
/** {@collect.stats}
* The <code>DialogType</code> instance to use for
* specifying the cross-platform, pure Java print dialog.
*/
public static final DialogType COMMON = new DialogType(I_COMMON);
/** {@collect.stats}
* The <code>DialogType</code> instance to use for
* specifying the platform's native print dialog.
*/
public static final DialogType NATIVE = new DialogType(I_NATIVE);
/** {@collect.stats}
* The <code>DialogType</code> instance to use for
* specifying no print dialog.
*/
public static final DialogType NONE = new DialogType(I_NONE);
private DialogType(int type) {
super(type, NAMES);
}
}
/** {@collect.stats}
* A type-safe enumeration of possible multiple copy handling states.
* It is used to control how the sheets of multiple copies of a single
* document are collated.
* @since 1.3
*/
public static final class MultipleDocumentHandlingType extends
AttributeValue {
private static final int I_SEPARATE_DOCUMENTS_COLLATED_COPIES = 0;
private static final int I_SEPARATE_DOCUMENTS_UNCOLLATED_COPIES = 1;
private static final String NAMES[] = {
"separate-documents-collated-copies",
"separate-documents-uncollated-copies"
};
/** {@collect.stats}
* The <code>MultipleDocumentHandlingType</code> instance to use for specifying
* that the job should be divided into separate, collated copies.
*/
public static final MultipleDocumentHandlingType
SEPARATE_DOCUMENTS_COLLATED_COPIES =
new MultipleDocumentHandlingType(
I_SEPARATE_DOCUMENTS_COLLATED_COPIES);
/** {@collect.stats}
* The <code>MultipleDocumentHandlingType</code> instance to use for specifying
* that the job should be divided into separate, uncollated copies.
*/
public static final MultipleDocumentHandlingType
SEPARATE_DOCUMENTS_UNCOLLATED_COPIES =
new MultipleDocumentHandlingType(
I_SEPARATE_DOCUMENTS_UNCOLLATED_COPIES);
private MultipleDocumentHandlingType(int type) {
super(type, NAMES);
}
}
/** {@collect.stats}
* A type-safe enumeration of possible multi-page impositions. These
* impositions are in compliance with IPP 1.1.
* @since 1.3
*/
public static final class SidesType extends AttributeValue {
private static final int I_ONE_SIDED = 0;
private static final int I_TWO_SIDED_LONG_EDGE = 1;
private static final int I_TWO_SIDED_SHORT_EDGE = 2;
private static final String NAMES[] = {
"one-sided", "two-sided-long-edge", "two-sided-short-edge"
};
/** {@collect.stats}
* The <code>SidesType</code> instance to use for specifying that
* consecutive job pages should be printed upon the same side of
* consecutive media sheets.
*/
public static final SidesType ONE_SIDED = new SidesType(I_ONE_SIDED);
/** {@collect.stats}
* The <code>SidesType</code> instance to use for specifying that
* consecutive job pages should be printed upon front and back sides
* of consecutive media sheets, such that the orientation of each pair
* of pages on the medium would be correct for the reader as if for
* binding on the long edge.
*/
public static final SidesType TWO_SIDED_LONG_EDGE =
new SidesType(I_TWO_SIDED_LONG_EDGE);
/** {@collect.stats}
* The <code>SidesType</code> instance to use for specifying that
* consecutive job pages should be printed upon front and back sides
* of consecutive media sheets, such that the orientation of each pair
* of pages on the medium would be correct for the reader as if for
* binding on the short edge.
*/
public static final SidesType TWO_SIDED_SHORT_EDGE =
new SidesType(I_TWO_SIDED_SHORT_EDGE);
private SidesType(int type) {
super(type, NAMES);
}
}
private int copies;
private DefaultSelectionType defaultSelection;
private DestinationType destination;
private DialogType dialog;
private String fileName;
private int fromPage;
private int maxPage;
private int minPage;
private MultipleDocumentHandlingType multipleDocumentHandling;
private int[][] pageRanges;
private int prFirst;
private int prLast;
private String printer;
private SidesType sides;
private int toPage;
/** {@collect.stats}
* Constructs a <code>JobAttributes</code> instance with default
* values for every attribute. The dialog defaults to
* <code>DialogType.NATIVE</code>. Min page defaults to
* <code>1</code>. Max page defaults to <code>Integer.MAX_VALUE</code>.
* Destination defaults to <code>DestinationType.PRINTER</code>.
* Selection defaults to <code>DefaultSelectionType.ALL</code>.
* Number of copies defaults to <code>1</code>. Multiple document handling defaults
* to <code>MultipleDocumentHandlingType.SEPARATE_DOCUMENTS_UNCOLLATED_COPIES</code>.
* Sides defaults to <code>SidesType.ONE_SIDED</code>. File name defaults
* to <code>null</code>.
*/
public JobAttributes() {
setCopiesToDefault();
setDefaultSelection(DefaultSelectionType.ALL);
setDestination(DestinationType.PRINTER);
setDialog(DialogType.NATIVE);
setMaxPage(Integer.MAX_VALUE);
setMinPage(1);
setMultipleDocumentHandlingToDefault();
setSidesToDefault();
}
/** {@collect.stats}
* Constructs a <code>JobAttributes</code> instance which is a copy
* of the supplied <code>JobAttributes</code>.
*
* @param obj the <code>JobAttributes</code> to copy
*/
public JobAttributes(JobAttributes obj) {
set(obj);
}
/** {@collect.stats}
* Constructs a <code>JobAttributes</code> instance with the
* specified values for every attribute.
*
* @param copies an integer greater than 0
* @param defaultSelection <code>DefaultSelectionType.ALL</code>,
* <code>DefaultSelectionType.RANGE</code>, or
* <code>DefaultSelectionType.SELECTION</code>
* @param destination <code>DesintationType.FILE</code> or
* <code>DesintationType.PRINTER</code>
* @param dialog <code>DialogType.COMMON</code>,
* <code>DialogType.NATIVE</code>, or
* <code>DialogType.NONE</code>
* @param fileName the possibly <code>null</code> file name
* @param maxPage an integer greater than zero and greater than or equal
* to <i>minPage</i>
* @param minPage an integer greater than zero and less than or equal
* to <i>maxPage</i>
* @param multipleDocumentHandling
* <code>MultipleDocumentHandlingType.SEPARATE_DOCUMENTS_COLLATED_COPIES</code> or
* <code>MultipleDocumentHandlingType.SEPARATE_DOCUMENTS_UNCOLLATED_COPIES</code>
* @param pageRanges an array of integer arrays of two elements; an array
* is interpreted as a range spanning all pages including and
* between the specified pages; ranges must be in ascending
* order and must not overlap; specified page numbers cannot be
* less than <i>minPage</i> nor greater than <i>maxPage</i>;
* for example:
* <pre>
* (new int[][] { new int[] { 1, 3 }, new int[] { 5, 5 },
* new int[] { 15, 19 } }),
* </pre>
* specifies pages 1, 2, 3, 5, 15, 16, 17, 18, and 19. Note that
* (<code>new int[][] { new int[] { 1, 1 }, new int[] { 1, 2 } }</code>),
* is an invalid set of page ranges because the two ranges
* overlap
* @param printer the possibly <code>null</code> printer name
* @param sides <code>SidesType.ONE_SIDED</code>,
* <code>SidesType.TWO_SIDED_LONG_EDGE</code>, or
* <code>SidesType.TWO_SIDED_SHORT_EDGE</code>
* @throws IllegalArgumentException if one or more of the above
* conditions is violated
*/
public JobAttributes(int copies, DefaultSelectionType defaultSelection,
DestinationType destination, DialogType dialog,
String fileName, int maxPage, int minPage,
MultipleDocumentHandlingType multipleDocumentHandling,
int[][] pageRanges, String printer, SidesType sides) {
setCopies(copies);
setDefaultSelection(defaultSelection);
setDestination(destination);
setDialog(dialog);
setFileName(fileName);
setMaxPage(maxPage);
setMinPage(minPage);
setMultipleDocumentHandling(multipleDocumentHandling);
setPageRanges(pageRanges);
setPrinter(printer);
setSides(sides);
}
/** {@collect.stats}
* Creates and returns a copy of this <code>JobAttributes</code>.
*
* @return the newly created copy; it is safe to cast this Object into
* a <code>JobAttributes</code>
*/
public Object clone() {
try {
return super.clone();
} catch (CloneNotSupportedException e) {
// Since we implement Cloneable, this should never happen
throw new InternalError();
}
}
/** {@collect.stats}
* Sets all of the attributes of this <code>JobAttributes</code> to
* the same values as the attributes of obj.
*
* @param obj the <code>JobAttributes</code> to copy
*/
public void set(JobAttributes obj) {
copies = obj.copies;
defaultSelection = obj.defaultSelection;
destination = obj.destination;
dialog = obj.dialog;
fileName = obj.fileName;
fromPage = obj.fromPage;
maxPage = obj.maxPage;
minPage = obj.minPage;
multipleDocumentHandling = obj.multipleDocumentHandling;
// okay because we never modify the contents of pageRanges
pageRanges = obj.pageRanges;
prFirst = obj.prFirst;
prLast = obj.prLast;
printer = obj.printer;
sides = obj.sides;
toPage = obj.toPage;
}
/** {@collect.stats}
* Returns the number of copies the application should render for jobs
* using these attributes. This attribute is updated to the value chosen
* by the user.
*
* @return an integer greater than 0.
*/
public int getCopies() {
return copies;
}
/** {@collect.stats}
* Specifies the number of copies the application should render for jobs
* using these attributes. Not specifying this attribute is equivalent to
* specifying <code>1</code>.
*
* @param copies an integer greater than 0
* @throws IllegalArgumentException if <code>copies</code> is less than
* or equal to 0
*/
public void setCopies(int copies) {
if (copies <= 0) {
throw new IllegalArgumentException("Invalid value for attribute "+
"copies");
}
this.copies = copies;
}
/** {@collect.stats}
* Sets the number of copies the application should render for jobs using
* these attributes to the default. The default number of copies is 1.
*/
public void setCopiesToDefault() {
setCopies(1);
}
/** {@collect.stats}
* Specifies whether, for jobs using these attributes, the application
* should print all pages, the range specified by the return value of
* <code>getPageRanges</code>, or the current selection. This attribute
* is updated to the value chosen by the user.
*
* @return DefaultSelectionType.ALL, DefaultSelectionType.RANGE, or
* DefaultSelectionType.SELECTION
*/
public DefaultSelectionType getDefaultSelection() {
return defaultSelection;
}
/** {@collect.stats}
* Specifies whether, for jobs using these attributes, the application
* should print all pages, the range specified by the return value of
* <code>getPageRanges</code>, or the current selection. Not specifying
* this attribute is equivalent to specifying DefaultSelectionType.ALL.
*
* @param defaultSelection DefaultSelectionType.ALL,
* DefaultSelectionType.RANGE, or DefaultSelectionType.SELECTION.
* @throws IllegalArgumentException if defaultSelection is <code>null</code>
*/
public void setDefaultSelection(DefaultSelectionType defaultSelection) {
if (defaultSelection == null) {
throw new IllegalArgumentException("Invalid value for attribute "+
"defaultSelection");
}
this.defaultSelection = defaultSelection;
}
/** {@collect.stats}
* Specifies whether output will be to a printer or a file for jobs using
* these attributes. This attribute is updated to the value chosen by the
* user.
*
* @return DesintationType.FILE or DesintationType.PRINTER
*/
public DestinationType getDestination() {
return destination;
}
/** {@collect.stats}
* Specifies whether output will be to a printer or a file for jobs using
* these attributes. Not specifying this attribute is equivalent to
* specifying DesintationType.PRINTER.
*
* @param destination DesintationType.FILE or DesintationType.PRINTER.
* @throws IllegalArgumentException if destination is null.
*/
public void setDestination(DestinationType destination) {
if (destination == null) {
throw new IllegalArgumentException("Invalid value for attribute "+
"destination");
}
this.destination = destination;
}
/** {@collect.stats}
* Returns whether, for jobs using these attributes, the user should see
* a print dialog in which to modify the print settings, and which type of
* print dialog should be displayed. DialogType.COMMON denotes a cross-
* platform, pure Java print dialog. DialogType.NATIVE denotes the
* platform's native print dialog. If a platform does not support a native
* print dialog, the pure Java print dialog is displayed instead.
* DialogType.NONE specifies no print dialog (i.e., background printing).
* This attribute cannot be modified by, and is not subject to any
* limitations of, the implementation or the target printer.
*
* @return <code>DialogType.COMMON</code>, <code>DialogType.NATIVE</code>, or
* <code>DialogType.NONE</code>
*/
public DialogType getDialog() {
return dialog;
}
/** {@collect.stats}
* Specifies whether, for jobs using these attributes, the user should see
* a print dialog in which to modify the print settings, and which type of
* print dialog should be displayed. DialogType.COMMON denotes a cross-
* platform, pure Java print dialog. DialogType.NATIVE denotes the
* platform's native print dialog. If a platform does not support a native
* print dialog, the pure Java print dialog is displayed instead.
* DialogType.NONE specifies no print dialog (i.e., background printing).
* Not specifying this attribute is equivalent to specifying
* DialogType.NATIVE.
*
* @param dialog DialogType.COMMON, DialogType.NATIVE, or
* DialogType.NONE.
* @throws IllegalArgumentException if dialog is null.
*/
public void setDialog(DialogType dialog) {
if (dialog == null) {
throw new IllegalArgumentException("Invalid value for attribute "+
"dialog");
}
this.dialog = dialog;
}
/** {@collect.stats}
* Specifies the file name for the output file for jobs using these
* attributes. This attribute is updated to the value chosen by the user.
*
* @return the possibly <code>null</code> file name
*/
public String getFileName() {
return fileName;
}
/** {@collect.stats}
* Specifies the file name for the output file for jobs using these
* attributes. Default is platform-dependent and implementation-defined.
*
* @param fileName the possibly null file name.
*/
public void setFileName(String fileName) {
this.fileName = fileName;
}
/** {@collect.stats}
* Returns, for jobs using these attributes, the first page to be
* printed, if a range of pages is to be printed. This attribute is
* updated to the value chosen by the user. An application should ignore
* this attribute on output, unless the return value of the <code>
* getDefaultSelection</code> method is DefaultSelectionType.RANGE. An
* application should honor the return value of <code>getPageRanges</code>
* over the return value of this method, if possible.
*
* @return an integer greater than zero and less than or equal to
* <i>toPage</i> and greater than or equal to <i>minPage</i> and
* less than or equal to <i>maxPage</i>.
*/
public int getFromPage() {
if (fromPage != 0) {
return fromPage;
} else if (toPage != 0) {
return getMinPage();
} else if (pageRanges != null) {
return prFirst;
} else {
return getMinPage();
}
}
/** {@collect.stats}
* Specifies, for jobs using these attributes, the first page to be
* printed, if a range of pages is to be printed. If this attribute is not
* specified, then the values from the pageRanges attribute are used. If
* pageRanges and either or both of fromPage and toPage are specified,
* pageRanges takes precedence. Specifying none of pageRanges, fromPage,
* or toPage is equivalent to calling
* setPageRanges(new int[][] { new int[] { <i>minPage</i> } });
*
* @param fromPage an integer greater than zero and less than or equal to
* <i>toPage</i> and greater than or equal to <i>minPage</i> and
* less than or equal to <i>maxPage</i>.
* @throws IllegalArgumentException if one or more of the above
* conditions is violated.
*/
public void setFromPage(int fromPage) {
if (fromPage <= 0 ||
(toPage != 0 && fromPage > toPage) ||
fromPage < minPage ||
fromPage > maxPage) {
throw new IllegalArgumentException("Invalid value for attribute "+
"fromPage");
}
this.fromPage = fromPage;
}
/** {@collect.stats}
* Specifies the maximum value the user can specify as the last page to
* be printed for jobs using these attributes. This attribute cannot be
* modified by, and is not subject to any limitations of, the
* implementation or the target printer.
*
* @return an integer greater than zero and greater than or equal
* to <i>minPage</i>.
*/
public int getMaxPage() {
return maxPage;
}
/** {@collect.stats}
* Specifies the maximum value the user can specify as the last page to
* be printed for jobs using these attributes. Not specifying this
* attribute is equivalent to specifying <code>Integer.MAX_VALUE</code>.
*
* @param maxPage an integer greater than zero and greater than or equal
* to <i>minPage</i>
* @throws IllegalArgumentException if one or more of the above
* conditions is violated
*/
public void setMaxPage(int maxPage) {
if (maxPage <= 0 || maxPage < minPage) {
throw new IllegalArgumentException("Invalid value for attribute "+
"maxPage");
}
this.maxPage = maxPage;
}
/** {@collect.stats}
* Specifies the minimum value the user can specify as the first page to
* be printed for jobs using these attributes. This attribute cannot be
* modified by, and is not subject to any limitations of, the
* implementation or the target printer.
*
* @return an integer greater than zero and less than or equal
* to <i>maxPage</i>.
*/
public int getMinPage() {
return minPage;
}
/** {@collect.stats}
* Specifies the minimum value the user can specify as the first page to
* be printed for jobs using these attributes. Not specifying this
* attribute is equivalent to specifying <code>1</code>.
*
* @param minPage an integer greater than zero and less than or equal
* to <i>maxPage</i>.
* @throws IllegalArgumentException if one or more of the above
* conditions is violated.
*/
public void setMinPage(int minPage) {
if (minPage <= 0 || minPage > maxPage) {
throw new IllegalArgumentException("Invalid value for attribute "+
"minPage");
}
this.minPage = minPage;
}
/** {@collect.stats}
* Specifies the handling of multiple copies, including collation, for
* jobs using these attributes. This attribute is updated to the value
* chosen by the user.
*
* @return
* MultipleDocumentHandlingType.SEPARATE_DOCUMENTS_COLLATED_COPIES or
* MultipleDocumentHandlingType.SEPARATE_DOCUMENTS_UNCOLLATED_COPIES.
*/
public MultipleDocumentHandlingType getMultipleDocumentHandling() {
return multipleDocumentHandling;
}
/** {@collect.stats}
* Specifies the handling of multiple copies, including collation, for
* jobs using these attributes. Not specifying this attribute is equivalent
* to specifying
* MultipleDocumentHandlingType.SEPARATE_DOCUMENTS_UNCOLLATED_COPIES.
*
* @param multipleDocumentHandling
* MultipleDocumentHandlingType.SEPARATE_DOCUMENTS_COLLATED_COPIES or
* MultipleDocumentHandlingType.SEPARATE_DOCUMENTS_UNCOLLATED_COPIES.
* @throws IllegalArgumentException if multipleDocumentHandling is null.
*/
public void setMultipleDocumentHandling(MultipleDocumentHandlingType
multipleDocumentHandling) {
if (multipleDocumentHandling == null) {
throw new IllegalArgumentException("Invalid value for attribute "+
"multipleDocumentHandling");
}
this.multipleDocumentHandling = multipleDocumentHandling;
}
/** {@collect.stats}
* Sets the handling of multiple copies, including collation, for jobs
* using these attributes to the default. The default handling is
* MultipleDocumentHandlingType.SEPARATE_DOCUMENTS_UNCOLLATED_COPIES.
*/
public void setMultipleDocumentHandlingToDefault() {
setMultipleDocumentHandling(
MultipleDocumentHandlingType.SEPARATE_DOCUMENTS_UNCOLLATED_COPIES);
}
/** {@collect.stats}
* Specifies, for jobs using these attributes, the ranges of pages to be
* printed, if a range of pages is to be printed. All range numbers are
* inclusive. This attribute is updated to the value chosen by the user.
* An application should ignore this attribute on output, unless the
* return value of the <code>getDefaultSelection</code> method is
* DefaultSelectionType.RANGE.
*
* @return an array of integer arrays of 2 elements. An array
* is interpreted as a range spanning all pages including and
* between the specified pages. Ranges must be in ascending
* order and must not overlap. Specified page numbers cannot be
* less than <i>minPage</i> nor greater than <i>maxPage</i>.
* For example:
* (new int[][] { new int[] { 1, 3 }, new int[] { 5, 5 },
* new int[] { 15, 19 } }),
* specifies pages 1, 2, 3, 5, 15, 16, 17, 18, and 19.
*/
public int[][] getPageRanges() {
if (pageRanges != null) {
// Return a copy because otherwise client code could circumvent the
// the checks made in setPageRanges by modifying the returned
// array.
int[][] copy = new int[pageRanges.length][2];
for (int i = 0; i < pageRanges.length; i++) {
copy[i][0] = pageRanges[i][0];
copy[i][1] = pageRanges[i][1];
}
return copy;
} else if (fromPage != 0 || toPage != 0) {
int fromPage = getFromPage();
int toPage = getToPage();
return new int[][] { new int[] { fromPage, toPage } };
} else {
int minPage = getMinPage();
return new int[][] { new int[] { minPage, minPage } };
}
}
/** {@collect.stats}
* Specifies, for jobs using these attributes, the ranges of pages to be
* printed, if a range of pages is to be printed. All range numbers are
* inclusive. If this attribute is not specified, then the values from the
* fromPage and toPages attributes are used. If pageRanges and either or
* both of fromPage and toPage are specified, pageRanges takes precedence.
* Specifying none of pageRanges, fromPage, or toPage is equivalent to
* calling setPageRanges(new int[][] { new int[] { <i>minPage</i>,
* <i>minPage</i> } });
*
* @param pageRanges an array of integer arrays of 2 elements. An array
* is interpreted as a range spanning all pages including and
* between the specified pages. Ranges must be in ascending
* order and must not overlap. Specified page numbers cannot be
* less than <i>minPage</i> nor greater than <i>maxPage</i>.
* For example:
* (new int[][] { new int[] { 1, 3 }, new int[] { 5, 5 },
* new int[] { 15, 19 } }),
* specifies pages 1, 2, 3, 5, 15, 16, 17, 18, and 19. Note that
* (new int[][] { new int[] { 1, 1 }, new int[] { 1, 2 } }),
* is an invalid set of page ranges because the two ranges
* overlap.
* @throws IllegalArgumentException if one or more of the above
* conditions is violated.
*/
public void setPageRanges(int[][] pageRanges) {
String xcp = "Invalid value for attribute pageRanges";
int first = 0;
int last = 0;
if (pageRanges == null) {
throw new IllegalArgumentException(xcp);
}
for (int i = 0; i < pageRanges.length; i++) {
if (pageRanges[i] == null ||
pageRanges[i].length != 2 ||
pageRanges[i][0] <= last ||
pageRanges[i][1] < pageRanges[i][0]) {
throw new IllegalArgumentException(xcp);
}
last = pageRanges[i][1];
if (first == 0) {
first = pageRanges[i][0];
}
}
if (first < minPage || last > maxPage) {
throw new IllegalArgumentException(xcp);
}
// Store a copy because otherwise client code could circumvent the
// the checks made above by holding a reference to the array and
// modifying it after calling setPageRanges.
int[][] copy = new int[pageRanges.length][2];
for (int i = 0; i < pageRanges.length; i++) {
copy[i][0] = pageRanges[i][0];
copy[i][1] = pageRanges[i][1];
}
this.pageRanges = copy;
this.prFirst = first;
this.prLast = last;
}
/** {@collect.stats}
* Returns the destination printer for jobs using these attributes. This
* attribute is updated to the value chosen by the user.
*
* @return the possibly null printer name.
*/
public String getPrinter() {
return printer;
}
/** {@collect.stats}
* Specifies the destination printer for jobs using these attributes.
* Default is platform-dependent and implementation-defined.
*
* @param printer the possibly null printer name.
*/
public void setPrinter(String printer) {
this.printer = printer;
}
/** {@collect.stats}
* Returns how consecutive pages should be imposed upon the sides of the
* print medium for jobs using these attributes. SidesType.ONE_SIDED
* imposes each consecutive page upon the same side of consecutive media
* sheets. This imposition is sometimes called <i>simplex</i>.
* SidesType.TWO_SIDED_LONG_EDGE imposes each consecutive pair of pages
* upon front and back sides of consecutive media sheets, such that the
* orientation of each pair of pages on the medium would be correct for
* the reader as if for binding on the long edge. This imposition is
* sometimes called <i>duplex</i>. SidesType.TWO_SIDED_SHORT_EDGE imposes
* each consecutive pair of pages upon front and back sides of consecutive
* media sheets, such that the orientation of each pair of pages on the
* medium would be correct for the reader as if for binding on the short
* edge. This imposition is sometimes called <i>tumble</i>. This attribute
* is updated to the value chosen by the user.
*
* @return SidesType.ONE_SIDED, SidesType.TWO_SIDED_LONG_EDGE, or
* SidesType.TWO_SIDED_SHORT_EDGE.
*/
public SidesType getSides() {
return sides;
}
/** {@collect.stats}
* Specifies how consecutive pages should be imposed upon the sides of the
* print medium for jobs using these attributes. SidesType.ONE_SIDED
* imposes each consecutive page upon the same side of consecutive media
* sheets. This imposition is sometimes called <i>simplex</i>.
* SidesType.TWO_SIDED_LONG_EDGE imposes each consecutive pair of pages
* upon front and back sides of consecutive media sheets, such that the
* orientation of each pair of pages on the medium would be correct for
* the reader as if for binding on the long edge. This imposition is
* sometimes called <i>duplex</i>. SidesType.TWO_SIDED_SHORT_EDGE imposes
* each consecutive pair of pages upon front and back sides of consecutive
* media sheets, such that the orientation of each pair of pages on the
* medium would be correct for the reader as if for binding on the short
* edge. This imposition is sometimes called <i>tumble</i>. Not specifying
* this attribute is equivalent to specifying SidesType.ONE_SIDED.
*
* @param sides SidesType.ONE_SIDED, SidesType.TWO_SIDED_LONG_EDGE, or
* SidesType.TWO_SIDED_SHORT_EDGE.
* @throws IllegalArgumentException if sides is null.
*/
public void setSides(SidesType sides) {
if (sides == null) {
throw new IllegalArgumentException("Invalid value for attribute "+
"sides");
}
this.sides = sides;
}
/** {@collect.stats}
* Sets how consecutive pages should be imposed upon the sides of the
* print medium for jobs using these attributes to the default. The
* default imposition is SidesType.ONE_SIDED.
*/
public void setSidesToDefault() {
setSides(SidesType.ONE_SIDED);
}
/** {@collect.stats}
* Returns, for jobs using these attributes, the last page (inclusive)
* to be printed, if a range of pages is to be printed. This attribute is
* updated to the value chosen by the user. An application should ignore
* this attribute on output, unless the return value of the <code>
* getDefaultSelection</code> method is DefaultSelectionType.RANGE. An
* application should honor the return value of <code>getPageRanges</code>
* over the return value of this method, if possible.
*
* @return an integer greater than zero and greater than or equal
* to <i>toPage</i> and greater than or equal to <i>minPage</i>
* and less than or equal to <i>maxPage</i>.
*/
public int getToPage() {
if (toPage != 0) {
return toPage;
} else if (fromPage != 0) {
return fromPage;
} else if (pageRanges != null) {
return prLast;
} else {
return getMinPage();
}
}
/** {@collect.stats}
* Specifies, for jobs using these attributes, the last page (inclusive)
* to be printed, if a range of pages is to be printed.
* If this attribute is not specified, then the values from the pageRanges
* attribute are used. If pageRanges and either or both of fromPage and
* toPage are specified, pageRanges takes precedence. Specifying none of
* pageRanges, fromPage, or toPage is equivalent to calling
* setPageRanges(new int[][] { new int[] { <i>minPage</i> } });
*
* @param toPage an integer greater than zero and greater than or equal
* to <i>fromPage</i> and greater than or equal to <i>minPage</i>
* and less than or equal to <i>maxPage</i>.
* @throws IllegalArgumentException if one or more of the above
* conditions is violated.
*/
public void setToPage(int toPage) {
if (toPage <= 0 ||
(fromPage != 0 && toPage < fromPage) ||
toPage < minPage ||
toPage > maxPage) {
throw new IllegalArgumentException("Invalid value for attribute "+
"toPage");
}
this.toPage = toPage;
}
/** {@collect.stats}
* Determines whether two JobAttributes are equal to each other.
* <p>
* Two JobAttributes are equal if and only if each of their attributes are
* equal. Attributes of enumeration type are equal if and only if the
* fields refer to the same unique enumeration object. A set of page
* ranges is equal if and only if the sets are of equal length, each range
* enumerates the same pages, and the ranges are in the same order.
*
* @param obj the object whose equality will be checked.
* @return whether obj is equal to this JobAttribute according to the
* above criteria.
*/
public boolean equals(Object obj) {
if (!(obj instanceof JobAttributes)) {
return false;
}
JobAttributes rhs = (JobAttributes)obj;
if (fileName == null) {
if (rhs.fileName != null) {
return false;
}
} else {
if (!fileName.equals(rhs.fileName)) {
return false;
}
}
if (pageRanges == null) {
if (rhs.pageRanges != null) {
return false;
}
} else {
if (rhs.pageRanges == null ||
pageRanges.length != rhs.pageRanges.length) {
return false;
}
for (int i = 0; i < pageRanges.length; i++) {
if (pageRanges[i][0] != rhs.pageRanges[i][0] ||
pageRanges[i][1] != rhs.pageRanges[i][1]) {
return false;
}
}
}
if (printer == null) {
if (rhs.printer != null) {
return false;
}
} else {
if (!printer.equals(rhs.printer)) {
return false;
}
}
return (copies == rhs.copies &&
defaultSelection == rhs.defaultSelection &&
destination == rhs.destination &&
dialog == rhs.dialog &&
fromPage == rhs.fromPage &&
maxPage == rhs.maxPage &&
minPage == rhs.minPage &&
multipleDocumentHandling == rhs.multipleDocumentHandling &&
prFirst == rhs.prFirst &&
prLast == rhs.prLast &&
sides == rhs.sides &&
toPage == rhs.toPage);
}
/** {@collect.stats}
* Returns a hash code value for this JobAttributes.
*
* @return the hash code.
*/
public int hashCode() {
int rest = ((copies + fromPage + maxPage + minPage + prFirst + prLast +
toPage) * 31) << 21;
if (pageRanges != null) {
int sum = 0;
for (int i = 0; i < pageRanges.length; i++) {
sum += pageRanges[i][0] + pageRanges[i][1];
}
rest ^= (sum * 31) << 11;
}
if (fileName != null) {
rest ^= fileName.hashCode();
}
if (printer != null) {
rest ^= printer.hashCode();
}
return (defaultSelection.hashCode() << 6 ^
destination.hashCode() << 5 ^
dialog.hashCode() << 3 ^
multipleDocumentHandling.hashCode() << 2 ^
sides.hashCode() ^
rest);
}
/** {@collect.stats}
* Returns a string representation of this JobAttributes.
*
* @return the string representation.
*/
public String toString() {
int[][] pageRanges = getPageRanges();
String prStr = "[";
boolean first = true;
for (int i = 0; i < pageRanges.length; i++) {
if (first) {
first = false;
} else {
prStr += ",";
}
prStr += pageRanges[i][0] + ":" + pageRanges[i][1];
}
prStr += "]";
return "copies=" + getCopies() + ",defaultSelection=" +
getDefaultSelection() + ",destination=" + getDestination() +
",dialog=" + getDialog() + ",fileName=" + getFileName() +
",fromPage=" + getFromPage() + ",maxPage=" + getMaxPage() +
",minPage=" + getMinPage() + ",multiple-document-handling=" +
getMultipleDocumentHandling() + ",page-ranges=" + prStr +
",printer=" + getPrinter() + ",sides=" + getSides() + ",toPage=" +
getToPage();
}
}
|
Java
|
/*
* Copyright (c) 1995, 2004, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code 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
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package java.awt;
/** {@collect.stats}
* The <code>CheckboxGroup</code> class is used to group together
* a set of <code>Checkbox</code> buttons.
* <p>
* Exactly one check box button in a <code>CheckboxGroup</code> can
* be in the "on" state at any given time. Pushing any
* button sets its state to "on" and forces any other button that
* is in the "on" state into the "off" state.
* <p>
* The following code example produces a new check box group,
* with three check boxes:
* <p>
* <hr><blockquote><pre>
* setLayout(new GridLayout(3, 1));
* CheckboxGroup cbg = new CheckboxGroup();
* add(new Checkbox("one", cbg, true));
* add(new Checkbox("two", cbg, false));
* add(new Checkbox("three", cbg, false));
* </pre></blockquote><hr>
* <p>
* This image depicts the check box group created by this example:
* <p>
* <img src="doc-files/CheckboxGroup-1.gif"
* alt="Shows three checkboxes, arranged vertically, labeled one, two, and three. Checkbox one is in the on state."
* ALIGN=center HSPACE=10 VSPACE=7>
* <p>
* @author Sami Shaio
* @see java.awt.Checkbox
* @since JDK1.0
*/
public class CheckboxGroup implements java.io.Serializable {
/** {@collect.stats}
* The current choice.
* @serial
* @see #getCurrent()
* @see #setCurrent(Checkbox)
*/
Checkbox selectedCheckbox = null;
/*
* JDK 1.1 serialVersionUID
*/
private static final long serialVersionUID = 3729780091441768983L;
/** {@collect.stats}
* Creates a new instance of <code>CheckboxGroup</code>.
*/
public CheckboxGroup() {
}
/** {@collect.stats}
* Gets the current choice from this check box group.
* The current choice is the check box in this
* group that is currently in the "on" state,
* or <code>null</code> if all check boxes in the
* group are off.
* @return the check box that is currently in the
* "on" state, or <code>null</code>.
* @see java.awt.Checkbox
* @see java.awt.CheckboxGroup#setSelectedCheckbox
* @since JDK1.1
*/
public Checkbox getSelectedCheckbox() {
return getCurrent();
}
/** {@collect.stats}
* @deprecated As of JDK version 1.1,
* replaced by <code>getSelectedCheckbox()</code>.
*/
@Deprecated
public Checkbox getCurrent() {
return selectedCheckbox;
}
/** {@collect.stats}
* Sets the currently selected check box in this group
* to be the specified check box.
* This method sets the state of that check box to "on" and
* sets all other check boxes in the group to be off.
* <p>
* If the check box argument is <tt>null</tt>, all check boxes
* in this check box group are deselected. If the check box argument
* belongs to a different check box group, this method does
* nothing.
* @param box the <code>Checkbox</code> to set as the
* current selection.
* @see java.awt.Checkbox
* @see java.awt.CheckboxGroup#getSelectedCheckbox
* @since JDK1.1
*/
public void setSelectedCheckbox(Checkbox box) {
setCurrent(box);
}
/** {@collect.stats}
* @deprecated As of JDK version 1.1,
* replaced by <code>setSelectedCheckbox(Checkbox)</code>.
*/
@Deprecated
public synchronized void setCurrent(Checkbox box) {
if (box != null && box.group != this) {
return;
}
Checkbox oldChoice = this.selectedCheckbox;
this.selectedCheckbox = box;
if (oldChoice != null && oldChoice != box && oldChoice.group == this) {
oldChoice.setState(false);
}
if (box != null && oldChoice != box && !box.getState()) {
box.setStateInternal(true);
}
}
/** {@collect.stats}
* Returns a string representation of this check box group,
* including the value of its current selection.
* @return a string representation of this check box group.
*/
public String toString() {
return getClass().getName() + "[selectedCheckbox=" + selectedCheckbox + "]";
}
}
|
Java
|
/*
* Copyright (c) 2000, 2004, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code 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
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package java.awt;
import java.awt.peer.ComponentPeer;
/** {@collect.stats}
* A FocusTraversalPolicy that determines traversal order based on the order
* of child Components in a Container. From a particular focus cycle root, the
* policy makes a pre-order traversal of the Component hierarchy, and traverses
* a Container's children according to the ordering of the array returned by
* <code>Container.getComponents()</code>. Portions of the hierarchy that are
* not visible and displayable will not be searched.
* <p>
* If client code has explicitly set the focusability of a Component by either
* overriding <code>Component.isFocusTraversable()</code> or
* <code>Component.isFocusable()</code>, or by calling
* <code>Component.setFocusable()</code>, then a DefaultFocusTraversalPolicy
* behaves exactly like a ContainerOrderFocusTraversalPolicy. If, however, the
* Component is relying on default focusability, then a
* DefaultFocusTraversalPolicy will reject all Components with non-focusable
* peers. This is the default FocusTraversalPolicy for all AWT Containers.
* <p>
* The focusability of a peer is implementation-dependent. Sun recommends that
* all implementations for a particular native platform construct peers with
* the same focusability. The recommendations for Windows and Unix are that
* Canvases, Labels, Panels, Scrollbars, ScrollPanes, Windows, and lightweight
* Components have non-focusable peers, and all other Components have focusable
* peers. These recommendations are used in the Sun AWT implementations. Note
* that the focusability of a Component's peer is different from, and does not
* impact, the focusability of the Component itself.
* <p>
* Please see
* <a href="http://java.sun.com/docs/books/tutorial/uiswing/misc/focus.html">
* How to Use the Focus Subsystem</a>,
* a section in <em>The Java Tutorial</em>, and the
* <a href="../../java/awt/doc-files/FocusSpec.html">Focus Specification</a>
* for more information.
*
* @author David Mendenhall
*
* @see Container#getComponents
* @see Component#isFocusable
* @see Component#setFocusable
* @since 1.4
*/
public class DefaultFocusTraversalPolicy
extends ContainerOrderFocusTraversalPolicy
{
/*
* serialVersionUID
*/
private static final long serialVersionUID = 8876966522510157497L;
/** {@collect.stats}
* Determines whether a Component is an acceptable choice as the new
* focus owner. The Component must be visible, displayable, and enabled
* to be accepted. If client code has explicitly set the focusability
* of the Component by either overriding
* <code>Component.isFocusTraversable()</code> or
* <code>Component.isFocusable()</code>, or by calling
* <code>Component.setFocusable()</code>, then the Component will be
* accepted if and only if it is focusable. If, however, the Component is
* relying on default focusability, then all Canvases, Labels, Panels,
* Scrollbars, ScrollPanes, Windows, and lightweight Components will be
* rejected.
*
* @param aComponent the Component whose fitness as a focus owner is to
* be tested
* @return <code>true</code> if aComponent meets the above requirements;
* <code>false</code> otherwise
*/
protected boolean accept(Component aComponent) {
if (!(aComponent.isVisible() && aComponent.isDisplayable() &&
aComponent.isEnabled()))
{
return false;
}
// Verify that the Component is recursively enabled. Disabling a
// heavyweight Container disables its children, whereas disabling
// a lightweight Container does not.
if (!(aComponent instanceof Window)) {
for (Container enableTest = aComponent.getParent();
enableTest != null;
enableTest = enableTest.getParent())
{
if (!(enableTest.isEnabled() || enableTest.isLightweight())) {
return false;
}
if (enableTest instanceof Window) {
break;
}
}
}
boolean focusable = aComponent.isFocusable();
if (aComponent.isFocusTraversableOverridden()) {
return focusable;
}
ComponentPeer peer = aComponent.getPeer();
return (peer != null && peer.isFocusable());
}
}
|
Java
|
/*
* Copyright (c) 1995, 1997, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code 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
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package java.awt;
/** {@collect.stats}
* Thrown when a serious Abstract Window Toolkit error has occurred.
*
* @author Arthur van Hoff
*/
public class AWTError extends Error {
/*
* JDK 1.1 serialVersionUID
*/
private static final long serialVersionUID = -1819846354050686206L;
/** {@collect.stats}
* Constructs an instance of <code>AWTError</code> with the specified
* detail message.
* @param msg the detail message.
* @since JDK1.0
*/
public AWTError(String msg) {
super(msg);
}
}
|
Java
|
/*
* Copyright (c) 2003, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code 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
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package java.awt;
/** {@collect.stats}
* A class that describes the pointer position.
* It provides the <code>GraphicsDevice</code> where the
* pointer is and the <code>Point</code> that represents
* the coordinates of the pointer.
* <p>
* Instances of this class should be obtained via
* {@link MouseInfo#getPointerInfo}.
* The <code>PointerInfo</code> instance is not updated dynamically
* as the mouse moves. To get the updated location, you must call
* {@link MouseInfo#getPointerInfo} again.
*
* @see MouseInfo#getPointerInfo
* @author Roman Poborchiy
* @since 1.5
*/
public class PointerInfo {
private GraphicsDevice device;
private Point location;
/** {@collect.stats}
* Package-private constructor to prevent instantiation.
*/
PointerInfo(GraphicsDevice device, Point location) {
this.device = device;
this.location = location;
}
/** {@collect.stats}
* Returns the <code>GraphicsDevice</code> where the mouse pointer
* was at the moment this <code>PointerInfo</code> was created.
*
* @return <code>GraphicsDevice</code> corresponding to the pointer
* @since 1.5
*/
public GraphicsDevice getDevice() {
return device;
}
/** {@collect.stats}
* Returns the <code>Point</code> that represents the coordinates
* of the pointer on the screen. See {@link MouseInfo#getPointerInfo}
* for more information about coordinate calculation for multiscreen
* systems.
*
* @see MouseInfo
* @see MouseInfo#getPointerInfo
* @return coordinates of mouse pointer
* @since 1.5
*/
public Point getLocation() {
return location;
}
}
|
Java
|
/*
* Copyright (c) 2000, 2001, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code 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
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package java.awt;
import java.awt.event.KeyEvent;
/** {@collect.stats}
* A KeyEventDispatcher cooperates with the current KeyboardFocusManager in the
* targeting and dispatching of all KeyEvents. KeyEventDispatchers registered
* with the current KeyboardFocusManager will receive KeyEvents before they are
* dispatched to their targets, allowing each KeyEventDispatcher to retarget
* the event, consume it, dispatch the event itself, or make other changes.
* <p>
* Note that KeyboardFocusManager itself implements KeyEventDispatcher. By
* default, the current KeyboardFocusManager will be the sink for all KeyEvents
* not dispatched by the registered KeyEventDispatchers. The current
* KeyboardFocusManager cannot be completely deregistered as a
* KeyEventDispatcher. However, if a KeyEventDispatcher reports that it
* dispatched the KeyEvent, regardless of whether it actually did so, the
* KeyboardFocusManager will take no further action with regard to the
* KeyEvent. (While it is possible for client code to register the current
* KeyboardFocusManager as a KeyEventDispatcher one or more times, this is
* usually unnecessary and not recommended.)
*
* @author David Mendenhall
*
* @see KeyboardFocusManager#addKeyEventDispatcher
* @see KeyboardFocusManager#removeKeyEventDispatcher
* @since 1.4
*/
public interface KeyEventDispatcher {
/** {@collect.stats}
* This method is called by the current KeyboardFocusManager requesting
* that this KeyEventDispatcher dispatch the specified event on its behalf.
* This KeyEventDispatcher is free to retarget the event, consume it,
* dispatch it itself, or make other changes. This capability is typically
* used to deliver KeyEvents to Components other than the focus owner. This
* can be useful when navigating children of non-focusable Windows in an
* accessible environment, for example. Note that if a KeyEventDispatcher
* dispatches the KeyEvent itself, it must use <code>redispatchEvent</code>
* to prevent the current KeyboardFocusManager from recursively requesting
* that this KeyEventDispatcher dispatch the event again.
* <p>
* If an implementation of this method returns <code>false</code>, then
* the KeyEvent is passed to the next KeyEventDispatcher in the chain,
* ending with the current KeyboardFocusManager. If an implementation
* returns <code>true</code>, the KeyEvent is assumed to have been
* dispatched (although this need not be the case), and the current
* KeyboardFocusManager will take no further action with regard to the
* KeyEvent. In such a case,
* <code>KeyboardFocusManager.dispatchEvent</code> should return
* <code>true</code> as well. If an implementation consumes the KeyEvent,
* but returns <code>false</code>, the consumed event will still be passed
* to the next KeyEventDispatcher in the chain. It is important for
* developers to check whether the KeyEvent has been consumed before
* dispatching it to a target. By default, the current KeyboardFocusManager
* will not dispatch a consumed KeyEvent.
*
* @param e the KeyEvent to dispatch
* @return <code>true</code> if the KeyboardFocusManager should take no
* further action with regard to the KeyEvent; <code>false</code>
* otherwise
* @see KeyboardFocusManager#redispatchEvent
*/
boolean dispatchKeyEvent(KeyEvent e);
}
|
Java
|
/*
* Copyright (c) 1997, 2007, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code 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
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package java.awt;
import java.awt.image.Raster;
import java.awt.image.ColorModel;
/** {@collect.stats}
* The <code>PaintContext</code> interface defines the encapsulated
* and optimized environment to generate color patterns in device
* space for fill or stroke operations on a
* {@link Graphics2D}. The <code>PaintContext</code> provides
* the necessary colors for <code>Graphics2D</code> operations in the
* form of a {@link Raster} associated with a {@link ColorModel}.
* The <code>PaintContext</code> maintains state for a particular paint
* operation. In a multi-threaded environment, several
* contexts can exist simultaneously for a single {@link Paint} object.
* @see Paint
*/
public interface PaintContext {
/** {@collect.stats}
* Releases the resources allocated for the operation.
*/
public void dispose();
/** {@collect.stats}
* Returns the <code>ColorModel</code> of the output. Note that
* this <code>ColorModel</code> might be different from the hint
* specified in the
* {@link Paint#createContext(ColorModel, Rectangle, Rectangle2D,
AffineTransform, RenderingHints) createContext} method of
* <code>Paint</code>. Not all <code>PaintContext</code> objects are
* capable of generating color patterns in an arbitrary
* <code>ColorModel</code>.
* @return the <code>ColorModel</code> of the output.
*/
ColorModel getColorModel();
/** {@collect.stats}
* Returns a <code>Raster</code> containing the colors generated for
* the graphics operation.
* @param x the x coordinate of the area in device space
* for which colors are generated.
* @param y the y coordinate of the area in device space
* for which colors are generated.
* @param w the width of the area in device space
* @param h the height of the area in device space
* @return a <code>Raster</code> representing the specified
* rectangular area and containing the colors generated for
* the graphics operation.
*/
Raster getRaster(int x,
int y,
int w,
int h);
}
|
Java
|
/*
* Copyright (c) 1996, 2006, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code 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
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package java.awt;
import java.awt.geom.AffineTransform;
import java.awt.geom.PathIterator;
import java.awt.geom.Point2D;
import java.awt.geom.Rectangle2D;
/** {@collect.stats}
* The <code>Shape</code> interface provides definitions for objects
* that represent some form of geometric shape. The <code>Shape</code>
* is described by a {@link PathIterator} object, which can express the
* outline of the <code>Shape</code> as well as a rule for determining
* how the outline divides the 2D plane into interior and exterior
* points. Each <code>Shape</code> object provides callbacks to get the
* bounding box of the geometry, determine whether points or
* rectangles lie partly or entirely within the interior
* of the <code>Shape</code>, and retrieve a <code>PathIterator</code>
* object that describes the trajectory path of the <code>Shape</code>
* outline.
* <p>
* <b>Definition of insideness:</b>
* A point is considered to lie inside a
* <code>Shape</code> if and only if:
* <ul>
* <li> it lies completely
* inside the<code>Shape</code> boundary <i>or</i>
* <li>
* it lies exactly on the <code>Shape</code> boundary <i>and</i> the
* space immediately adjacent to the
* point in the increasing <code>X</code> direction is
* entirely inside the boundary <i>or</i>
* <li>
* it lies exactly on a horizontal boundary segment <b>and</b> the
* space immediately adjacent to the point in the
* increasing <code>Y</code> direction is inside the boundary.
* </ul>
* <p>The <code>contains</code> and <code>intersects</code> methods
* consider the interior of a <code>Shape</code> to be the area it
* encloses as if it were filled. This means that these methods
* consider
* unclosed shapes to be implicitly closed for the purpose of
* determining if a shape contains or intersects a rectangle or if a
* shape contains a point.
*
* @see java.awt.geom.PathIterator
* @see java.awt.geom.AffineTransform
* @see java.awt.geom.FlatteningPathIterator
* @see java.awt.geom.GeneralPath
*
* @author Jim Graham
* @since 1.2
*/
public interface Shape {
/** {@collect.stats}
* Returns an integer {@link Rectangle} that completely encloses the
* <code>Shape</code>. Note that there is no guarantee that the
* returned <code>Rectangle</code> is the smallest bounding box that
* encloses the <code>Shape</code>, only that the <code>Shape</code>
* lies entirely within the indicated <code>Rectangle</code>. The
* returned <code>Rectangle</code> might also fail to completely
* enclose the <code>Shape</code> if the <code>Shape</code> overflows
* the limited range of the integer data type. The
* <code>getBounds2D</code> method generally returns a
* tighter bounding box due to its greater flexibility in
* representation.
* @return an integer <code>Rectangle</code> that completely encloses
* the <code>Shape</code>.
* @see #getBounds2D
* @since 1.2
*/
public Rectangle getBounds();
/** {@collect.stats}
* Returns a high precision and more accurate bounding box of
* the <code>Shape</code> than the <code>getBounds</code> method.
* Note that there is no guarantee that the returned
* {@link Rectangle2D} is the smallest bounding box that encloses
* the <code>Shape</code>, only that the <code>Shape</code> lies
* entirely within the indicated <code>Rectangle2D</code>. The
* bounding box returned by this method is usually tighter than that
* returned by the <code>getBounds</code> method and never fails due
* to overflow problems since the return value can be an instance of
* the <code>Rectangle2D</code> that uses double precision values to
* store the dimensions.
* @return an instance of <code>Rectangle2D</code> that is a
* high-precision bounding box of the <code>Shape</code>.
* @see #getBounds
* @since 1.2
*/
public Rectangle2D getBounds2D();
/** {@collect.stats}
* Tests if the specified coordinates are inside the boundary of the
* <code>Shape</code>.
* @param x the specified X coordinate to be tested
* @param y the specified Y coordinate to be tested
* @return <code>true</code> if the specified coordinates are inside
* the <code>Shape</code> boundary; <code>false</code>
* otherwise.
* @since 1.2
*/
public boolean contains(double x, double y);
/** {@collect.stats}
* Tests if a specified {@link Point2D} is inside the boundary
* of the <code>Shape</code>.
* @param p the specified <code>Point2D</code> to be tested
* @return <code>true</code> if the specified <code>Point2D</code> is
* inside the boundary of the <code>Shape</code>;
* <code>false</code> otherwise.
* @since 1.2
*/
public boolean contains(Point2D p);
/** {@collect.stats}
* Tests if the interior of the <code>Shape</code> intersects the
* interior of a specified rectangular area.
* The rectangular area is considered to intersect the <code>Shape</code>
* if any point is contained in both the interior of the
* <code>Shape</code> and the specified rectangular area.
* <p>
* The {@code Shape.intersects()} method allows a {@code Shape}
* implementation to conservatively return {@code true} when:
* <ul>
* <li>
* there is a high probability that the rectangular area and the
* <code>Shape</code> intersect, but
* <li>
* the calculations to accurately determine this intersection
* are prohibitively expensive.
* </ul>
* This means that for some {@code Shapes} this method might
* return {@code true} even though the rectangular area does not
* intersect the {@code Shape}.
* The {@link java.awt.geom.Area Area} class performs
* more accurate computations of geometric intersection than most
* {@code Shape} objects and therefore can be used if a more precise
* answer is required.
*
* @param x the X coordinate of the upper-left corner
* of the specified rectangular area
* @param y the Y coordinate of the upper-left corner
* of the specified rectangular area
* @param w the width of the specified rectangular area
* @param h the height of the specified rectangular area
* @return <code>true</code> if the interior of the <code>Shape</code> and
* the interior of the rectangular area intersect, or are
* both highly likely to intersect and intersection calculations
* would be too expensive to perform; <code>false</code> otherwise.
* @see java.awt.geom.Area
* @since 1.2
*/
public boolean intersects(double x, double y, double w, double h);
/** {@collect.stats}
* Tests if the interior of the <code>Shape</code> intersects the
* interior of a specified <code>Rectangle2D</code>.
* The {@code Shape.intersects()} method allows a {@code Shape}
* implementation to conservatively return {@code true} when:
* <ul>
* <li>
* there is a high probability that the <code>Rectangle2D</code> and the
* <code>Shape</code> intersect, but
* <li>
* the calculations to accurately determine this intersection
* are prohibitively expensive.
* </ul>
* This means that for some {@code Shapes} this method might
* return {@code true} even though the {@code Rectangle2D} does not
* intersect the {@code Shape}.
* The {@link java.awt.geom.Area Area} class performs
* more accurate computations of geometric intersection than most
* {@code Shape} objects and therefore can be used if a more precise
* answer is required.
*
* @param r the specified <code>Rectangle2D</code>
* @return <code>true</code> if the interior of the <code>Shape</code> and
* the interior of the specified <code>Rectangle2D</code>
* intersect, or are both highly likely to intersect and intersection
* calculations would be too expensive to perform; <code>false</code>
* otherwise.
* @see #intersects(double, double, double, double)
* @since 1.2
*/
public boolean intersects(Rectangle2D r);
/** {@collect.stats}
* Tests if the interior of the <code>Shape</code> entirely contains
* the specified rectangular area. All coordinates that lie inside
* the rectangular area must lie within the <code>Shape</code> for the
* entire rectanglar area to be considered contained within the
* <code>Shape</code>.
* <p>
* The {@code Shape.contains()} method allows a {@code Shape}
* implementation to conservatively return {@code false} when:
* <ul>
* <li>
* the <code>intersect</code> method returns <code>true</code> and
* <li>
* the calculations to determine whether or not the
* <code>Shape</code> entirely contains the rectangular area are
* prohibitively expensive.
* </ul>
* This means that for some {@code Shapes} this method might
* return {@code false} even though the {@code Shape} contains
* the rectangular area.
* The {@link java.awt.geom.Area Area} class performs
* more accurate geometric computations than most
* {@code Shape} objects and therefore can be used if a more precise
* answer is required.
*
* @param x the X coordinate of the upper-left corner
* of the specified rectangular area
* @param y the Y coordinate of the upper-left corner
* of the specified rectangular area
* @param w the width of the specified rectangular area
* @param h the height of the specified rectangular area
* @return <code>true</code> if the interior of the <code>Shape</code>
* entirely contains the specified rectangular area;
* <code>false</code> otherwise or, if the <code>Shape</code>
* contains the rectangular area and the
* <code>intersects</code> method returns <code>true</code>
* and the containment calculations would be too expensive to
* perform.
* @see java.awt.geom.Area
* @see #intersects
* @since 1.2
*/
public boolean contains(double x, double y, double w, double h);
/** {@collect.stats}
* Tests if the interior of the <code>Shape</code> entirely contains the
* specified <code>Rectangle2D</code>.
* The {@code Shape.contains()} method allows a {@code Shape}
* implementation to conservatively return {@code false} when:
* <ul>
* <li>
* the <code>intersect</code> method returns <code>true</code> and
* <li>
* the calculations to determine whether or not the
* <code>Shape</code> entirely contains the <code>Rectangle2D</code>
* are prohibitively expensive.
* </ul>
* This means that for some {@code Shapes} this method might
* return {@code false} even though the {@code Shape} contains
* the {@code Rectangle2D}.
* The {@link java.awt.geom.Area Area} class performs
* more accurate geometric computations than most
* {@code Shape} objects and therefore can be used if a more precise
* answer is required.
*
* @param r The specified <code>Rectangle2D</code>
* @return <code>true</code> if the interior of the <code>Shape</code>
* entirely contains the <code>Rectangle2D</code>;
* <code>false</code> otherwise or, if the <code>Shape</code>
* contains the <code>Rectangle2D</code> and the
* <code>intersects</code> method returns <code>true</code>
* and the containment calculations would be too expensive to
* perform.
* @see #contains(double, double, double, double)
* @since 1.2
*/
public boolean contains(Rectangle2D r);
/** {@collect.stats}
* Returns an iterator object that iterates along the
* <code>Shape</code> boundary and provides access to the geometry of the
* <code>Shape</code> outline. If an optional {@link AffineTransform}
* is specified, the coordinates returned in the iteration are
* transformed accordingly.
* <p>
* Each call to this method returns a fresh <code>PathIterator</code>
* object that traverses the geometry of the <code>Shape</code> object
* independently from any other <code>PathIterator</code> objects in use
* at the same time.
* <p>
* It is recommended, but not guaranteed, that objects
* implementing the <code>Shape</code> interface isolate iterations
* that are in process from any changes that might occur to the original
* object's geometry during such iterations.
*
* @param at an optional <code>AffineTransform</code> to be applied to the
* coordinates as they are returned in the iteration, or
* <code>null</code> if untransformed coordinates are desired
* @return a new <code>PathIterator</code> object, which independently
* traverses the geometry of the <code>Shape</code>.
* @since 1.2
*/
public PathIterator getPathIterator(AffineTransform at);
/** {@collect.stats}
* Returns an iterator object that iterates along the <code>Shape</code>
* boundary and provides access to a flattened view of the
* <code>Shape</code> outline geometry.
* <p>
* Only SEG_MOVETO, SEG_LINETO, and SEG_CLOSE point types are
* returned by the iterator.
* <p>
* If an optional <code>AffineTransform</code> is specified,
* the coordinates returned in the iteration are transformed
* accordingly.
* <p>
* The amount of subdivision of the curved segments is controlled
* by the <code>flatness</code> parameter, which specifies the
* maximum distance that any point on the unflattened transformed
* curve can deviate from the returned flattened path segments.
* Note that a limit on the accuracy of the flattened path might be
* silently imposed, causing very small flattening parameters to be
* treated as larger values. This limit, if there is one, is
* defined by the particular implementation that is used.
* <p>
* Each call to this method returns a fresh <code>PathIterator</code>
* object that traverses the <code>Shape</code> object geometry
* independently from any other <code>PathIterator</code> objects in use at
* the same time.
* <p>
* It is recommended, but not guaranteed, that objects
* implementing the <code>Shape</code> interface isolate iterations
* that are in process from any changes that might occur to the original
* object's geometry during such iterations.
*
* @param at an optional <code>AffineTransform</code> to be applied to the
* coordinates as they are returned in the iteration, or
* <code>null</code> if untransformed coordinates are desired
* @param flatness the maximum distance that the line segments used to
* approximate the curved segments are allowed to deviate
* from any point on the original curve
* @return a new <code>PathIterator</code> that independently traverses
* a flattened view of the geometry of the <code>Shape</code>.
* @since 1.2
*/
public PathIterator getPathIterator(AffineTransform at, double flatness);
}
|
Java
|
/*
* Copyright (c) 1999, 2006, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code 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
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package java.awt;
import java.util.Locale;
/** {@collect.stats}
* A set of attributes which control the output of a printed page.
* <p>
* Instances of this class control the color state, paper size (media type),
* orientation, logical origin, print quality, and resolution of every
* page which uses the instance. Attribute names are compliant with the
* Internet Printing Protocol (IPP) 1.1 where possible. Attribute values
* are partially compliant where possible.
* <p>
* To use a method which takes an inner class type, pass a reference to
* one of the constant fields of the inner class. Client code cannot create
* new instances of the inner class types because none of those classes
* has a public constructor. For example, to set the color state to
* monochrome, use the following code:
* <pre>
* import java.awt.PageAttributes;
*
* public class MonochromeExample {
* public void setMonochrome(PageAttributes pageAttributes) {
* pageAttributes.setColor(PageAttributes.ColorType.MONOCHROME);
* }
* }
* </pre>
* <p>
* Every IPP attribute which supports an <i>attributeName</i>-default value
* has a corresponding <code>set<i>attributeName</i>ToDefault</code> method.
* Default value fields are not provided.
*
* @author David Mendenhall
* @since 1.3
*/
public final class PageAttributes implements Cloneable {
/** {@collect.stats}
* A type-safe enumeration of possible color states.
* @since 1.3
*/
public static final class ColorType extends AttributeValue {
private static final int I_COLOR = 0;
private static final int I_MONOCHROME = 1;
private static final String NAMES[] = {
"color", "monochrome"
};
/** {@collect.stats}
* The ColorType instance to use for specifying color printing.
*/
public static final ColorType COLOR = new ColorType(I_COLOR);
/** {@collect.stats}
* The ColorType instance to use for specifying monochrome printing.
*/
public static final ColorType MONOCHROME = new ColorType(I_MONOCHROME);
private ColorType(int type) {
super(type, NAMES);
}
}
/** {@collect.stats}
* A type-safe enumeration of possible paper sizes. These sizes are in
* compliance with IPP 1.1.
* @since 1.3
*/
public static final class MediaType extends AttributeValue {
private static final int I_ISO_4A0 = 0;
private static final int I_ISO_2A0 = 1;
private static final int I_ISO_A0 = 2;
private static final int I_ISO_A1 = 3;
private static final int I_ISO_A2 = 4;
private static final int I_ISO_A3 = 5;
private static final int I_ISO_A4 = 6;
private static final int I_ISO_A5 = 7;
private static final int I_ISO_A6 = 8;
private static final int I_ISO_A7 = 9;
private static final int I_ISO_A8 = 10;
private static final int I_ISO_A9 = 11;
private static final int I_ISO_A10 = 12;
private static final int I_ISO_B0 = 13;
private static final int I_ISO_B1 = 14;
private static final int I_ISO_B2 = 15;
private static final int I_ISO_B3 = 16;
private static final int I_ISO_B4 = 17;
private static final int I_ISO_B5 = 18;
private static final int I_ISO_B6 = 19;
private static final int I_ISO_B7 = 20;
private static final int I_ISO_B8 = 21;
private static final int I_ISO_B9 = 22;
private static final int I_ISO_B10 = 23;
private static final int I_JIS_B0 = 24;
private static final int I_JIS_B1 = 25;
private static final int I_JIS_B2 = 26;
private static final int I_JIS_B3 = 27;
private static final int I_JIS_B4 = 28;
private static final int I_JIS_B5 = 29;
private static final int I_JIS_B6 = 30;
private static final int I_JIS_B7 = 31;
private static final int I_JIS_B8 = 32;
private static final int I_JIS_B9 = 33;
private static final int I_JIS_B10 = 34;
private static final int I_ISO_C0 = 35;
private static final int I_ISO_C1 = 36;
private static final int I_ISO_C2 = 37;
private static final int I_ISO_C3 = 38;
private static final int I_ISO_C4 = 39;
private static final int I_ISO_C5 = 40;
private static final int I_ISO_C6 = 41;
private static final int I_ISO_C7 = 42;
private static final int I_ISO_C8 = 43;
private static final int I_ISO_C9 = 44;
private static final int I_ISO_C10 = 45;
private static final int I_ISO_DESIGNATED_LONG = 46;
private static final int I_EXECUTIVE = 47;
private static final int I_FOLIO = 48;
private static final int I_INVOICE = 49;
private static final int I_LEDGER = 50;
private static final int I_NA_LETTER = 51;
private static final int I_NA_LEGAL = 52;
private static final int I_QUARTO = 53;
private static final int I_A = 54;
private static final int I_B = 55;
private static final int I_C = 56;
private static final int I_D = 57;
private static final int I_E = 58;
private static final int I_NA_10X15_ENVELOPE = 59;
private static final int I_NA_10X14_ENVELOPE = 60;
private static final int I_NA_10X13_ENVELOPE = 61;
private static final int I_NA_9X12_ENVELOPE = 62;
private static final int I_NA_9X11_ENVELOPE = 63;
private static final int I_NA_7X9_ENVELOPE = 64;
private static final int I_NA_6X9_ENVELOPE = 65;
private static final int I_NA_NUMBER_9_ENVELOPE = 66;
private static final int I_NA_NUMBER_10_ENVELOPE = 67;
private static final int I_NA_NUMBER_11_ENVELOPE = 68;
private static final int I_NA_NUMBER_12_ENVELOPE = 69;
private static final int I_NA_NUMBER_14_ENVELOPE = 70;
private static final int I_INVITE_ENVELOPE = 71;
private static final int I_ITALY_ENVELOPE = 72;
private static final int I_MONARCH_ENVELOPE = 73;
private static final int I_PERSONAL_ENVELOPE = 74;
private static final String NAMES[] = {
"iso-4a0", "iso-2a0", "iso-a0", "iso-a1", "iso-a2", "iso-a3",
"iso-a4", "iso-a5", "iso-a6", "iso-a7", "iso-a8", "iso-a9",
"iso-a10", "iso-b0", "iso-b1", "iso-b2", "iso-b3", "iso-b4",
"iso-b5", "iso-b6", "iso-b7", "iso-b8", "iso-b9", "iso-b10",
"jis-b0", "jis-b1", "jis-b2", "jis-b3", "jis-b4", "jis-b5",
"jis-b6", "jis-b7", "jis-b8", "jis-b9", "jis-b10", "iso-c0",
"iso-c1", "iso-c2", "iso-c3", "iso-c4", "iso-c5", "iso-c6",
"iso-c7", "iso-c8", "iso-c9", "iso-c10", "iso-designated-long",
"executive", "folio", "invoice", "ledger", "na-letter", "na-legal",
"quarto", "a", "b", "c", "d", "e", "na-10x15-envelope",
"na-10x14-envelope", "na-10x13-envelope", "na-9x12-envelope",
"na-9x11-envelope", "na-7x9-envelope", "na-6x9-envelope",
"na-number-9-envelope", "na-number-10-envelope",
"na-number-11-envelope", "na-number-12-envelope",
"na-number-14-envelope", "invite-envelope", "italy-envelope",
"monarch-envelope", "personal-envelope"
};
/** {@collect.stats}
* The MediaType instance for ISO/DIN & JIS 4A0, 1682 x 2378 mm.
*/
public static final MediaType ISO_4A0 = new MediaType(I_ISO_4A0);
/** {@collect.stats}
* The MediaType instance for ISO/DIN & JIS 2A0, 1189 x 1682 mm.
*/
public static final MediaType ISO_2A0 = new MediaType(I_ISO_2A0);
/** {@collect.stats}
* The MediaType instance for ISO/DIN & JIS A0, 841 x 1189 mm.
*/
public static final MediaType ISO_A0 = new MediaType(I_ISO_A0);
/** {@collect.stats}
* The MediaType instance for ISO/DIN & JIS A1, 594 x 841 mm.
*/
public static final MediaType ISO_A1 = new MediaType(I_ISO_A1);
/** {@collect.stats}
* The MediaType instance for ISO/DIN & JIS A2, 420 x 594 mm.
*/
public static final MediaType ISO_A2 = new MediaType(I_ISO_A2);
/** {@collect.stats}
* The MediaType instance for ISO/DIN & JIS A3, 297 x 420 mm.
*/
public static final MediaType ISO_A3 = new MediaType(I_ISO_A3);
/** {@collect.stats}
* The MediaType instance for ISO/DIN & JIS A4, 210 x 297 mm.
*/
public static final MediaType ISO_A4 = new MediaType(I_ISO_A4);
/** {@collect.stats}
* The MediaType instance for ISO/DIN & JIS A5, 148 x 210 mm.
*/
public static final MediaType ISO_A5 = new MediaType(I_ISO_A5);
/** {@collect.stats}
* The MediaType instance for ISO/DIN & JIS A6, 105 x 148 mm.
*/
public static final MediaType ISO_A6 = new MediaType(I_ISO_A6);
/** {@collect.stats}
* The MediaType instance for ISO/DIN & JIS A7, 74 x 105 mm.
*/
public static final MediaType ISO_A7 = new MediaType(I_ISO_A7);
/** {@collect.stats}
* The MediaType instance for ISO/DIN & JIS A8, 52 x 74 mm.
*/
public static final MediaType ISO_A8 = new MediaType(I_ISO_A8);
/** {@collect.stats}
* The MediaType instance for ISO/DIN & JIS A9, 37 x 52 mm.
*/
public static final MediaType ISO_A9 = new MediaType(I_ISO_A9);
/** {@collect.stats}
* The MediaType instance for ISO/DIN & JIS A10, 26 x 37 mm.
*/
public static final MediaType ISO_A10 = new MediaType(I_ISO_A10);
/** {@collect.stats}
* The MediaType instance for ISO/DIN B0, 1000 x 1414 mm.
*/
public static final MediaType ISO_B0 = new MediaType(I_ISO_B0);
/** {@collect.stats}
* The MediaType instance for ISO/DIN B1, 707 x 1000 mm.
*/
public static final MediaType ISO_B1 = new MediaType(I_ISO_B1);
/** {@collect.stats}
* The MediaType instance for ISO/DIN B2, 500 x 707 mm.
*/
public static final MediaType ISO_B2 = new MediaType(I_ISO_B2);
/** {@collect.stats}
* The MediaType instance for ISO/DIN B3, 353 x 500 mm.
*/
public static final MediaType ISO_B3 = new MediaType(I_ISO_B3);
/** {@collect.stats}
* The MediaType instance for ISO/DIN B4, 250 x 353 mm.
*/
public static final MediaType ISO_B4 = new MediaType(I_ISO_B4);
/** {@collect.stats}
* The MediaType instance for ISO/DIN B5, 176 x 250 mm.
*/
public static final MediaType ISO_B5 = new MediaType(I_ISO_B5);
/** {@collect.stats}
* The MediaType instance for ISO/DIN B6, 125 x 176 mm.
*/
public static final MediaType ISO_B6 = new MediaType(I_ISO_B6);
/** {@collect.stats}
* The MediaType instance for ISO/DIN B7, 88 x 125 mm.
*/
public static final MediaType ISO_B7 = new MediaType(I_ISO_B7);
/** {@collect.stats}
* The MediaType instance for ISO/DIN B8, 62 x 88 mm.
*/
public static final MediaType ISO_B8 = new MediaType(I_ISO_B8);
/** {@collect.stats}
* The MediaType instance for ISO/DIN B9, 44 x 62 mm.
*/
public static final MediaType ISO_B9 = new MediaType(I_ISO_B9);
/** {@collect.stats}
* The MediaType instance for ISO/DIN B10, 31 x 44 mm.
*/
public static final MediaType ISO_B10 = new MediaType(I_ISO_B10);
/** {@collect.stats}
* The MediaType instance for JIS B0, 1030 x 1456 mm.
*/
public static final MediaType JIS_B0 = new MediaType(I_JIS_B0);
/** {@collect.stats}
* The MediaType instance for JIS B1, 728 x 1030 mm.
*/
public static final MediaType JIS_B1 = new MediaType(I_JIS_B1);
/** {@collect.stats}
* The MediaType instance for JIS B2, 515 x 728 mm.
*/
public static final MediaType JIS_B2 = new MediaType(I_JIS_B2);
/** {@collect.stats}
* The MediaType instance for JIS B3, 364 x 515 mm.
*/
public static final MediaType JIS_B3 = new MediaType(I_JIS_B3);
/** {@collect.stats}
* The MediaType instance for JIS B4, 257 x 364 mm.
*/
public static final MediaType JIS_B4 = new MediaType(I_JIS_B4);
/** {@collect.stats}
* The MediaType instance for JIS B5, 182 x 257 mm.
*/
public static final MediaType JIS_B5 = new MediaType(I_JIS_B5);
/** {@collect.stats}
* The MediaType instance for JIS B6, 128 x 182 mm.
*/
public static final MediaType JIS_B6 = new MediaType(I_JIS_B6);
/** {@collect.stats}
* The MediaType instance for JIS B7, 91 x 128 mm.
*/
public static final MediaType JIS_B7 = new MediaType(I_JIS_B7);
/** {@collect.stats}
* The MediaType instance for JIS B8, 64 x 91 mm.
*/
public static final MediaType JIS_B8 = new MediaType(I_JIS_B8);
/** {@collect.stats}
* The MediaType instance for JIS B9, 45 x 64 mm.
*/
public static final MediaType JIS_B9 = new MediaType(I_JIS_B9);
/** {@collect.stats}
* The MediaType instance for JIS B10, 32 x 45 mm.
*/
public static final MediaType JIS_B10 = new MediaType(I_JIS_B10);
/** {@collect.stats}
* The MediaType instance for ISO/DIN C0, 917 x 1297 mm.
*/
public static final MediaType ISO_C0 = new MediaType(I_ISO_C0);
/** {@collect.stats}
* The MediaType instance for ISO/DIN C1, 648 x 917 mm.
*/
public static final MediaType ISO_C1 = new MediaType(I_ISO_C1);
/** {@collect.stats}
* The MediaType instance for ISO/DIN C2, 458 x 648 mm.
*/
public static final MediaType ISO_C2 = new MediaType(I_ISO_C2);
/** {@collect.stats}
* The MediaType instance for ISO/DIN C3, 324 x 458 mm.
*/
public static final MediaType ISO_C3 = new MediaType(I_ISO_C3);
/** {@collect.stats}
* The MediaType instance for ISO/DIN C4, 229 x 324 mm.
*/
public static final MediaType ISO_C4 = new MediaType(I_ISO_C4);
/** {@collect.stats}
* The MediaType instance for ISO/DIN C5, 162 x 229 mm.
*/
public static final MediaType ISO_C5 = new MediaType(I_ISO_C5);
/** {@collect.stats}
* The MediaType instance for ISO/DIN C6, 114 x 162 mm.
*/
public static final MediaType ISO_C6 = new MediaType(I_ISO_C6);
/** {@collect.stats}
* The MediaType instance for ISO/DIN C7, 81 x 114 mm.
*/
public static final MediaType ISO_C7 = new MediaType(I_ISO_C7);
/** {@collect.stats}
* The MediaType instance for ISO/DIN C8, 57 x 81 mm.
*/
public static final MediaType ISO_C8 = new MediaType(I_ISO_C8);
/** {@collect.stats}
* The MediaType instance for ISO/DIN C9, 40 x 57 mm.
*/
public static final MediaType ISO_C9 = new MediaType(I_ISO_C9);
/** {@collect.stats}
* The MediaType instance for ISO/DIN C10, 28 x 40 mm.
*/
public static final MediaType ISO_C10 = new MediaType(I_ISO_C10);
/** {@collect.stats}
* The MediaType instance for ISO Designated Long, 110 x 220 mm.
*/
public static final MediaType ISO_DESIGNATED_LONG =
new MediaType(I_ISO_DESIGNATED_LONG);
/** {@collect.stats}
* The MediaType instance for Executive, 7 1/4 x 10 1/2 in.
*/
public static final MediaType EXECUTIVE = new MediaType(I_EXECUTIVE);
/** {@collect.stats}
* The MediaType instance for Folio, 8 1/2 x 13 in.
*/
public static final MediaType FOLIO = new MediaType(I_FOLIO);
/** {@collect.stats}
* The MediaType instance for Invoice, 5 1/2 x 8 1/2 in.
*/
public static final MediaType INVOICE = new MediaType(I_INVOICE);
/** {@collect.stats}
* The MediaType instance for Ledger, 11 x 17 in.
*/
public static final MediaType LEDGER = new MediaType(I_LEDGER);
/** {@collect.stats}
* The MediaType instance for North American Letter, 8 1/2 x 11 in.
*/
public static final MediaType NA_LETTER = new MediaType(I_NA_LETTER);
/** {@collect.stats}
* The MediaType instance for North American Legal, 8 1/2 x 14 in.
*/
public static final MediaType NA_LEGAL = new MediaType(I_NA_LEGAL);
/** {@collect.stats}
* The MediaType instance for Quarto, 215 x 275 mm.
*/
public static final MediaType QUARTO = new MediaType(I_QUARTO);
/** {@collect.stats}
* The MediaType instance for Engineering A, 8 1/2 x 11 in.
*/
public static final MediaType A = new MediaType(I_A);
/** {@collect.stats}
* The MediaType instance for Engineering B, 11 x 17 in.
*/
public static final MediaType B = new MediaType(I_B);
/** {@collect.stats}
* The MediaType instance for Engineering C, 17 x 22 in.
*/
public static final MediaType C = new MediaType(I_C);
/** {@collect.stats}
* The MediaType instance for Engineering D, 22 x 34 in.
*/
public static final MediaType D = new MediaType(I_D);
/** {@collect.stats}
* The MediaType instance for Engineering E, 34 x 44 in.
*/
public static final MediaType E = new MediaType(I_E);
/** {@collect.stats}
* The MediaType instance for North American 10 x 15 in.
*/
public static final MediaType NA_10X15_ENVELOPE =
new MediaType(I_NA_10X15_ENVELOPE);
/** {@collect.stats}
* The MediaType instance for North American 10 x 14 in.
*/
public static final MediaType NA_10X14_ENVELOPE =
new MediaType(I_NA_10X14_ENVELOPE);
/** {@collect.stats}
* The MediaType instance for North American 10 x 13 in.
*/
public static final MediaType NA_10X13_ENVELOPE =
new MediaType(I_NA_10X13_ENVELOPE);
/** {@collect.stats}
* The MediaType instance for North American 9 x 12 in.
*/
public static final MediaType NA_9X12_ENVELOPE =
new MediaType(I_NA_9X12_ENVELOPE);
/** {@collect.stats}
* The MediaType instance for North American 9 x 11 in.
*/
public static final MediaType NA_9X11_ENVELOPE =
new MediaType(I_NA_9X11_ENVELOPE);
/** {@collect.stats}
* The MediaType instance for North American 7 x 9 in.
*/
public static final MediaType NA_7X9_ENVELOPE =
new MediaType(I_NA_7X9_ENVELOPE);
/** {@collect.stats}
* The MediaType instance for North American 6 x 9 in.
*/
public static final MediaType NA_6X9_ENVELOPE =
new MediaType(I_NA_6X9_ENVELOPE);
/** {@collect.stats}
* The MediaType instance for North American #9 Business Envelope,
* 3 7/8 x 8 7/8 in.
*/
public static final MediaType NA_NUMBER_9_ENVELOPE =
new MediaType(I_NA_NUMBER_9_ENVELOPE);
/** {@collect.stats}
* The MediaType instance for North American #10 Business Envelope,
* 4 1/8 x 9 1/2 in.
*/
public static final MediaType NA_NUMBER_10_ENVELOPE =
new MediaType(I_NA_NUMBER_10_ENVELOPE);
/** {@collect.stats}
* The MediaType instance for North American #11 Business Envelope,
* 4 1/2 x 10 3/8 in.
*/
public static final MediaType NA_NUMBER_11_ENVELOPE =
new MediaType(I_NA_NUMBER_11_ENVELOPE);
/** {@collect.stats}
* The MediaType instance for North American #12 Business Envelope,
* 4 3/4 x 11 in.
*/
public static final MediaType NA_NUMBER_12_ENVELOPE =
new MediaType(I_NA_NUMBER_12_ENVELOPE);
/** {@collect.stats}
* The MediaType instance for North American #14 Business Envelope,
* 5 x 11 1/2 in.
*/
public static final MediaType NA_NUMBER_14_ENVELOPE =
new MediaType(I_NA_NUMBER_14_ENVELOPE);
/** {@collect.stats}
* The MediaType instance for Invitation Envelope, 220 x 220 mm.
*/
public static final MediaType INVITE_ENVELOPE =
new MediaType(I_INVITE_ENVELOPE);
/** {@collect.stats}
* The MediaType instance for Italy Envelope, 110 x 230 mm.
*/
public static final MediaType ITALY_ENVELOPE =
new MediaType(I_ITALY_ENVELOPE);
/** {@collect.stats}
* The MediaType instance for Monarch Envelope, 3 7/8 x 7 1/2 in.
*/
public static final MediaType MONARCH_ENVELOPE =
new MediaType(I_MONARCH_ENVELOPE);
/** {@collect.stats}
* The MediaType instance for 6 3/4 envelope, 3 5/8 x 6 1/2 in.
*/
public static final MediaType PERSONAL_ENVELOPE =
new MediaType(I_PERSONAL_ENVELOPE);
/** {@collect.stats}
* An alias for ISO_A0.
*/
public static final MediaType A0 = ISO_A0;
/** {@collect.stats}
* An alias for ISO_A1.
*/
public static final MediaType A1 = ISO_A1;
/** {@collect.stats}
* An alias for ISO_A2.
*/
public static final MediaType A2 = ISO_A2;
/** {@collect.stats}
* An alias for ISO_A3.
*/
public static final MediaType A3 = ISO_A3;
/** {@collect.stats}
* An alias for ISO_A4.
*/
public static final MediaType A4 = ISO_A4;
/** {@collect.stats}
* An alias for ISO_A5.
*/
public static final MediaType A5 = ISO_A5;
/** {@collect.stats}
* An alias for ISO_A6.
*/
public static final MediaType A6 = ISO_A6;
/** {@collect.stats}
* An alias for ISO_A7.
*/
public static final MediaType A7 = ISO_A7;
/** {@collect.stats}
* An alias for ISO_A8.
*/
public static final MediaType A8 = ISO_A8;
/** {@collect.stats}
* An alias for ISO_A9.
*/
public static final MediaType A9 = ISO_A9;
/** {@collect.stats}
* An alias for ISO_A10.
*/
public static final MediaType A10 = ISO_A10;
/** {@collect.stats}
* An alias for ISO_B0.
*/
public static final MediaType B0 = ISO_B0;
/** {@collect.stats}
* An alias for ISO_B1.
*/
public static final MediaType B1 = ISO_B1;
/** {@collect.stats}
* An alias for ISO_B2.
*/
public static final MediaType B2 = ISO_B2;
/** {@collect.stats}
* An alias for ISO_B3.
*/
public static final MediaType B3 = ISO_B3;
/** {@collect.stats}
* An alias for ISO_B4.
*/
public static final MediaType B4 = ISO_B4;
/** {@collect.stats}
* An alias for ISO_B4.
*/
public static final MediaType ISO_B4_ENVELOPE = ISO_B4;
/** {@collect.stats}
* An alias for ISO_B5.
*/
public static final MediaType B5 = ISO_B5;
/** {@collect.stats}
* An alias for ISO_B5.
*/
public static final MediaType ISO_B5_ENVELOPE = ISO_B5;
/** {@collect.stats}
* An alias for ISO_B6.
*/
public static final MediaType B6 = ISO_B6;
/** {@collect.stats}
* An alias for ISO_B7.
*/
public static final MediaType B7 = ISO_B7;
/** {@collect.stats}
* An alias for ISO_B8.
*/
public static final MediaType B8 = ISO_B8;
/** {@collect.stats}
* An alias for ISO_B9.
*/
public static final MediaType B9 = ISO_B9;
/** {@collect.stats}
* An alias for ISO_B10.
*/
public static final MediaType B10 = ISO_B10;
/** {@collect.stats}
* An alias for ISO_C0.
*/
public static final MediaType C0 = ISO_C0;
/** {@collect.stats}
* An alias for ISO_C0.
*/
public static final MediaType ISO_C0_ENVELOPE = ISO_C0;
/** {@collect.stats}
* An alias for ISO_C1.
*/
public static final MediaType C1 = ISO_C1;
/** {@collect.stats}
* An alias for ISO_C1.
*/
public static final MediaType ISO_C1_ENVELOPE = ISO_C1;
/** {@collect.stats}
* An alias for ISO_C2.
*/
public static final MediaType C2 = ISO_C2;
/** {@collect.stats}
* An alias for ISO_C2.
*/
public static final MediaType ISO_C2_ENVELOPE = ISO_C2;
/** {@collect.stats}
* An alias for ISO_C3.
*/
public static final MediaType C3 = ISO_C3;
/** {@collect.stats}
* An alias for ISO_C3.
*/
public static final MediaType ISO_C3_ENVELOPE = ISO_C3;
/** {@collect.stats}
* An alias for ISO_C4.
*/
public static final MediaType C4 = ISO_C4;
/** {@collect.stats}
* An alias for ISO_C4.
*/
public static final MediaType ISO_C4_ENVELOPE = ISO_C4;
/** {@collect.stats}
* An alias for ISO_C5.
*/
public static final MediaType C5 = ISO_C5;
/** {@collect.stats}
* An alias for ISO_C5.
*/
public static final MediaType ISO_C5_ENVELOPE = ISO_C5;
/** {@collect.stats}
* An alias for ISO_C6.
*/
public static final MediaType C6 = ISO_C6;
/** {@collect.stats}
* An alias for ISO_C6.
*/
public static final MediaType ISO_C6_ENVELOPE = ISO_C6;
/** {@collect.stats}
* An alias for ISO_C7.
*/
public static final MediaType C7 = ISO_C7;
/** {@collect.stats}
* An alias for ISO_C7.
*/
public static final MediaType ISO_C7_ENVELOPE = ISO_C7;
/** {@collect.stats}
* An alias for ISO_C8.
*/
public static final MediaType C8 = ISO_C8;
/** {@collect.stats}
* An alias for ISO_C8.
*/
public static final MediaType ISO_C8_ENVELOPE = ISO_C8;
/** {@collect.stats}
* An alias for ISO_C9.
*/
public static final MediaType C9 = ISO_C9;
/** {@collect.stats}
* An alias for ISO_C9.
*/
public static final MediaType ISO_C9_ENVELOPE = ISO_C9;
/** {@collect.stats}
* An alias for ISO_C10.
*/
public static final MediaType C10 = ISO_C10;
/** {@collect.stats}
* An alias for ISO_C10.
*/
public static final MediaType ISO_C10_ENVELOPE = ISO_C10;
/** {@collect.stats}
* An alias for ISO_DESIGNATED_LONG.
*/
public static final MediaType ISO_DESIGNATED_LONG_ENVELOPE =
ISO_DESIGNATED_LONG;
/** {@collect.stats}
* An alias for INVOICE.
*/
public static final MediaType STATEMENT = INVOICE;
/** {@collect.stats}
* An alias for LEDGER.
*/
public static final MediaType TABLOID = LEDGER;
/** {@collect.stats}
* An alias for NA_LETTER.
*/
public static final MediaType LETTER = NA_LETTER;
/** {@collect.stats}
* An alias for NA_LETTER.
*/
public static final MediaType NOTE = NA_LETTER;
/** {@collect.stats}
* An alias for NA_LEGAL.
*/
public static final MediaType LEGAL = NA_LEGAL;
/** {@collect.stats}
* An alias for NA_10X15_ENVELOPE.
*/
public static final MediaType ENV_10X15 = NA_10X15_ENVELOPE;
/** {@collect.stats}
* An alias for NA_10X14_ENVELOPE.
*/
public static final MediaType ENV_10X14 = NA_10X14_ENVELOPE;
/** {@collect.stats}
* An alias for NA_10X13_ENVELOPE.
*/
public static final MediaType ENV_10X13 = NA_10X13_ENVELOPE;
/** {@collect.stats}
* An alias for NA_9X12_ENVELOPE.
*/
public static final MediaType ENV_9X12 = NA_9X12_ENVELOPE;
/** {@collect.stats}
* An alias for NA_9X11_ENVELOPE.
*/
public static final MediaType ENV_9X11 = NA_9X11_ENVELOPE;
/** {@collect.stats}
* An alias for NA_7X9_ENVELOPE.
*/
public static final MediaType ENV_7X9 = NA_7X9_ENVELOPE;
/** {@collect.stats}
* An alias for NA_6X9_ENVELOPE.
*/
public static final MediaType ENV_6X9 = NA_6X9_ENVELOPE;
/** {@collect.stats}
* An alias for NA_NUMBER_9_ENVELOPE.
*/
public static final MediaType ENV_9 = NA_NUMBER_9_ENVELOPE;
/** {@collect.stats}
* An alias for NA_NUMBER_10_ENVELOPE.
*/
public static final MediaType ENV_10 = NA_NUMBER_10_ENVELOPE;
/** {@collect.stats}
* An alias for NA_NUMBER_11_ENVELOPE.
*/
public static final MediaType ENV_11 = NA_NUMBER_11_ENVELOPE;
/** {@collect.stats}
* An alias for NA_NUMBER_12_ENVELOPE.
*/
public static final MediaType ENV_12 = NA_NUMBER_12_ENVELOPE;
/** {@collect.stats}
* An alias for NA_NUMBER_14_ENVELOPE.
*/
public static final MediaType ENV_14 = NA_NUMBER_14_ENVELOPE;
/** {@collect.stats}
* An alias for INVITE_ENVELOPE.
*/
public static final MediaType ENV_INVITE = INVITE_ENVELOPE;
/** {@collect.stats}
* An alias for ITALY_ENVELOPE.
*/
public static final MediaType ENV_ITALY = ITALY_ENVELOPE;
/** {@collect.stats}
* An alias for MONARCH_ENVELOPE.
*/
public static final MediaType ENV_MONARCH = MONARCH_ENVELOPE;
/** {@collect.stats}
* An alias for PERSONAL_ENVELOPE.
*/
public static final MediaType ENV_PERSONAL = PERSONAL_ENVELOPE;
/** {@collect.stats}
* An alias for INVITE_ENVELOPE.
*/
public static final MediaType INVITE = INVITE_ENVELOPE;
/** {@collect.stats}
* An alias for ITALY_ENVELOPE.
*/
public static final MediaType ITALY = ITALY_ENVELOPE;
/** {@collect.stats}
* An alias for MONARCH_ENVELOPE.
*/
public static final MediaType MONARCH = MONARCH_ENVELOPE;
/** {@collect.stats}
* An alias for PERSONAL_ENVELOPE.
*/
public static final MediaType PERSONAL = PERSONAL_ENVELOPE;
private MediaType(int type) {
super(type, NAMES);
}
}
/** {@collect.stats}
* A type-safe enumeration of possible orientations. These orientations
* are in partial compliance with IPP 1.1.
* @since 1.3
*/
public static final class OrientationRequestedType extends AttributeValue {
private static final int I_PORTRAIT = 0;
private static final int I_LANDSCAPE = 1;
private static final String NAMES[] = {
"portrait", "landscape"
};
/** {@collect.stats}
* The OrientationRequestedType instance to use for specifying a
* portrait orientation.
*/
public static final OrientationRequestedType PORTRAIT =
new OrientationRequestedType(I_PORTRAIT);
/** {@collect.stats}
* The OrientationRequestedType instance to use for specifying a
* landscape orientation.
*/
public static final OrientationRequestedType LANDSCAPE =
new OrientationRequestedType(I_LANDSCAPE);
private OrientationRequestedType(int type) {
super(type, NAMES);
}
}
/** {@collect.stats}
* A type-safe enumeration of possible origins.
* @since 1.3
*/
public static final class OriginType extends AttributeValue {
private static final int I_PHYSICAL = 0;
private static final int I_PRINTABLE = 1;
private static final String NAMES[] = {
"physical", "printable"
};
/** {@collect.stats}
* The OriginType instance to use for specifying a physical origin.
*/
public static final OriginType PHYSICAL = new OriginType(I_PHYSICAL);
/** {@collect.stats}
* The OriginType instance to use for specifying a printable origin.
*/
public static final OriginType PRINTABLE = new OriginType(I_PRINTABLE);
private OriginType(int type) {
super(type, NAMES);
}
}
/** {@collect.stats}
* A type-safe enumeration of possible print qualities. These print
* qualities are in compliance with IPP 1.1.
* @since 1.3
*/
public static final class PrintQualityType extends AttributeValue {
private static final int I_HIGH = 0;
private static final int I_NORMAL = 1;
private static final int I_DRAFT = 2;
private static final String NAMES[] = {
"high", "normal", "draft"
};
/** {@collect.stats}
* The PrintQualityType instance to use for specifying a high print
* quality.
*/
public static final PrintQualityType HIGH =
new PrintQualityType(I_HIGH);
/** {@collect.stats}
* The PrintQualityType instance to use for specifying a normal print
* quality.
*/
public static final PrintQualityType NORMAL =
new PrintQualityType(I_NORMAL);
/** {@collect.stats}
* The PrintQualityType instance to use for specifying a draft print
* quality.
*/
public static final PrintQualityType DRAFT =
new PrintQualityType(I_DRAFT);
private PrintQualityType(int type) {
super(type, NAMES);
}
}
private ColorType color;
private MediaType media;
private OrientationRequestedType orientationRequested;
private OriginType origin;
private PrintQualityType printQuality;
private int[] printerResolution;
/** {@collect.stats}
* Constructs a PageAttributes instance with default values for every
* attribute.
*/
public PageAttributes() {
setColor(ColorType.MONOCHROME);
setMediaToDefault();
setOrientationRequestedToDefault();
setOrigin(OriginType.PHYSICAL);
setPrintQualityToDefault();
setPrinterResolutionToDefault();
}
/** {@collect.stats}
* Constructs a PageAttributes instance which is a copy of the supplied
* PageAttributes.
*
* @param obj the PageAttributes to copy.
*/
public PageAttributes(PageAttributes obj) {
set(obj);
}
/** {@collect.stats}
* Constructs a PageAttributes instance with the specified values for
* every attribute.
*
* @param color ColorType.COLOR or ColorType.MONOCHROME.
* @param media one of the constant fields of the MediaType class.
* @param orientationRequested OrientationRequestedType.PORTRAIT or
* OrientationRequestedType.LANDSCAPE.
* @param origin OriginType.PHYSICAL or OriginType.PRINTABLE
* @param printQuality PrintQualityType.DRAFT, PrintQualityType.NORMAL,
* or PrintQualityType.HIGH
* @param printerResolution an integer array of 3 elements. The first
* element must be greater than 0. The second element must be
* must be greater than 0. The third element must be either
* <code>3</code> or <code>4</code>.
* @throws IllegalArgumentException if one or more of the above
* conditions is violated.
*/
public PageAttributes(ColorType color, MediaType media,
OrientationRequestedType orientationRequested,
OriginType origin, PrintQualityType printQuality,
int[] printerResolution) {
setColor(color);
setMedia(media);
setOrientationRequested(orientationRequested);
setOrigin(origin);
setPrintQuality(printQuality);
setPrinterResolution(printerResolution);
}
/** {@collect.stats}
* Creates and returns a copy of this PageAttributes.
*
* @return the newly created copy. It is safe to cast this Object into
* a PageAttributes.
*/
public Object clone() {
try {
return super.clone();
} catch (CloneNotSupportedException e) {
// Since we implement Cloneable, this should never happen
throw new InternalError();
}
}
/** {@collect.stats}
* Sets all of the attributes of this PageAttributes to the same values as
* the attributes of obj.
*
* @param obj the PageAttributes to copy.
*/
public void set(PageAttributes obj) {
color = obj.color;
media = obj.media;
orientationRequested = obj.orientationRequested;
origin = obj.origin;
printQuality = obj.printQuality;
// okay because we never modify the contents of printerResolution
printerResolution = obj.printerResolution;
}
/** {@collect.stats}
* Returns whether pages using these attributes will be rendered in
* color or monochrome. This attribute is updated to the value chosen
* by the user.
*
* @return ColorType.COLOR or ColorType.MONOCHROME.
*/
public ColorType getColor() {
return color;
}
/** {@collect.stats}
* Specifies whether pages using these attributes will be rendered in
* color or monochrome. Not specifying this attribute is equivalent to
* specifying ColorType.MONOCHROME.
*
* @param color ColorType.COLOR or ColorType.MONOCHROME.
* @throws IllegalArgumentException if color is null.
*/
public void setColor(ColorType color) {
if (color == null) {
throw new IllegalArgumentException("Invalid value for attribute "+
"color");
}
this.color = color;
}
/** {@collect.stats}
* Returns the paper size for pages using these attributes. This
* attribute is updated to the value chosen by the user.
*
* @return one of the constant fields of the MediaType class.
*/
public MediaType getMedia() {
return media;
}
/** {@collect.stats}
* Specifies the desired paper size for pages using these attributes. The
* actual paper size will be determined by the limitations of the target
* printer. If an exact match cannot be found, an implementation will
* choose the closest possible match. Not specifying this attribute is
* equivalent to specifying the default size for the default locale. The
* default size for locales in the United States and Canada is
* MediaType.NA_LETTER. The default size for all other locales is
* MediaType.ISO_A4.
*
* @param media one of the constant fields of the MediaType class.
* @throws IllegalArgumentException if media is null.
*/
public void setMedia(MediaType media) {
if (media == null) {
throw new IllegalArgumentException("Invalid value for attribute "+
"media");
}
this.media = media;
}
/** {@collect.stats}
* Sets the paper size for pages using these attributes to the default
* size for the default locale. The default size for locales in the
* United States and Canada is MediaType.NA_LETTER. The default size for
* all other locales is MediaType.ISO_A4.
*/
public void setMediaToDefault(){
String defaultCountry = Locale.getDefault().getCountry();
if (defaultCountry != null &&
(defaultCountry.equals(Locale.US.getCountry()) ||
defaultCountry.equals(Locale.CANADA.getCountry()))) {
setMedia(MediaType.NA_LETTER);
} else {
setMedia(MediaType.ISO_A4);
}
}
/** {@collect.stats}
* Returns the print orientation for pages using these attributes. This
* attribute is updated to the value chosen by the user.
*
* @return OrientationRequestedType.PORTRAIT or
* OrientationRequestedType.LANDSCAPE.
*/
public OrientationRequestedType getOrientationRequested() {
return orientationRequested;
}
/** {@collect.stats}
* Specifies the print orientation for pages using these attributes. Not
* specifying the property is equivalent to specifying
* OrientationRequestedType.PORTRAIT.
*
* @param orientationRequested OrientationRequestedType.PORTRAIT or
* OrientationRequestedType.LANDSCAPE.
* @throws IllegalArgumentException if orientationRequested is null.
*/
public void setOrientationRequested(OrientationRequestedType
orientationRequested) {
if (orientationRequested == null) {
throw new IllegalArgumentException("Invalid value for attribute "+
"orientationRequested");
}
this.orientationRequested = orientationRequested;
}
/** {@collect.stats}
* Specifies the print orientation for pages using these attributes.
* Specifying <code>3</code> denotes portrait. Specifying <code>4</code>
* denotes landscape. Specifying any other value will generate an
* IllegalArgumentException. Not specifying the property is equivalent
* to calling setOrientationRequested(OrientationRequestedType.PORTRAIT).
*
* @param orientationRequested <code>3</code> or <code>4</code>
* @throws IllegalArgumentException if orientationRequested is not
* <code>3</code> or <code>4</code>
*/
public void setOrientationRequested(int orientationRequested) {
switch (orientationRequested) {
case 3:
setOrientationRequested(OrientationRequestedType.PORTRAIT);
break;
case 4:
setOrientationRequested(OrientationRequestedType.LANDSCAPE);
break;
default:
// This will throw an IllegalArgumentException
setOrientationRequested(null);
break;
}
}
/** {@collect.stats}
* Sets the print orientation for pages using these attributes to the
* default. The default orientation is portrait.
*/
public void setOrientationRequestedToDefault() {
setOrientationRequested(OrientationRequestedType.PORTRAIT);
}
/** {@collect.stats}
* Returns whether drawing at (0, 0) to pages using these attributes
* draws at the upper-left corner of the physical page, or at the
* upper-left corner of the printable area. (Note that these locations
* could be equivalent.) This attribute cannot be modified by,
* and is not subject to any limitations of, the implementation or the
* target printer.
*
* @return OriginType.PHYSICAL or OriginType.PRINTABLE
*/
public OriginType getOrigin() {
return origin;
}
/** {@collect.stats}
* Specifies whether drawing at (0, 0) to pages using these attributes
* draws at the upper-left corner of the physical page, or at the
* upper-left corner of the printable area. (Note that these locations
* could be equivalent.) Not specifying the property is equivalent to
* specifying OriginType.PHYSICAL.
*
* @param origin OriginType.PHYSICAL or OriginType.PRINTABLE
* @throws IllegalArgumentException if origin is null.
*/
public void setOrigin(OriginType origin) {
if (origin == null) {
throw new IllegalArgumentException("Invalid value for attribute "+
"origin");
}
this.origin = origin;
}
/** {@collect.stats}
* Returns the print quality for pages using these attributes. This
* attribute is updated to the value chosen by the user.
*
* @return PrintQualityType.DRAFT, PrintQualityType.NORMAL, or
* PrintQualityType.HIGH
*/
public PrintQualityType getPrintQuality() {
return printQuality;
}
/** {@collect.stats}
* Specifies the print quality for pages using these attributes. Not
* specifying the property is equivalent to specifying
* PrintQualityType.NORMAL.
*
* @param printQuality PrintQualityType.DRAFT, PrintQualityType.NORMAL,
* or PrintQualityType.HIGH
* @throws IllegalArgumentException if printQuality is null.
*/
public void setPrintQuality(PrintQualityType printQuality) {
if (printQuality == null) {
throw new IllegalArgumentException("Invalid value for attribute "+
"printQuality");
}
this.printQuality = printQuality;
}
/** {@collect.stats}
* Specifies the print quality for pages using these attributes.
* Specifying <code>3</code> denotes draft. Specifying <code>4</code>
* denotes normal. Specifying <code>5</code> denotes high. Specifying
* any other value will generate an IllegalArgumentException. Not
* specifying the property is equivalent to calling
* setPrintQuality(PrintQualityType.NORMAL).
*
* @param printQuality <code>3</code>, <code>4</code>, or <code>5</code>
* @throws IllegalArgumentException if printQuality is not <code>3
* </code>, <code>4</code>, or <code>5</code>
*/
public void setPrintQuality(int printQuality) {
switch (printQuality) {
case 3:
setPrintQuality(PrintQualityType.DRAFT);
break;
case 4:
setPrintQuality(PrintQualityType.NORMAL);
break;
case 5:
setPrintQuality(PrintQualityType.HIGH);
break;
default:
// This will throw an IllegalArgumentException
setPrintQuality(null);
break;
}
}
/** {@collect.stats}
* Sets the print quality for pages using these attributes to the default.
* The default print quality is normal.
*/
public void setPrintQualityToDefault() {
setPrintQuality(PrintQualityType.NORMAL);
}
/** {@collect.stats}
* Returns the print resolution for pages using these attributes.
* Index 0 of the array specifies the cross feed direction resolution
* (typically the horizontal resolution). Index 1 of the array specifies
* the feed direction resolution (typically the vertical resolution).
* Index 2 of the array specifies whether the resolutions are in dots per
* inch or dots per centimeter. <code>3</code> denotes dots per inch.
* <code>4</code> denotes dots per centimeter.
*
* @return an integer array of 3 elements. The first
* element must be greater than 0. The second element must be
* must be greater than 0. The third element must be either
* <code>3</code> or <code>4</code>.
*/
public int[] getPrinterResolution() {
// Return a copy because otherwise client code could circumvent the
// the checks made in setPrinterResolution by modifying the
// returned array.
int[] copy = new int[3];
copy[0] = printerResolution[0];
copy[1] = printerResolution[1];
copy[2] = printerResolution[2];
return copy;
}
/** {@collect.stats}
* Specifies the desired print resolution for pages using these attributes.
* The actual resolution will be determined by the limitations of the
* implementation and the target printer. Index 0 of the array specifies
* the cross feed direction resolution (typically the horizontal
* resolution). Index 1 of the array specifies the feed direction
* resolution (typically the vertical resolution). Index 2 of the array
* specifies whether the resolutions are in dots per inch or dots per
* centimeter. <code>3</code> denotes dots per inch. <code>4</code>
* denotes dots per centimeter. Note that the 1.1 printing implementation
* (Toolkit.getPrintJob) requires that the feed and cross feed resolutions
* be the same. Not specifying the property is equivalent to calling
* setPrinterResolution(72).
*
* @param printerResolution an integer array of 3 elements. The first
* element must be greater than 0. The second element must be
* must be greater than 0. The third element must be either
* <code>3</code> or <code>4</code>.
* @throws IllegalArgumentException if one or more of the above
* conditions is violated.
*/
public void setPrinterResolution(int[] printerResolution) {
if (printerResolution == null ||
printerResolution.length != 3 ||
printerResolution[0] <= 0 ||
printerResolution[1] <= 0 ||
(printerResolution[2] != 3 && printerResolution[2] != 4)) {
throw new IllegalArgumentException("Invalid value for attribute "+
"printerResolution");
}
// Store a copy because otherwise client code could circumvent the
// the checks made above by holding a reference to the array and
// modifying it after calling setPrinterResolution.
int[] copy = new int[3];
copy[0] = printerResolution[0];
copy[1] = printerResolution[1];
copy[2] = printerResolution[2];
this.printerResolution = copy;
}
/** {@collect.stats}
* Specifies the desired cross feed and feed print resolutions in dots per
* inch for pages using these attributes. The same value is used for both
* resolutions. The actual resolutions will be determined by the
* limitations of the implementation and the target printer. Not
* specifying the property is equivalent to specifying <code>72</code>.
*
* @param printerResolution an integer greater than 0.
* @throws IllegalArgumentException if printerResolution is less than or
* equal to 0.
*/
public void setPrinterResolution(int printerResolution) {
setPrinterResolution(new int[] { printerResolution, printerResolution,
3 } );
}
/** {@collect.stats}
* Sets the printer resolution for pages using these attributes to the
* default. The default is 72 dpi for both the feed and cross feed
* resolutions.
*/
public void setPrinterResolutionToDefault() {
setPrinterResolution(72);
}
/** {@collect.stats}
* Determines whether two PageAttributes are equal to each other.
* <p>
* Two PageAttributes are equal if and only if each of their attributes are
* equal. Attributes of enumeration type are equal if and only if the
* fields refer to the same unique enumeration object. This means that
* an aliased media is equal to its underlying unique media. Printer
* resolutions are equal if and only if the feed resolution, cross feed
* resolution, and units are equal.
*
* @param obj the object whose equality will be checked.
* @return whether obj is equal to this PageAttribute according to the
* above criteria.
*/
public boolean equals(Object obj) {
if (!(obj instanceof PageAttributes)) {
return false;
}
PageAttributes rhs = (PageAttributes)obj;
return (color == rhs.color &&
media == rhs.media &&
orientationRequested == rhs.orientationRequested &&
origin == rhs.origin &&
printQuality == rhs.printQuality &&
printerResolution[0] == rhs.printerResolution[0] &&
printerResolution[1] == rhs.printerResolution[1] &&
printerResolution[2] == rhs.printerResolution[2]);
}
/** {@collect.stats}
* Returns a hash code value for this PageAttributes.
*
* @return the hash code.
*/
public int hashCode() {
return (color.hashCode() << 31 ^
media.hashCode() << 24 ^
orientationRequested.hashCode() << 23 ^
origin.hashCode() << 22 ^
printQuality.hashCode() << 20 ^
printerResolution[2] >> 2 << 19 ^
printerResolution[1] << 10 ^
printerResolution[0]);
}
/** {@collect.stats}
* Returns a string representation of this PageAttributes.
*
* @return the string representation.
*/
public String toString() {
// int[] printerResolution = getPrinterResolution();
return "color=" + getColor() + ",media=" + getMedia() +
",orientation-requested=" + getOrientationRequested() +
",origin=" + getOrigin() + ",print-quality=" + getPrintQuality() +
",printer-resolution=[" + printerResolution[0] + "," +
printerResolution[1] + "," + printerResolution[2] + "]";
}
}
|
Java
|
/*
* Copyright (c) 1995, 2006, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code 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
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package java.awt;
import java.awt.peer.MenuItemPeer;
import java.awt.event.*;
import java.util.EventListener;
import java.io.ObjectOutputStream;
import java.io.ObjectInputStream;
import java.io.IOException;
import javax.accessibility.*;
/** {@collect.stats}
* All items in a menu must belong to the class
* <code>MenuItem</code>, or one of its subclasses.
* <p>
* The default <code>MenuItem</code> object embodies
* a simple labeled menu item.
* <p>
* This picture of a menu bar shows five menu items:
* <IMG SRC="doc-files/MenuBar-1.gif" alt="The following text describes this graphic."
* ALIGN=CENTER HSPACE=10 VSPACE=7>
* <br CLEAR=LEFT>
* The first two items are simple menu items, labeled
* <code>"Basic"</code> and <code>"Simple"</code>.
* Following these two items is a separator, which is itself
* a menu item, created with the label <code>"-"</code>.
* Next is an instance of <code>CheckboxMenuItem</code>
* labeled <code>"Check"</code>. The final menu item is a
* submenu labeled <code>"More Examples"</code>,
* and this submenu is an instance of <code>Menu</code>.
* <p>
* When a menu item is selected, AWT sends an action event to
* the menu item. Since the event is an
* instance of <code>ActionEvent</code>, the <code>processEvent</code>
* method examines the event and passes it along to
* <code>processActionEvent</code>. The latter method redirects the
* event to any <code>ActionListener</code> objects that have
* registered an interest in action events generated by this
* menu item.
* <P>
* Note that the subclass <code>Menu</code> overrides this behavior and
* does not send any event to the frame until one of its subitems is
* selected.
*
* @author Sami Shaio
*/
public class MenuItem extends MenuComponent implements Accessible {
static {
/* ensure that the necessary native libraries are loaded */
Toolkit.loadLibraries();
if (!GraphicsEnvironment.isHeadless()) {
initIDs();
}
}
/** {@collect.stats}
* A value to indicate whether a menu item is enabled
* or not. If it is enabled, <code>enabled</code> will
* be set to true. Else <code>enabled</code> will
* be set to false.
*
* @serial
* @see #isEnabled()
* @see #setEnabled(boolean)
*/
boolean enabled = true;
/** {@collect.stats}
* <code>label</code> is the label of a menu item.
* It can be any string.
*
* @serial
* @see #getLabel()
* @see #setLabel(String)
*/
String label;
/** {@collect.stats}
* This field indicates the command tha has been issued
* by a particular menu item.
* By default the <code>actionCommand</code>
* is the label of the menu item, unless it has been
* set using setActionCommand.
*
* @serial
* @see #setActionCommand(String)
* @see #getActionCommand()
*/
String actionCommand;
/** {@collect.stats}
* The eventMask is ONLY set by subclasses via enableEvents.
* The mask should NOT be set when listeners are registered
* so that we can distinguish the difference between when
* listeners request events and subclasses request them.
*
* @serial
*/
long eventMask;
transient ActionListener actionListener;
/** {@collect.stats}
* A sequence of key stokes that ia associated with
* a menu item.
* Note :in 1.1.2 you must use setActionCommand()
* on a menu item in order for its shortcut to
* work.
*
* @serial
* @see #getShortcut()
* @see #setShortcut(MenuShortcut)
* @see #deleteShortcut()
*/
private MenuShortcut shortcut = null;
private static final String base = "menuitem";
private static int nameCounter = 0;
/*
* JDK 1.1 serialVersionUID
*/
private static final long serialVersionUID = -21757335363267194L;
/** {@collect.stats}
* Constructs a new MenuItem with an empty label and no keyboard
* shortcut.
* @exception HeadlessException if GraphicsEnvironment.isHeadless()
* returns true.
* @see java.awt.GraphicsEnvironment#isHeadless
* @since JDK1.1
*/
public MenuItem() throws HeadlessException {
this("", null);
}
/** {@collect.stats}
* Constructs a new MenuItem with the specified label
* and no keyboard shortcut. Note that use of "-" in
* a label is reserved to indicate a separator between
* menu items. By default, all menu items except for
* separators are enabled.
* @param label the label for this menu item.
* @exception HeadlessException if GraphicsEnvironment.isHeadless()
* returns true.
* @see java.awt.GraphicsEnvironment#isHeadless
* @since JDK1.0
*/
public MenuItem(String label) throws HeadlessException {
this(label, null);
}
/** {@collect.stats}
* Create a menu item with an associated keyboard shortcut.
* Note that use of "-" in a label is reserved to indicate
* a separator between menu items. By default, all menu
* items except for separators are enabled.
* @param label the label for this menu item.
* @param s the instance of <code>MenuShortcut</code>
* associated with this menu item.
* @exception HeadlessException if GraphicsEnvironment.isHeadless()
* returns true.
* @see java.awt.GraphicsEnvironment#isHeadless
* @since JDK1.1
*/
public MenuItem(String label, MenuShortcut s) throws HeadlessException {
this.label = label;
this.shortcut = s;
}
/** {@collect.stats}
* Construct a name for this MenuComponent. Called by getName() when
* the name is null.
*/
String constructComponentName() {
synchronized (MenuItem.class) {
return base + nameCounter++;
}
}
/** {@collect.stats}
* Creates the menu item's peer. The peer allows us to modify the
* appearance of the menu item without changing its functionality.
*/
public void addNotify() {
synchronized (getTreeLock()) {
if (peer == null)
peer = Toolkit.getDefaultToolkit().createMenuItem(this);
}
}
/** {@collect.stats}
* Gets the label for this menu item.
* @return the label of this menu item, or <code>null</code>
if this menu item has no label.
* @see java.awt.MenuItem#setLabel
* @since JDK1.0
*/
public String getLabel() {
return label;
}
/** {@collect.stats}
* Sets the label for this menu item to the specified label.
* @param label the new label, or <code>null</code> for no label.
* @see java.awt.MenuItem#getLabel
* @since JDK1.0
*/
public synchronized void setLabel(String label) {
this.label = label;
MenuItemPeer peer = (MenuItemPeer)this.peer;
if (peer != null) {
peer.setLabel(label);
}
}
/** {@collect.stats}
* Checks whether this menu item is enabled.
* @see java.awt.MenuItem#setEnabled
* @since JDK1.0
*/
public boolean isEnabled() {
return enabled;
}
/** {@collect.stats}
* Sets whether or not this menu item can be chosen.
* @param b if <code>true</code>, enables this menu item;
* if <code>false</code>, disables it.
* @see java.awt.MenuItem#isEnabled
* @since JDK1.1
*/
public synchronized void setEnabled(boolean b) {
enable(b);
}
/** {@collect.stats}
* @deprecated As of JDK version 1.1,
* replaced by <code>setEnabled(boolean)</code>.
*/
@Deprecated
public synchronized void enable() {
enabled = true;
MenuItemPeer peer = (MenuItemPeer)this.peer;
if (peer != null) {
peer.enable();
}
}
/** {@collect.stats}
* @deprecated As of JDK version 1.1,
* replaced by <code>setEnabled(boolean)</code>.
*/
@Deprecated
public void enable(boolean b) {
if (b) {
enable();
} else {
disable();
}
}
/** {@collect.stats}
* @deprecated As of JDK version 1.1,
* replaced by <code>setEnabled(boolean)</code>.
*/
@Deprecated
public synchronized void disable() {
enabled = false;
MenuItemPeer peer = (MenuItemPeer)this.peer;
if (peer != null) {
peer.disable();
}
}
/** {@collect.stats}
* Get the <code>MenuShortcut</code> object associated with this
* menu item,
* @return the menu shortcut associated with this menu item,
* or <code>null</code> if none has been specified.
* @see java.awt.MenuItem#setShortcut
* @since JDK1.1
*/
public MenuShortcut getShortcut() {
return shortcut;
}
/** {@collect.stats}
* Set the <code>MenuShortcut</code> object associated with this
* menu item. If a menu shortcut is already associated with
* this menu item, it is replaced.
* @param s the menu shortcut to associate
* with this menu item.
* @see java.awt.MenuItem#getShortcut
* @since JDK1.1
*/
public void setShortcut(MenuShortcut s) {
shortcut = s;
MenuItemPeer peer = (MenuItemPeer)this.peer;
if (peer != null) {
peer.setLabel(label);
}
}
/** {@collect.stats}
* Delete any <code>MenuShortcut</code> object associated
* with this menu item.
* @since JDK1.1
*/
public void deleteShortcut() {
shortcut = null;
MenuItemPeer peer = (MenuItemPeer)this.peer;
if (peer != null) {
peer.setLabel(label);
}
}
/*
* Delete a matching MenuShortcut associated with this MenuItem.
* Used when iterating Menus.
*/
void deleteShortcut(MenuShortcut s) {
if (s.equals(shortcut)) {
shortcut = null;
MenuItemPeer peer = (MenuItemPeer)this.peer;
if (peer != null) {
peer.setLabel(label);
}
}
}
/*
* The main goal of this method is to post an appropriate event
* to the event queue when menu shortcut is pressed. However,
* in subclasses this method may do more than just posting
* an event.
*/
void doMenuEvent(long when, int modifiers) {
Toolkit.getEventQueue().postEvent(
new ActionEvent(this, ActionEvent.ACTION_PERFORMED,
getActionCommand(), when, modifiers));
}
/*
* Returns true if the item and all its ancestors are
* enabled, false otherwise
*/
private final boolean isItemEnabled() {
// Fix For 6185151: Menu shortcuts of all menuitems within a menu
// should be disabled when the menu itself is disabled
if (!isEnabled()) {
return false;
}
MenuContainer container = getParent_NoClientCode();
do {
if (!(container instanceof Menu)) {
return true;
}
Menu menu = (Menu)container;
if (!menu.isEnabled()) {
return false;
}
container = menu.getParent_NoClientCode();
} while (container != null);
return true;
}
/*
* Post an ActionEvent to the target (on
* keydown) and the item is enabled.
* Returns true if there is an associated shortcut.
*/
boolean handleShortcut(KeyEvent e) {
MenuShortcut s = new MenuShortcut(e.getKeyCode(),
(e.getModifiers() & InputEvent.SHIFT_MASK) > 0);
// Fix For 6185151: Menu shortcuts of all menuitems within a menu
// should be disabled when the menu itself is disabled
if (s.equals(shortcut) && isItemEnabled()) {
// MenuShortcut match -- issue an event on keydown.
if (e.getID() == KeyEvent.KEY_PRESSED) {
doMenuEvent(e.getWhen(), e.getModifiers());
} else {
// silently eat key release.
}
return true;
}
return false;
}
MenuItem getShortcutMenuItem(MenuShortcut s) {
return (s.equals(shortcut)) ? this : null;
}
/** {@collect.stats}
* Enables event delivery to this menu item for events
* to be defined by the specified event mask parameter
* <p>
* Since event types are automatically enabled when a listener for
* that type is added to the menu item, this method only needs
* to be invoked by subclasses of <code>MenuItem</code> which desire to
* have the specified event types delivered to <code>processEvent</code>
* regardless of whether a listener is registered.
*
* @param eventsToEnable the event mask defining the event types
* @see java.awt.MenuItem#processEvent
* @see java.awt.MenuItem#disableEvents
* @see java.awt.Component#enableEvents
* @since JDK1.1
*/
protected final void enableEvents(long eventsToEnable) {
eventMask |= eventsToEnable;
newEventsOnly = true;
}
/** {@collect.stats}
* Disables event delivery to this menu item for events
* defined by the specified event mask parameter.
*
* @param eventsToDisable the event mask defining the event types
* @see java.awt.MenuItem#processEvent
* @see java.awt.MenuItem#enableEvents
* @see java.awt.Component#disableEvents
* @since JDK1.1
*/
protected final void disableEvents(long eventsToDisable) {
eventMask &= ~eventsToDisable;
}
/** {@collect.stats}
* Sets the command name of the action event that is fired
* by this menu item.
* <p>
* By default, the action command is set to the label of
* the menu item.
* @param command the action command to be set
* for this menu item.
* @see java.awt.MenuItem#getActionCommand
* @since JDK1.1
*/
public void setActionCommand(String command) {
actionCommand = command;
}
/** {@collect.stats}
* Gets the command name of the action event that is fired
* by this menu item.
* @see java.awt.MenuItem#setActionCommand
* @since JDK1.1
*/
public String getActionCommand() {
return getActionCommandImpl();
}
// This is final so it can be called on the Toolkit thread.
final String getActionCommandImpl() {
return (actionCommand == null? label : actionCommand);
}
/** {@collect.stats}
* Adds the specified action listener to receive action events
* from this menu item.
* If l is null, no exception is thrown and no action is performed.
* <p>Refer to <a href="doc-files/AWTThreadIssues.html#ListenersThreads"
* >AWT Threading Issues</a> for details on AWT's threading model.
*
* @param l the action listener.
* @see #removeActionListener
* @see #getActionListeners
* @see java.awt.event.ActionEvent
* @see java.awt.event.ActionListener
* @since JDK1.1
*/
public synchronized void addActionListener(ActionListener l) {
if (l == null) {
return;
}
actionListener = AWTEventMulticaster.add(actionListener, l);
newEventsOnly = true;
}
/** {@collect.stats}
* Removes the specified action listener so it no longer receives
* action events from this menu item.
* If l is null, no exception is thrown and no action is performed.
* <p>Refer to <a href="doc-files/AWTThreadIssues.html#ListenersThreads"
* >AWT Threading Issues</a> for details on AWT's threading model.
*
* @param l the action listener.
* @see #addActionListener
* @see #getActionListeners
* @see java.awt.event.ActionEvent
* @see java.awt.event.ActionListener
* @since JDK1.1
*/
public synchronized void removeActionListener(ActionListener l) {
if (l == null) {
return;
}
actionListener = AWTEventMulticaster.remove(actionListener, l);
}
/** {@collect.stats}
* Returns an array of all the action listeners
* registered on this menu item.
*
* @return all of this menu item's <code>ActionListener</code>s
* or an empty array if no action
* listeners are currently registered
*
* @see #addActionListener
* @see #removeActionListener
* @see java.awt.event.ActionEvent
* @see java.awt.event.ActionListener
* @since 1.4
*/
public synchronized ActionListener[] getActionListeners() {
return (ActionListener[])(getListeners(ActionListener.class));
}
/** {@collect.stats}
* Returns an array of all the objects currently registered
* as <code><em>Foo</em>Listener</code>s
* upon this <code>MenuItem</code>.
* <code><em>Foo</em>Listener</code>s are registered using the
* <code>add<em>Foo</em>Listener</code> method.
*
* <p>
* You can specify the <code>listenerType</code> argument
* with a class literal, such as
* <code><em>Foo</em>Listener.class</code>.
* For example, you can query a
* <code>MenuItem</code> <code>m</code>
* for its action listeners with the following code:
*
* <pre>ActionListener[] als = (ActionListener[])(m.getListeners(ActionListener.class));</pre>
*
* If no such listeners exist, this method returns an empty array.
*
* @param listenerType the type of listeners requested; this parameter
* should specify an interface that descends from
* <code>java.util.EventListener</code>
* @return an array of all objects registered as
* <code><em>Foo</em>Listener</code>s on this menu item,
* or an empty array if no such
* listeners have been added
* @exception ClassCastException if <code>listenerType</code>
* doesn't specify a class or interface that implements
* <code>java.util.EventListener</code>
*
* @see #getActionListeners
* @since 1.3
*/
public <T extends EventListener> T[] getListeners(Class<T> listenerType) {
EventListener l = null;
if (listenerType == ActionListener.class) {
l = actionListener;
}
return AWTEventMulticaster.getListeners(l, listenerType);
}
/** {@collect.stats}
* Processes events on this menu item. If the event is an
* instance of <code>ActionEvent</code>, it invokes
* <code>processActionEvent</code>, another method
* defined by <code>MenuItem</code>.
* <p>
* Currently, menu items only support action events.
* <p>Note that if the event parameter is <code>null</code>
* the behavior is unspecified and may result in an
* exception.
*
* @param e the event
* @see java.awt.MenuItem#processActionEvent
* @since JDK1.1
*/
protected void processEvent(AWTEvent e) {
if (e instanceof ActionEvent) {
processActionEvent((ActionEvent)e);
}
}
// REMIND: remove when filtering is done at lower level
boolean eventEnabled(AWTEvent e) {
if (e.id == ActionEvent.ACTION_PERFORMED) {
if ((eventMask & AWTEvent.ACTION_EVENT_MASK) != 0 ||
actionListener != null) {
return true;
}
return false;
}
return super.eventEnabled(e);
}
/** {@collect.stats}
* Processes action events occurring on this menu item,
* by dispatching them to any registered
* <code>ActionListener</code> objects.
* This method is not called unless action events are
* enabled for this component. Action events are enabled
* when one of the following occurs:
* <p><ul>
* <li>An <code>ActionListener</code> object is registered
* via <code>addActionListener</code>.
* <li>Action events are enabled via <code>enableEvents</code>.
* </ul>
* <p>Note that if the event parameter is <code>null</code>
* the behavior is unspecified and may result in an
* exception.
*
* @param e the action event
* @see java.awt.event.ActionEvent
* @see java.awt.event.ActionListener
* @see java.awt.MenuItem#enableEvents
* @since JDK1.1
*/
protected void processActionEvent(ActionEvent e) {
ActionListener listener = actionListener;
if (listener != null) {
listener.actionPerformed(e);
}
}
/** {@collect.stats}
* Returns a string representing the state of this <code>MenuItem</code>.
* This method is intended to be used only for debugging purposes, and the
* content and format of the returned string may vary between
* implementations. The returned string may be empty but may not be
* <code>null</code>.
*
* @return the parameter string of this menu item
*/
public String paramString() {
String str = ",label=" + label;
if (shortcut != null) {
str += ",shortcut=" + shortcut;
}
return super.paramString() + str;
}
/* Serialization support.
*/
/** {@collect.stats}
* Menu item serialized data version.
*
* @serial
*/
private int menuItemSerializedDataVersion = 1;
/** {@collect.stats}
* Writes default serializable fields to stream. Writes
* a list of serializable <code>ActionListeners</code>
* as optional data. The non-serializable listeners are
* detected and no attempt is made to serialize them.
*
* @param s the <code>ObjectOutputStream</code> to write
* @serialData <code>null</code> terminated sequence of 0
* or more pairs; the pair consists of a <code>String</code>
* and an <code>Object</code>; the <code>String</code>
* indicates the type of object and is one of the following:
* <code>actionListenerK</code> indicating an
* <code>ActionListener</code> object
*
* @see AWTEventMulticaster#save(ObjectOutputStream, String, EventListener)
* @see #readObject(ObjectInputStream)
*/
private void writeObject(ObjectOutputStream s)
throws IOException
{
s.defaultWriteObject();
AWTEventMulticaster.save(s, actionListenerK, actionListener);
s.writeObject(null);
}
/** {@collect.stats}
* Reads the <code>ObjectInputStream</code> and if it
* isn't <code>null</code> adds a listener to receive
* action events fired by the <code>Menu</code> Item.
* Unrecognized keys or values will be ignored.
*
* @param s the <code>ObjectInputStream</code> to read
* @exception HeadlessException if
* <code>GraphicsEnvironment.isHeadless</code> returns
* <code>true</code>
* @see #removeActionListener(ActionListener)
* @see #addActionListener(ActionListener)
* @see #writeObject(ObjectOutputStream)
*/
private void readObject(ObjectInputStream s)
throws ClassNotFoundException, IOException, HeadlessException
{
// HeadlessException will be thrown from MenuComponent's readObject
s.defaultReadObject();
Object keyOrNull;
while(null != (keyOrNull = s.readObject())) {
String key = ((String)keyOrNull).intern();
if (actionListenerK == key)
addActionListener((ActionListener)(s.readObject()));
else // skip value for unrecognized key
s.readObject();
}
}
/** {@collect.stats}
* Initialize JNI field and method IDs
*/
private static native void initIDs();
/////////////////
// Accessibility support
////////////////
/** {@collect.stats}
* Gets the AccessibleContext associated with this MenuItem.
* For menu items, the AccessibleContext takes the form of an
* AccessibleAWTMenuItem.
* A new AccessibleAWTMenuItem instance is created if necessary.
*
* @return an AccessibleAWTMenuItem that serves as the
* AccessibleContext of this MenuItem
* @since 1.3
*/
public AccessibleContext getAccessibleContext() {
if (accessibleContext == null) {
accessibleContext = new AccessibleAWTMenuItem();
}
return accessibleContext;
}
/** {@collect.stats}
* Inner class of MenuItem used to provide default support for
* accessibility. This class is not meant to be used directly by
* application developers, but is instead meant only to be
* subclassed by menu component developers.
* <p>
* This class implements accessibility support for the
* <code>MenuItem</code> class. It provides an implementation of the
* Java Accessibility API appropriate to menu item user-interface elements.
* @since 1.3
*/
protected class AccessibleAWTMenuItem extends AccessibleAWTMenuComponent
implements AccessibleAction, AccessibleValue
{
/*
* JDK 1.3 serialVersionUID
*/
private static final long serialVersionUID = -217847831945965825L;
/** {@collect.stats}
* Get the accessible name of this object.
*
* @return the localized name of the object -- can be null if this
* object does not have a name
*/
public String getAccessibleName() {
if (accessibleName != null) {
return accessibleName;
} else {
if (getLabel() == null) {
return super.getAccessibleName();
} else {
return getLabel();
}
}
}
/** {@collect.stats}
* Get the role of this object.
*
* @return an instance of AccessibleRole describing the role of the
* object
*/
public AccessibleRole getAccessibleRole() {
return AccessibleRole.MENU_ITEM;
}
/** {@collect.stats}
* Get the AccessibleAction associated with this object. In the
* implementation of the Java Accessibility API for this class,
* return this object, which is responsible for implementing the
* AccessibleAction interface on behalf of itself.
*
* @return this object
*/
public AccessibleAction getAccessibleAction() {
return this;
}
/** {@collect.stats}
* Get the AccessibleValue associated with this object. In the
* implementation of the Java Accessibility API for this class,
* return this object, which is responsible for implementing the
* AccessibleValue interface on behalf of itself.
*
* @return this object
*/
public AccessibleValue getAccessibleValue() {
return this;
}
/** {@collect.stats}
* Returns the number of Actions available in this object. The
* default behavior of a menu item is to have one action.
*
* @return 1, the number of Actions in this object
*/
public int getAccessibleActionCount() {
return 1;
}
/** {@collect.stats}
* Return a description of the specified action of the object.
*
* @param i zero-based index of the actions
*/
public String getAccessibleActionDescription(int i) {
if (i == 0) {
// [[[PENDING: WDW -- need to provide a localized string]]]
return new String("click");
} else {
return null;
}
}
/** {@collect.stats}
* Perform the specified Action on the object
*
* @param i zero-based index of actions
* @return true if the action was performed; otherwise false.
*/
public boolean doAccessibleAction(int i) {
if (i == 0) {
// Simulate a button click
Toolkit.getEventQueue().postEvent(
new ActionEvent(MenuItem.this,
ActionEvent.ACTION_PERFORMED,
MenuItem.this.getActionCommand(),
EventQueue.getMostRecentEventTime(),
0));
return true;
} else {
return false;
}
}
/** {@collect.stats}
* Get the value of this object as a Number.
*
* @return An Integer of 0 if this isn't selected or an Integer of 1 if
* this is selected.
* @see javax.swing.AbstractButton#isSelected()
*/
public Number getCurrentAccessibleValue() {
return Integer.valueOf(0);
}
/** {@collect.stats}
* Set the value of this object as a Number.
*
* @return True if the value was set.
*/
public boolean setCurrentAccessibleValue(Number n) {
return false;
}
/** {@collect.stats}
* Get the minimum value of this object as a Number.
*
* @return An Integer of 0.
*/
public Number getMinimumAccessibleValue() {
return Integer.valueOf(0);
}
/** {@collect.stats}
* Get the maximum value of this object as a Number.
*
* @return An Integer of 0.
*/
public Number getMaximumAccessibleValue() {
return Integer.valueOf(0);
}
} // class AccessibleAWTMenuItem
}
|
Java
|
/*
* Copyright (c) 1995, 2006, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code 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
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package java.awt;
import java.io.*;
import java.lang.*;
import java.util.*;
import java.awt.image.ImageObserver;
import java.text.AttributedCharacterIterator;
/** {@collect.stats}
* The <code>Graphics</code> class is the abstract base class for
* all graphics contexts that allow an application to draw onto
* components that are realized on various devices, as well as
* onto off-screen images.
* <p>
* A <code>Graphics</code> object encapsulates state information needed
* for the basic rendering operations that Java supports. This
* state information includes the following properties:
* <p>
* <ul>
* <li>The <code>Component</code> object on which to draw.
* <li>A translation origin for rendering and clipping coordinates.
* <li>The current clip.
* <li>The current color.
* <li>The current font.
* <li>The current logical pixel operation function (XOR or Paint).
* <li>The current XOR alternation color
* (see {@link Graphics#setXORMode}).
* </ul>
* <p>
* Coordinates are infinitely thin and lie between the pixels of the
* output device.
* Operations that draw the outline of a figure operate by traversing
* an infinitely thin path between pixels with a pixel-sized pen that hangs
* down and to the right of the anchor point on the path.
* Operations that fill a figure operate by filling the interior
* of that infinitely thin path.
* Operations that render horizontal text render the ascending
* portion of character glyphs entirely above the baseline coordinate.
* <p>
* The graphics pen hangs down and to the right from the path it traverses.
* This has the following implications:
* <p><ul>
* <li>If you draw a figure that covers a given rectangle, that
* figure occupies one extra row of pixels on the right and bottom edges
* as compared to filling a figure that is bounded by that same rectangle.
* <li>If you draw a horizontal line along the same <i>y</i> coordinate as
* the baseline of a line of text, that line is drawn entirely below
* the text, except for any descenders.
* </ul><p>
* All coordinates that appear as arguments to the methods of this
* <code>Graphics</code> object are considered relative to the
* translation origin of this <code>Graphics</code> object prior to
* the invocation of the method.
* <p>
* All rendering operations modify only pixels which lie within the
* area bounded by the current clip, which is specified by a {@link Shape}
* in user space and is controlled by the program using the
* <code>Graphics</code> object. This <i>user clip</i>
* is transformed into device space and combined with the
* <i>device clip</i>, which is defined by the visibility of windows and
* device extents. The combination of the user clip and device clip
* defines the <i>composite clip</i>, which determines the final clipping
* region. The user clip cannot be modified by the rendering
* system to reflect the resulting composite clip. The user clip can only
* be changed through the <code>setClip</code> or <code>clipRect</code>
* methods.
* All drawing or writing is done in the current color,
* using the current paint mode, and in the current font.
*
* @author Sami Shaio
* @author Arthur van Hoff
* @see java.awt.Component
* @see java.awt.Graphics#clipRect(int, int, int, int)
* @see java.awt.Graphics#setColor(java.awt.Color)
* @see java.awt.Graphics#setPaintMode()
* @see java.awt.Graphics#setXORMode(java.awt.Color)
* @see java.awt.Graphics#setFont(java.awt.Font)
* @since JDK1.0
*/
public abstract class Graphics {
/** {@collect.stats}
* Constructs a new <code>Graphics</code> object.
* This constructor is the default contructor for a graphics
* context.
* <p>
* Since <code>Graphics</code> is an abstract class, applications
* cannot call this constructor directly. Graphics contexts are
* obtained from other graphics contexts or are created by calling
* <code>getGraphics</code> on a component.
* @see java.awt.Graphics#create()
* @see java.awt.Component#getGraphics
*/
protected Graphics() {
}
/** {@collect.stats}
* Creates a new <code>Graphics</code> object that is
* a copy of this <code>Graphics</code> object.
* @return a new graphics context that is a copy of
* this graphics context.
*/
public abstract Graphics create();
/** {@collect.stats}
* Creates a new <code>Graphics</code> object based on this
* <code>Graphics</code> object, but with a new translation and clip area.
* The new <code>Graphics</code> object has its origin
* translated to the specified point (<i>x</i>, <i>y</i>).
* Its clip area is determined by the intersection of the original
* clip area with the specified rectangle. The arguments are all
* interpreted in the coordinate system of the original
* <code>Graphics</code> object. The new graphics context is
* identical to the original, except in two respects:
* <p>
* <ul>
* <li>
* The new graphics context is translated by (<i>x</i>, <i>y</i>).
* That is to say, the point (<code>0</code>, <code>0</code>) in the
* new graphics context is the same as (<i>x</i>, <i>y</i>) in
* the original graphics context.
* <li>
* The new graphics context has an additional clipping rectangle, in
* addition to whatever (translated) clipping rectangle it inherited
* from the original graphics context. The origin of the new clipping
* rectangle is at (<code>0</code>, <code>0</code>), and its size
* is specified by the <code>width</code> and <code>height</code>
* arguments.
* </ul>
* <p>
* @param x the <i>x</i> coordinate.
* @param y the <i>y</i> coordinate.
* @param width the width of the clipping rectangle.
* @param height the height of the clipping rectangle.
* @return a new graphics context.
* @see java.awt.Graphics#translate
* @see java.awt.Graphics#clipRect
*/
public Graphics create(int x, int y, int width, int height) {
Graphics g = create();
if (g == null) return null;
g.translate(x, y);
g.clipRect(0, 0, width, height);
return g;
}
/** {@collect.stats}
* Translates the origin of the graphics context to the point
* (<i>x</i>, <i>y</i>) in the current coordinate system.
* Modifies this graphics context so that its new origin corresponds
* to the point (<i>x</i>, <i>y</i>) in this graphics context's
* original coordinate system. All coordinates used in subsequent
* rendering operations on this graphics context will be relative
* to this new origin.
* @param x the <i>x</i> coordinate.
* @param y the <i>y</i> coordinate.
*/
public abstract void translate(int x, int y);
/** {@collect.stats}
* Gets this graphics context's current color.
* @return this graphics context's current color.
* @see java.awt.Color
* @see java.awt.Graphics#setColor(Color)
*/
public abstract Color getColor();
/** {@collect.stats}
* Sets this graphics context's current color to the specified
* color. All subsequent graphics operations using this graphics
* context use this specified color.
* @param c the new rendering color.
* @see java.awt.Color
* @see java.awt.Graphics#getColor
*/
public abstract void setColor(Color c);
/** {@collect.stats}
* Sets the paint mode of this graphics context to overwrite the
* destination with this graphics context's current color.
* This sets the logical pixel operation function to the paint or
* overwrite mode. All subsequent rendering operations will
* overwrite the destination with the current color.
*/
public abstract void setPaintMode();
/** {@collect.stats}
* Sets the paint mode of this graphics context to alternate between
* this graphics context's current color and the new specified color.
* This specifies that logical pixel operations are performed in the
* XOR mode, which alternates pixels between the current color and
* a specified XOR color.
* <p>
* When drawing operations are performed, pixels which are the
* current color are changed to the specified color, and vice versa.
* <p>
* Pixels that are of colors other than those two colors are changed
* in an unpredictable but reversible manner; if the same figure is
* drawn twice, then all pixels are restored to their original values.
* @param c1 the XOR alternation color
*/
public abstract void setXORMode(Color c1);
/** {@collect.stats}
* Gets the current font.
* @return this graphics context's current font.
* @see java.awt.Font
* @see java.awt.Graphics#setFont(Font)
*/
public abstract Font getFont();
/** {@collect.stats}
* Sets this graphics context's font to the specified font.
* All subsequent text operations using this graphics context
* use this font. A null argument is silently ignored.
* @param font the font.
* @see java.awt.Graphics#getFont
* @see java.awt.Graphics#drawString(java.lang.String, int, int)
* @see java.awt.Graphics#drawBytes(byte[], int, int, int, int)
* @see java.awt.Graphics#drawChars(char[], int, int, int, int)
*/
public abstract void setFont(Font font);
/** {@collect.stats}
* Gets the font metrics of the current font.
* @return the font metrics of this graphics
* context's current font.
* @see java.awt.Graphics#getFont
* @see java.awt.FontMetrics
* @see java.awt.Graphics#getFontMetrics(Font)
*/
public FontMetrics getFontMetrics() {
return getFontMetrics(getFont());
}
/** {@collect.stats}
* Gets the font metrics for the specified font.
* @return the font metrics for the specified font.
* @param f the specified font
* @see java.awt.Graphics#getFont
* @see java.awt.FontMetrics
* @see java.awt.Graphics#getFontMetrics()
*/
public abstract FontMetrics getFontMetrics(Font f);
/** {@collect.stats}
* Returns the bounding rectangle of the current clipping area.
* This method refers to the user clip, which is independent of the
* clipping associated with device bounds and window visibility.
* If no clip has previously been set, or if the clip has been
* cleared using <code>setClip(null)</code>, this method returns
* <code>null</code>.
* The coordinates in the rectangle are relative to the coordinate
* system origin of this graphics context.
* @return the bounding rectangle of the current clipping area,
* or <code>null</code> if no clip is set.
* @see java.awt.Graphics#getClip
* @see java.awt.Graphics#clipRect
* @see java.awt.Graphics#setClip(int, int, int, int)
* @see java.awt.Graphics#setClip(Shape)
* @since JDK1.1
*/
public abstract Rectangle getClipBounds();
/** {@collect.stats}
* Intersects the current clip with the specified rectangle.
* The resulting clipping area is the intersection of the current
* clipping area and the specified rectangle. If there is no
* current clipping area, either because the clip has never been
* set, or the clip has been cleared using <code>setClip(null)</code>,
* the specified rectangle becomes the new clip.
* This method sets the user clip, which is independent of the
* clipping associated with device bounds and window visibility.
* This method can only be used to make the current clip smaller.
* To set the current clip larger, use any of the setClip methods.
* Rendering operations have no effect outside of the clipping area.
* @param x the x coordinate of the rectangle to intersect the clip with
* @param y the y coordinate of the rectangle to intersect the clip with
* @param width the width of the rectangle to intersect the clip with
* @param height the height of the rectangle to intersect the clip with
* @see #setClip(int, int, int, int)
* @see #setClip(Shape)
*/
public abstract void clipRect(int x, int y, int width, int height);
/** {@collect.stats}
* Sets the current clip to the rectangle specified by the given
* coordinates. This method sets the user clip, which is
* independent of the clipping associated with device bounds
* and window visibility.
* Rendering operations have no effect outside of the clipping area.
* @param x the <i>x</i> coordinate of the new clip rectangle.
* @param y the <i>y</i> coordinate of the new clip rectangle.
* @param width the width of the new clip rectangle.
* @param height the height of the new clip rectangle.
* @see java.awt.Graphics#clipRect
* @see java.awt.Graphics#setClip(Shape)
* @see java.awt.Graphics#getClip
* @since JDK1.1
*/
public abstract void setClip(int x, int y, int width, int height);
/** {@collect.stats}
* Gets the current clipping area.
* This method returns the user clip, which is independent of the
* clipping associated with device bounds and window visibility.
* If no clip has previously been set, or if the clip has been
* cleared using <code>setClip(null)</code>, this method returns
* <code>null</code>.
* @return a <code>Shape</code> object representing the
* current clipping area, or <code>null</code> if
* no clip is set.
* @see java.awt.Graphics#getClipBounds
* @see java.awt.Graphics#clipRect
* @see java.awt.Graphics#setClip(int, int, int, int)
* @see java.awt.Graphics#setClip(Shape)
* @since JDK1.1
*/
public abstract Shape getClip();
/** {@collect.stats}
* Sets the current clipping area to an arbitrary clip shape.
* Not all objects that implement the <code>Shape</code>
* interface can be used to set the clip. The only
* <code>Shape</code> objects that are guaranteed to be
* supported are <code>Shape</code> objects that are
* obtained via the <code>getClip</code> method and via
* <code>Rectangle</code> objects. This method sets the
* user clip, which is independent of the clipping associated
* with device bounds and window visibility.
* @param clip the <code>Shape</code> to use to set the clip
* @see java.awt.Graphics#getClip()
* @see java.awt.Graphics#clipRect
* @see java.awt.Graphics#setClip(int, int, int, int)
* @since JDK1.1
*/
public abstract void setClip(Shape clip);
/** {@collect.stats}
* Copies an area of the component by a distance specified by
* <code>dx</code> and <code>dy</code>. From the point specified
* by <code>x</code> and <code>y</code>, this method
* copies downwards and to the right. To copy an area of the
* component to the left or upwards, specify a negative value for
* <code>dx</code> or <code>dy</code>.
* If a portion of the source rectangle lies outside the bounds
* of the component, or is obscured by another window or component,
* <code>copyArea</code> will be unable to copy the associated
* pixels. The area that is omitted can be refreshed by calling
* the component's <code>paint</code> method.
* @param x the <i>x</i> coordinate of the source rectangle.
* @param y the <i>y</i> coordinate of the source rectangle.
* @param width the width of the source rectangle.
* @param height the height of the source rectangle.
* @param dx the horizontal distance to copy the pixels.
* @param dy the vertical distance to copy the pixels.
*/
public abstract void copyArea(int x, int y, int width, int height,
int dx, int dy);
/** {@collect.stats}
* Draws a line, using the current color, between the points
* <code>(x1, y1)</code> and <code>(x2, y2)</code>
* in this graphics context's coordinate system.
* @param x1 the first point's <i>x</i> coordinate.
* @param y1 the first point's <i>y</i> coordinate.
* @param x2 the second point's <i>x</i> coordinate.
* @param y2 the second point's <i>y</i> coordinate.
*/
public abstract void drawLine(int x1, int y1, int x2, int y2);
/** {@collect.stats}
* Fills the specified rectangle.
* The left and right edges of the rectangle are at
* <code>x</code> and <code>x + width - 1</code>.
* The top and bottom edges are at
* <code>y</code> and <code>y + height - 1</code>.
* The resulting rectangle covers an area
* <code>width</code> pixels wide by
* <code>height</code> pixels tall.
* The rectangle is filled using the graphics context's current color.
* @param x the <i>x</i> coordinate
* of the rectangle to be filled.
* @param y the <i>y</i> coordinate
* of the rectangle to be filled.
* @param width the width of the rectangle to be filled.
* @param height the height of the rectangle to be filled.
* @see java.awt.Graphics#clearRect
* @see java.awt.Graphics#drawRect
*/
public abstract void fillRect(int x, int y, int width, int height);
/** {@collect.stats}
* Draws the outline of the specified rectangle.
* The left and right edges of the rectangle are at
* <code>x</code> and <code>x + width</code>.
* The top and bottom edges are at
* <code>y</code> and <code>y + height</code>.
* The rectangle is drawn using the graphics context's current color.
* @param x the <i>x</i> coordinate
* of the rectangle to be drawn.
* @param y the <i>y</i> coordinate
* of the rectangle to be drawn.
* @param width the width of the rectangle to be drawn.
* @param height the height of the rectangle to be drawn.
* @see java.awt.Graphics#fillRect
* @see java.awt.Graphics#clearRect
*/
public void drawRect(int x, int y, int width, int height) {
if ((width < 0) || (height < 0)) {
return;
}
if (height == 0 || width == 0) {
drawLine(x, y, x + width, y + height);
} else {
drawLine(x, y, x + width - 1, y);
drawLine(x + width, y, x + width, y + height - 1);
drawLine(x + width, y + height, x + 1, y + height);
drawLine(x, y + height, x, y + 1);
}
}
/** {@collect.stats}
* Clears the specified rectangle by filling it with the background
* color of the current drawing surface. This operation does not
* use the current paint mode.
* <p>
* Beginning with Java 1.1, the background color
* of offscreen images may be system dependent. Applications should
* use <code>setColor</code> followed by <code>fillRect</code> to
* ensure that an offscreen image is cleared to a specific color.
* @param x the <i>x</i> coordinate of the rectangle to clear.
* @param y the <i>y</i> coordinate of the rectangle to clear.
* @param width the width of the rectangle to clear.
* @param height the height of the rectangle to clear.
* @see java.awt.Graphics#fillRect(int, int, int, int)
* @see java.awt.Graphics#drawRect
* @see java.awt.Graphics#setColor(java.awt.Color)
* @see java.awt.Graphics#setPaintMode
* @see java.awt.Graphics#setXORMode(java.awt.Color)
*/
public abstract void clearRect(int x, int y, int width, int height);
/** {@collect.stats}
* Draws an outlined round-cornered rectangle using this graphics
* context's current color. The left and right edges of the rectangle
* are at <code>x</code> and <code>x + width</code>,
* respectively. The top and bottom edges of the rectangle are at
* <code>y</code> and <code>y + height</code>.
* @param x the <i>x</i> coordinate of the rectangle to be drawn.
* @param y the <i>y</i> coordinate of the rectangle to be drawn.
* @param width the width of the rectangle to be drawn.
* @param height the height of the rectangle to be drawn.
* @param arcWidth the horizontal diameter of the arc
* at the four corners.
* @param arcHeight the vertical diameter of the arc
* at the four corners.
* @see java.awt.Graphics#fillRoundRect
*/
public abstract void drawRoundRect(int x, int y, int width, int height,
int arcWidth, int arcHeight);
/** {@collect.stats}
* Fills the specified rounded corner rectangle with the current color.
* The left and right edges of the rectangle
* are at <code>x</code> and <code>x + width - 1</code>,
* respectively. The top and bottom edges of the rectangle are at
* <code>y</code> and <code>y + height - 1</code>.
* @param x the <i>x</i> coordinate of the rectangle to be filled.
* @param y the <i>y</i> coordinate of the rectangle to be filled.
* @param width the width of the rectangle to be filled.
* @param height the height of the rectangle to be filled.
* @param arcWidth the horizontal diameter
* of the arc at the four corners.
* @param arcHeight the vertical diameter
* of the arc at the four corners.
* @see java.awt.Graphics#drawRoundRect
*/
public abstract void fillRoundRect(int x, int y, int width, int height,
int arcWidth, int arcHeight);
/** {@collect.stats}
* Draws a 3-D highlighted outline of the specified rectangle.
* The edges of the rectangle are highlighted so that they
* appear to be beveled and lit from the upper left corner.
* <p>
* The colors used for the highlighting effect are determined
* based on the current color.
* The resulting rectangle covers an area that is
* <code>width + 1</code> pixels wide
* by <code>height + 1</code> pixels tall.
* @param x the <i>x</i> coordinate of the rectangle to be drawn.
* @param y the <i>y</i> coordinate of the rectangle to be drawn.
* @param width the width of the rectangle to be drawn.
* @param height the height of the rectangle to be drawn.
* @param raised a boolean that determines whether the rectangle
* appears to be raised above the surface
* or sunk into the surface.
* @see java.awt.Graphics#fill3DRect
*/
public void draw3DRect(int x, int y, int width, int height,
boolean raised) {
Color c = getColor();
Color brighter = c.brighter();
Color darker = c.darker();
setColor(raised ? brighter : darker);
drawLine(x, y, x, y + height);
drawLine(x + 1, y, x + width - 1, y);
setColor(raised ? darker : brighter);
drawLine(x + 1, y + height, x + width, y + height);
drawLine(x + width, y, x + width, y + height - 1);
setColor(c);
}
/** {@collect.stats}
* Paints a 3-D highlighted rectangle filled with the current color.
* The edges of the rectangle will be highlighted so that it appears
* as if the edges were beveled and lit from the upper left corner.
* The colors used for the highlighting effect will be determined from
* the current color.
* @param x the <i>x</i> coordinate of the rectangle to be filled.
* @param y the <i>y</i> coordinate of the rectangle to be filled.
* @param width the width of the rectangle to be filled.
* @param height the height of the rectangle to be filled.
* @param raised a boolean value that determines whether the
* rectangle appears to be raised above the surface
* or etched into the surface.
* @see java.awt.Graphics#draw3DRect
*/
public void fill3DRect(int x, int y, int width, int height,
boolean raised) {
Color c = getColor();
Color brighter = c.brighter();
Color darker = c.darker();
if (!raised) {
setColor(darker);
}
fillRect(x+1, y+1, width-2, height-2);
setColor(raised ? brighter : darker);
drawLine(x, y, x, y + height - 1);
drawLine(x + 1, y, x + width - 2, y);
setColor(raised ? darker : brighter);
drawLine(x + 1, y + height - 1, x + width - 1, y + height - 1);
drawLine(x + width - 1, y, x + width - 1, y + height - 2);
setColor(c);
}
/** {@collect.stats}
* Draws the outline of an oval.
* The result is a circle or ellipse that fits within the
* rectangle specified by the <code>x</code>, <code>y</code>,
* <code>width</code>, and <code>height</code> arguments.
* <p>
* The oval covers an area that is
* <code>width + 1</code> pixels wide
* and <code>height + 1</code> pixels tall.
* @param x the <i>x</i> coordinate of the upper left
* corner of the oval to be drawn.
* @param y the <i>y</i> coordinate of the upper left
* corner of the oval to be drawn.
* @param width the width of the oval to be drawn.
* @param height the height of the oval to be drawn.
* @see java.awt.Graphics#fillOval
*/
public abstract void drawOval(int x, int y, int width, int height);
/** {@collect.stats}
* Fills an oval bounded by the specified rectangle with the
* current color.
* @param x the <i>x</i> coordinate of the upper left corner
* of the oval to be filled.
* @param y the <i>y</i> coordinate of the upper left corner
* of the oval to be filled.
* @param width the width of the oval to be filled.
* @param height the height of the oval to be filled.
* @see java.awt.Graphics#drawOval
*/
public abstract void fillOval(int x, int y, int width, int height);
/** {@collect.stats}
* Draws the outline of a circular or elliptical arc
* covering the specified rectangle.
* <p>
* The resulting arc begins at <code>startAngle</code> and extends
* for <code>arcAngle</code> degrees, using the current color.
* Angles are interpreted such that 0 degrees
* is at the 3 o'clock position.
* A positive value indicates a counter-clockwise rotation
* while a negative value indicates a clockwise rotation.
* <p>
* The center of the arc is the center of the rectangle whose origin
* is (<i>x</i>, <i>y</i>) and whose size is specified by the
* <code>width</code> and <code>height</code> arguments.
* <p>
* The resulting arc covers an area
* <code>width + 1</code> pixels wide
* by <code>height + 1</code> pixels tall.
* <p>
* The angles are specified relative to the non-square extents of
* the bounding rectangle such that 45 degrees always falls on the
* line from the center of the ellipse to the upper right corner of
* the bounding rectangle. As a result, if the bounding rectangle is
* noticeably longer in one axis than the other, the angles to the
* start and end of the arc segment will be skewed farther along the
* longer axis of the bounds.
* @param x the <i>x</i> coordinate of the
* upper-left corner of the arc to be drawn.
* @param y the <i>y</i> coordinate of the
* upper-left corner of the arc to be drawn.
* @param width the width of the arc to be drawn.
* @param height the height of the arc to be drawn.
* @param startAngle the beginning angle.
* @param arcAngle the angular extent of the arc,
* relative to the start angle.
* @see java.awt.Graphics#fillArc
*/
public abstract void drawArc(int x, int y, int width, int height,
int startAngle, int arcAngle);
/** {@collect.stats}
* Fills a circular or elliptical arc covering the specified rectangle.
* <p>
* The resulting arc begins at <code>startAngle</code> and extends
* for <code>arcAngle</code> degrees.
* Angles are interpreted such that 0 degrees
* is at the 3 o'clock position.
* A positive value indicates a counter-clockwise rotation
* while a negative value indicates a clockwise rotation.
* <p>
* The center of the arc is the center of the rectangle whose origin
* is (<i>x</i>, <i>y</i>) and whose size is specified by the
* <code>width</code> and <code>height</code> arguments.
* <p>
* The resulting arc covers an area
* <code>width + 1</code> pixels wide
* by <code>height + 1</code> pixels tall.
* <p>
* The angles are specified relative to the non-square extents of
* the bounding rectangle such that 45 degrees always falls on the
* line from the center of the ellipse to the upper right corner of
* the bounding rectangle. As a result, if the bounding rectangle is
* noticeably longer in one axis than the other, the angles to the
* start and end of the arc segment will be skewed farther along the
* longer axis of the bounds.
* @param x the <i>x</i> coordinate of the
* upper-left corner of the arc to be filled.
* @param y the <i>y</i> coordinate of the
* upper-left corner of the arc to be filled.
* @param width the width of the arc to be filled.
* @param height the height of the arc to be filled.
* @param startAngle the beginning angle.
* @param arcAngle the angular extent of the arc,
* relative to the start angle.
* @see java.awt.Graphics#drawArc
*/
public abstract void fillArc(int x, int y, int width, int height,
int startAngle, int arcAngle);
/** {@collect.stats}
* Draws a sequence of connected lines defined by
* arrays of <i>x</i> and <i>y</i> coordinates.
* Each pair of (<i>x</i>, <i>y</i>) coordinates defines a point.
* The figure is not closed if the first point
* differs from the last point.
* @param xPoints an array of <i>x</i> points
* @param yPoints an array of <i>y</i> points
* @param nPoints the total number of points
* @see java.awt.Graphics#drawPolygon(int[], int[], int)
* @since JDK1.1
*/
public abstract void drawPolyline(int xPoints[], int yPoints[],
int nPoints);
/** {@collect.stats}
* Draws a closed polygon defined by
* arrays of <i>x</i> and <i>y</i> coordinates.
* Each pair of (<i>x</i>, <i>y</i>) coordinates defines a point.
* <p>
* This method draws the polygon defined by <code>nPoint</code> line
* segments, where the first <code>nPoint - 1</code>
* line segments are line segments from
* <code>(xPoints[i - 1], yPoints[i - 1])</code>
* to <code>(xPoints[i], yPoints[i])</code>, for
* 1 ≤ <i>i</i> ≤ <code>nPoints</code>.
* The figure is automatically closed by drawing a line connecting
* the final point to the first point, if those points are different.
* @param xPoints a an array of <code>x</code> coordinates.
* @param yPoints a an array of <code>y</code> coordinates.
* @param nPoints a the total number of points.
* @see java.awt.Graphics#fillPolygon
* @see java.awt.Graphics#drawPolyline
*/
public abstract void drawPolygon(int xPoints[], int yPoints[],
int nPoints);
/** {@collect.stats}
* Draws the outline of a polygon defined by the specified
* <code>Polygon</code> object.
* @param p the polygon to draw.
* @see java.awt.Graphics#fillPolygon
* @see java.awt.Graphics#drawPolyline
*/
public void drawPolygon(Polygon p) {
drawPolygon(p.xpoints, p.ypoints, p.npoints);
}
/** {@collect.stats}
* Fills a closed polygon defined by
* arrays of <i>x</i> and <i>y</i> coordinates.
* <p>
* This method draws the polygon defined by <code>nPoint</code> line
* segments, where the first <code>nPoint - 1</code>
* line segments are line segments from
* <code>(xPoints[i - 1], yPoints[i - 1])</code>
* to <code>(xPoints[i], yPoints[i])</code>, for
* 1 ≤ <i>i</i> ≤ <code>nPoints</code>.
* The figure is automatically closed by drawing a line connecting
* the final point to the first point, if those points are different.
* <p>
* The area inside the polygon is defined using an
* even-odd fill rule, also known as the alternating rule.
* @param xPoints a an array of <code>x</code> coordinates.
* @param yPoints a an array of <code>y</code> coordinates.
* @param nPoints a the total number of points.
* @see java.awt.Graphics#drawPolygon(int[], int[], int)
*/
public abstract void fillPolygon(int xPoints[], int yPoints[],
int nPoints);
/** {@collect.stats}
* Fills the polygon defined by the specified Polygon object with
* the graphics context's current color.
* <p>
* The area inside the polygon is defined using an
* even-odd fill rule, also known as the alternating rule.
* @param p the polygon to fill.
* @see java.awt.Graphics#drawPolygon(int[], int[], int)
*/
public void fillPolygon(Polygon p) {
fillPolygon(p.xpoints, p.ypoints, p.npoints);
}
/** {@collect.stats}
* Draws the text given by the specified string, using this
* graphics context's current font and color. The baseline of the
* leftmost character is at position (<i>x</i>, <i>y</i>) in this
* graphics context's coordinate system.
* @param str the string to be drawn.
* @param x the <i>x</i> coordinate.
* @param y the <i>y</i> coordinate.
* @throws NullPointerException if <code>str</code> is <code>null</code>.
* @see java.awt.Graphics#drawBytes
* @see java.awt.Graphics#drawChars
*/
public abstract void drawString(String str, int x, int y);
/** {@collect.stats}
* Renders the text of the specified iterator applying its attributes
* in accordance with the specification of the
* {@link java.awt.font.TextAttribute TextAttribute} class.
* <p>
* The baseline of the leftmost character is at position
* (<i>x</i>, <i>y</i>) in this graphics context's coordinate system.
* @param iterator the iterator whose text is to be drawn
* @param x the <i>x</i> coordinate.
* @param y the <i>y</i> coordinate.
* @throws NullPointerException if <code>iterator</code> is
* <code>null</code>.
* @see java.awt.Graphics#drawBytes
* @see java.awt.Graphics#drawChars
*/
public abstract void drawString(AttributedCharacterIterator iterator,
int x, int y);
/** {@collect.stats}
* Draws the text given by the specified character array, using this
* graphics context's current font and color. The baseline of the
* first character is at position (<i>x</i>, <i>y</i>) in this
* graphics context's coordinate system.
* @param data the array of characters to be drawn
* @param offset the start offset in the data
* @param length the number of characters to be drawn
* @param x the <i>x</i> coordinate of the baseline of the text
* @param y the <i>y</i> coordinate of the baseline of the text
* @throws NullPointerException if <code>data</code> is <code>null</code>.
* @throws IndexOutOfBoundsException if <code>offset</code> or
* <code>length</code>is less than zero, or
* <code>offset+length</code> is greater than the length of the
* <code>data</code> array.
* @see java.awt.Graphics#drawBytes
* @see java.awt.Graphics#drawString
*/
public void drawChars(char data[], int offset, int length, int x, int y) {
drawString(new String(data, offset, length), x, y);
}
/** {@collect.stats}
* Draws the text given by the specified byte array, using this
* graphics context's current font and color. The baseline of the
* first character is at position (<i>x</i>, <i>y</i>) in this
* graphics context's coordinate system.
* <p>
* Use of this method is not recommended as each byte is interpreted
* as a Unicode code point in the range 0 to 255, and so can only be
* used to draw Latin characters in that range.
* @param data the data to be drawn
* @param offset the start offset in the data
* @param length the number of bytes that are drawn
* @param x the <i>x</i> coordinate of the baseline of the text
* @param y the <i>y</i> coordinate of the baseline of the text
* @throws NullPointerException if <code>data</code> is <code>null</code>.
* @throws IndexOutOfBoundsException if <code>offset</code> or
* <code>length</code>is less than zero, or <code>offset+length</code>
* is greater than the length of the <code>data</code> array.
* @see java.awt.Graphics#drawChars
* @see java.awt.Graphics#drawString
*/
public void drawBytes(byte data[], int offset, int length, int x, int y) {
drawString(new String(data, 0, offset, length), x, y);
}
/** {@collect.stats}
* Draws as much of the specified image as is currently available.
* The image is drawn with its top-left corner at
* (<i>x</i>, <i>y</i>) in this graphics context's coordinate
* space. Transparent pixels in the image do not affect whatever
* pixels are already there.
* <p>
* This method returns immediately in all cases, even if the
* complete image has not yet been loaded, and it has not been dithered
* and converted for the current output device.
* <p>
* If the image has completely loaded and its pixels are
* no longer being changed, then
* <code>drawImage</code> returns <code>true</code>.
* Otherwise, <code>drawImage</code> returns <code>false</code>
* and as more of
* the image becomes available
* or it is time to draw another frame of animation,
* the process that loads the image notifies
* the specified image observer.
* @param img the specified image to be drawn. This method does
* nothing if <code>img</code> is null.
* @param x the <i>x</i> coordinate.
* @param y the <i>y</i> coordinate.
* @param observer object to be notified as more of
* the image is converted.
* @return <code>false</code> if the image pixels are still changing;
* <code>true</code> otherwise.
* @see java.awt.Image
* @see java.awt.image.ImageObserver
* @see java.awt.image.ImageObserver#imageUpdate(java.awt.Image, int, int, int, int, int)
*/
public abstract boolean drawImage(Image img, int x, int y,
ImageObserver observer);
/** {@collect.stats}
* Draws as much of the specified image as has already been scaled
* to fit inside the specified rectangle.
* <p>
* The image is drawn inside the specified rectangle of this
* graphics context's coordinate space, and is scaled if
* necessary. Transparent pixels do not affect whatever pixels
* are already there.
* <p>
* This method returns immediately in all cases, even if the
* entire image has not yet been scaled, dithered, and converted
* for the current output device.
* If the current output representation is not yet complete, then
* <code>drawImage</code> returns <code>false</code>. As more of
* the image becomes available, the process that loads the image notifies
* the image observer by calling its <code>imageUpdate</code> method.
* <p>
* A scaled version of an image will not necessarily be
* available immediately just because an unscaled version of the
* image has been constructed for this output device. Each size of
* the image may be cached separately and generated from the original
* data in a separate image production sequence.
* @param img the specified image to be drawn. This method does
* nothing if <code>img</code> is null.
* @param x the <i>x</i> coordinate.
* @param y the <i>y</i> coordinate.
* @param width the width of the rectangle.
* @param height the height of the rectangle.
* @param observer object to be notified as more of
* the image is converted.
* @return <code>false</code> if the image pixels are still changing;
* <code>true</code> otherwise.
* @see java.awt.Image
* @see java.awt.image.ImageObserver
* @see java.awt.image.ImageObserver#imageUpdate(java.awt.Image, int, int, int, int, int)
*/
public abstract boolean drawImage(Image img, int x, int y,
int width, int height,
ImageObserver observer);
/** {@collect.stats}
* Draws as much of the specified image as is currently available.
* The image is drawn with its top-left corner at
* (<i>x</i>, <i>y</i>) in this graphics context's coordinate
* space. Transparent pixels are drawn in the specified
* background color.
* <p>
* This operation is equivalent to filling a rectangle of the
* width and height of the specified image with the given color and then
* drawing the image on top of it, but possibly more efficient.
* <p>
* This method returns immediately in all cases, even if the
* complete image has not yet been loaded, and it has not been dithered
* and converted for the current output device.
* <p>
* If the image has completely loaded and its pixels are
* no longer being changed, then
* <code>drawImage</code> returns <code>true</code>.
* Otherwise, <code>drawImage</code> returns <code>false</code>
* and as more of
* the image becomes available
* or it is time to draw another frame of animation,
* the process that loads the image notifies
* the specified image observer.
* @param img the specified image to be drawn. This method does
* nothing if <code>img</code> is null.
* @param x the <i>x</i> coordinate.
* @param y the <i>y</i> coordinate.
* @param bgcolor the background color to paint under the
* non-opaque portions of the image.
* @param observer object to be notified as more of
* the image is converted.
* @return <code>false</code> if the image pixels are still changing;
* <code>true</code> otherwise.
* @see java.awt.Image
* @see java.awt.image.ImageObserver
* @see java.awt.image.ImageObserver#imageUpdate(java.awt.Image, int, int, int, int, int)
*/
public abstract boolean drawImage(Image img, int x, int y,
Color bgcolor,
ImageObserver observer);
/** {@collect.stats}
* Draws as much of the specified image as has already been scaled
* to fit inside the specified rectangle.
* <p>
* The image is drawn inside the specified rectangle of this
* graphics context's coordinate space, and is scaled if
* necessary. Transparent pixels are drawn in the specified
* background color.
* This operation is equivalent to filling a rectangle of the
* width and height of the specified image with the given color and then
* drawing the image on top of it, but possibly more efficient.
* <p>
* This method returns immediately in all cases, even if the
* entire image has not yet been scaled, dithered, and converted
* for the current output device.
* If the current output representation is not yet complete then
* <code>drawImage</code> returns <code>false</code>. As more of
* the image becomes available, the process that loads the image notifies
* the specified image observer.
* <p>
* A scaled version of an image will not necessarily be
* available immediately just because an unscaled version of the
* image has been constructed for this output device. Each size of
* the image may be cached separately and generated from the original
* data in a separate image production sequence.
* @param img the specified image to be drawn. This method does
* nothing if <code>img</code> is null.
* @param x the <i>x</i> coordinate.
* @param y the <i>y</i> coordinate.
* @param width the width of the rectangle.
* @param height the height of the rectangle.
* @param bgcolor the background color to paint under the
* non-opaque portions of the image.
* @param observer object to be notified as more of
* the image is converted.
* @return <code>false</code> if the image pixels are still changing;
* <code>true</code> otherwise.
* @see java.awt.Image
* @see java.awt.image.ImageObserver
* @see java.awt.image.ImageObserver#imageUpdate(java.awt.Image, int, int, int, int, int)
*/
public abstract boolean drawImage(Image img, int x, int y,
int width, int height,
Color bgcolor,
ImageObserver observer);
/** {@collect.stats}
* Draws as much of the specified area of the specified image as is
* currently available, scaling it on the fly to fit inside the
* specified area of the destination drawable surface. Transparent pixels
* do not affect whatever pixels are already there.
* <p>
* This method returns immediately in all cases, even if the
* image area to be drawn has not yet been scaled, dithered, and converted
* for the current output device.
* If the current output representation is not yet complete then
* <code>drawImage</code> returns <code>false</code>. As more of
* the image becomes available, the process that loads the image notifies
* the specified image observer.
* <p>
* This method always uses the unscaled version of the image
* to render the scaled rectangle and performs the required
* scaling on the fly. It does not use a cached, scaled version
* of the image for this operation. Scaling of the image from source
* to destination is performed such that the first coordinate
* of the source rectangle is mapped to the first coordinate of
* the destination rectangle, and the second source coordinate is
* mapped to the second destination coordinate. The subimage is
* scaled and flipped as needed to preserve those mappings.
* @param img the specified image to be drawn. This method does
* nothing if <code>img</code> is null.
* @param dx1 the <i>x</i> coordinate of the first corner of the
* destination rectangle.
* @param dy1 the <i>y</i> coordinate of the first corner of the
* destination rectangle.
* @param dx2 the <i>x</i> coordinate of the second corner of the
* destination rectangle.
* @param dy2 the <i>y</i> coordinate of the second corner of the
* destination rectangle.
* @param sx1 the <i>x</i> coordinate of the first corner of the
* source rectangle.
* @param sy1 the <i>y</i> coordinate of the first corner of the
* source rectangle.
* @param sx2 the <i>x</i> coordinate of the second corner of the
* source rectangle.
* @param sy2 the <i>y</i> coordinate of the second corner of the
* source rectangle.
* @param observer object to be notified as more of the image is
* scaled and converted.
* @return <code>false</code> if the image pixels are still changing;
* <code>true</code> otherwise.
* @see java.awt.Image
* @see java.awt.image.ImageObserver
* @see java.awt.image.ImageObserver#imageUpdate(java.awt.Image, int, int, int, int, int)
* @since JDK1.1
*/
public abstract boolean drawImage(Image img,
int dx1, int dy1, int dx2, int dy2,
int sx1, int sy1, int sx2, int sy2,
ImageObserver observer);
/** {@collect.stats}
* Draws as much of the specified area of the specified image as is
* currently available, scaling it on the fly to fit inside the
* specified area of the destination drawable surface.
* <p>
* Transparent pixels are drawn in the specified background color.
* This operation is equivalent to filling a rectangle of the
* width and height of the specified image with the given color and then
* drawing the image on top of it, but possibly more efficient.
* <p>
* This method returns immediately in all cases, even if the
* image area to be drawn has not yet been scaled, dithered, and converted
* for the current output device.
* If the current output representation is not yet complete then
* <code>drawImage</code> returns <code>false</code>. As more of
* the image becomes available, the process that loads the image notifies
* the specified image observer.
* <p>
* This method always uses the unscaled version of the image
* to render the scaled rectangle and performs the required
* scaling on the fly. It does not use a cached, scaled version
* of the image for this operation. Scaling of the image from source
* to destination is performed such that the first coordinate
* of the source rectangle is mapped to the first coordinate of
* the destination rectangle, and the second source coordinate is
* mapped to the second destination coordinate. The subimage is
* scaled and flipped as needed to preserve those mappings.
* @param img the specified image to be drawn. This method does
* nothing if <code>img</code> is null.
* @param dx1 the <i>x</i> coordinate of the first corner of the
* destination rectangle.
* @param dy1 the <i>y</i> coordinate of the first corner of the
* destination rectangle.
* @param dx2 the <i>x</i> coordinate of the second corner of the
* destination rectangle.
* @param dy2 the <i>y</i> coordinate of the second corner of the
* destination rectangle.
* @param sx1 the <i>x</i> coordinate of the first corner of the
* source rectangle.
* @param sy1 the <i>y</i> coordinate of the first corner of the
* source rectangle.
* @param sx2 the <i>x</i> coordinate of the second corner of the
* source rectangle.
* @param sy2 the <i>y</i> coordinate of the second corner of the
* source rectangle.
* @param bgcolor the background color to paint under the
* non-opaque portions of the image.
* @param observer object to be notified as more of the image is
* scaled and converted.
* @return <code>false</code> if the image pixels are still changing;
* <code>true</code> otherwise.
* @see java.awt.Image
* @see java.awt.image.ImageObserver
* @see java.awt.image.ImageObserver#imageUpdate(java.awt.Image, int, int, int, int, int)
* @since JDK1.1
*/
public abstract boolean drawImage(Image img,
int dx1, int dy1, int dx2, int dy2,
int sx1, int sy1, int sx2, int sy2,
Color bgcolor,
ImageObserver observer);
/** {@collect.stats}
* Disposes of this graphics context and releases
* any system resources that it is using.
* A <code>Graphics</code> object cannot be used after
* <code>dispose</code>has been called.
* <p>
* When a Java program runs, a large number of <code>Graphics</code>
* objects can be created within a short time frame.
* Although the finalization process of the garbage collector
* also disposes of the same system resources, it is preferable
* to manually free the associated resources by calling this
* method rather than to rely on a finalization process which
* may not run to completion for a long period of time.
* <p>
* Graphics objects which are provided as arguments to the
* <code>paint</code> and <code>update</code> methods
* of components are automatically released by the system when
* those methods return. For efficiency, programmers should
* call <code>dispose</code> when finished using
* a <code>Graphics</code> object only if it was created
* directly from a component or another <code>Graphics</code> object.
* @see java.awt.Graphics#finalize
* @see java.awt.Component#paint
* @see java.awt.Component#update
* @see java.awt.Component#getGraphics
* @see java.awt.Graphics#create
*/
public abstract void dispose();
/** {@collect.stats}
* Disposes of this graphics context once it is no longer referenced.
* @see #dispose
*/
public void finalize() {
dispose();
}
/** {@collect.stats}
* Returns a <code>String</code> object representing this
* <code>Graphics</code> object's value.
* @return a string representation of this graphics context.
*/
public String toString() {
return getClass().getName() + "[font=" + getFont() + ",color=" + getColor() + "]";
}
/** {@collect.stats}
* Returns the bounding rectangle of the current clipping area.
* @return the bounding rectangle of the current clipping area
* or <code>null</code> if no clip is set.
* @deprecated As of JDK version 1.1,
* replaced by <code>getClipBounds()</code>.
*/
@Deprecated
public Rectangle getClipRect() {
return getClipBounds();
}
/** {@collect.stats}
* Returns true if the specified rectangular area might intersect
* the current clipping area.
* The coordinates of the specified rectangular area are in the
* user coordinate space and are relative to the coordinate
* system origin of this graphics context.
* This method may use an algorithm that calculates a result quickly
* but which sometimes might return true even if the specified
* rectangular area does not intersect the clipping area.
* The specific algorithm employed may thus trade off accuracy for
* speed, but it will never return false unless it can guarantee
* that the specified rectangular area does not intersect the
* current clipping area.
* The clipping area used by this method can represent the
* intersection of the user clip as specified through the clip
* methods of this graphics context as well as the clipping
* associated with the device or image bounds and window visibility.
*
* @param x the x coordinate of the rectangle to test against the clip
* @param y the y coordinate of the rectangle to test against the clip
* @param width the width of the rectangle to test against the clip
* @param height the height of the rectangle to test against the clip
* @return <code>true</code> if the specified rectangle intersects
* the bounds of the current clip; <code>false</code>
* otherwise.
*/
public boolean hitClip(int x, int y, int width, int height) {
// Note, this implementation is not very efficient.
// Subclasses should override this method and calculate
// the results more directly.
Rectangle clipRect = getClipBounds();
if (clipRect == null) {
return true;
}
return clipRect.intersects(x, y, width, height);
}
/** {@collect.stats}
* Returns the bounding rectangle of the current clipping area.
* The coordinates in the rectangle are relative to the coordinate
* system origin of this graphics context. This method differs
* from {@link #getClipBounds() getClipBounds} in that an existing
* rectangle is used instead of allocating a new one.
* This method refers to the user clip, which is independent of the
* clipping associated with device bounds and window visibility.
* If no clip has previously been set, or if the clip has been
* cleared using <code>setClip(null)</code>, this method returns the
* specified <code>Rectangle</code>.
* @param r the rectangle where the current clipping area is
* copied to. Any current values in this rectangle are
* overwritten.
* @return the bounding rectangle of the current clipping area.
*/
public Rectangle getClipBounds(Rectangle r) {
// Note, this implementation is not very efficient.
// Subclasses should override this method and avoid
// the allocation overhead of getClipBounds().
Rectangle clipRect = getClipBounds();
if (clipRect != null) {
r.x = clipRect.x;
r.y = clipRect.y;
r.width = clipRect.width;
r.height = clipRect.height;
} else if (r == null) {
throw new NullPointerException("null rectangle parameter");
}
return r;
}
}
|
Java
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.