|
Generated by JDiff |
||||||||
PREV PACKAGE NEXT PACKAGE FRAMES NO FRAMES |
This file contains all the changes in documentation in the packagejava.awt
as colored differences. Deletions are shownlike this, and additions are shown like this.
If no deletions or additions are shown in an entry, the HTML tags will be what has changed. The new HTML tags are shown in the differences. If no documentation existed, and then some was added in a later version, this change is noted in the appropriate class pages of differences, but the change is not shown on this page. Only changes in existing text are shown here. Similarly, documentation which was inherited from another class or interface is not shown here.
Note that an HTML error in the new documentation may cause the display of other documentation changes to be presented incorrectly. For instance, failure to close a <code> tag will cause all subsequent paragraphs to be displayed differently.
Thrown when a serious Abstract Window Toolkit error has occurred. @version 1.10 0912 02/2102/9800 @author Arthur van Hoff
The root event class for all AWT events. This class and its subclasses supercede the original java.awt.Event class. Subclasses of this root AWTEvent class defined outside of the java.awt.event package should define event ID values greater than the value defined by RESERVED_ID_MAX.The event masks defined in this class are needed
ONLYbycomponentComponent subclasses which are using Component.enableEvents() to select for event types not selected by registered listeners. If a listener is registered on a component the appropriate event mask is already set internally by the component.The masks are also used to specify to which types of events an AWTEventListener should listen. The masks are bitwise-ORed together and passed to Toolkit.addAWTEventListener. @see Component#enableEvents @see Toolkit#addAWTEventListener @see java.awt.event.ActionEvent @see java.awt.event.AdjustmentEvent @see java.awt.event.ComponentEvent @see java.awt.event.ContainerEvent @see java.awt.event.FocusEvent @see java.awt.event.
KeyEventInputMethodEvent @see java.awt.event.MouseEventInvocationEvent @see java.awt.event.WindowEventItemEvent @see java.awt.event.ActionEventHierarchyEvent @see java.awt.event.AdjustmentEventKeyEvent @see java.awt.event.ItemEventMouseEvent @see java.awt.event.TextEventPaintEvent @versionsee1java.33awt.event.TextEvent10/05/98@see java.awt.event.WindowEvent @author Carl Quinn @author Amy Fowler @version 1.38 02/11/00 @since 1.1
A class which implements efficient and thread-safe multi-cast event dispatching for the AWT events defined in the java.awt.event package. This class will manage an immutable structure consisting of a chain of event listeners and will dispatch events to those listeners. Because the structure is immutable it is safe to use this API to add/remove listeners during the process of an event dispatch operation. An example of how this class could be used to implement a new component which fires "action" events:@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 if (actionListener = null) { actionListener.actionPerformed(new ActionEvent()); } }
version 1.20 04/22/99 @author John Rose @author Amy Fowler @version 1.25 02/02/00 @since 1.1
Signals that an Absract Window Toolkit exception has occurred. @version 1.11 0913 02/2102/9800 @author Arthur van Hoff
This class is for AWT permissions. An AWTPermission contains a target name but no actions list; you either have the named permission or you don't.The target name is the name of the AWT permission (see below). The naming convention follows the hierarchical property naming convention. Also an asterisk could be used to represent all AWT permissions.
The following table lists all the possible AWTPermission target names and for each provides a description of what the permission allows and a discussion of the risks of granting code the permission.
@see java.security.BasicPermission @see java.security.Permission @see java.security.Permissions @see java.security.PermissionCollection @see java.lang.SecurityManager @version 1.
Permission Target Name What the Permission Allows Risks of Allowing this Permission accessClipboard Posting and retrieval of information to and from the AWT clipboard This would allow malfeasant code to share potentially sensitive or confidential information. accessEventQueue Access to the AWT event queue After retrieving the AWT event queue malicious code may peek at and even remove existing events from its event queue as well as post bogus events which may purposefully cause the application or applet to misbehave in an insecure manner. listenToAllAWTEvents Listen to all AWT events system-wide After adding an AWT event listener malicious code may scan all AWT events dispatched in the system allowing it to read all user input (such as passwords). Each AWT event listener is called from within the context of that event queue's EventDispatchThread so if the accessEventQueue permission is also enabled malicious code could modify the contents of AWT event queues system-wide causing the application or applet to misbehave in an insecure manner. showWindowWithoutWarningBanner Display of a window without also displaying a banner warning that the window was created by an applet Without this warning an applet may pop up windows without the user knowing that they belong to an applet. Since users may make security-sensitive decisions based on whether or not the window belongs to an applet (entering a username and password into a dialog box for example) disabling this warning banner may allow applets to trick the user into entering such information. readDisplayPixels Readback of pixels from the display screen Interfaces such as the java.awt.Composite interface whichor the java.awt.Robot class allow arbitrary code to examine pixels on the display enable malicious code to snoop on the activities of the user.createRobot Create java.awt.Robot objects The java.awt.Robot object allows code to generate native-level mouse and keyboard events as well as read the screen. It could allow malicious code to control the system run other programs read the display and deny mouse and keyboard access to the user. 12 9818 02/1202/0300 @author Marianne Mueller @author Roland Schemers
An interface for events that know how dispatch themselves. By implementing this interface an event can be placed upon the event queue and itsdispatch()
method will be called when the event is dispatched using theEventDispatchThread
.This is a very useful mechanism for avoiding deadlocks. If a thread is executing in a critical section (i.e. it has entered one or more monitors) calling other synchronized code may cause deadlocks. To avoid the potential deadlocks an
ActiveEvent
can be created to run the second section of code at later time. If there is contention on the monitor the second thread will simply block until the first thread has finished its work and exited its monitors.For security reasons it is often desirable to use an
ActiveEvent
to avoid calling untrusted code from a critical thread. For instance peer implementations can use this facility to avoid making calls into user code from a system thread. Doing so avoids potential deadlocks and denial-of-service attacks. @author Timothy Prinzing @version 1.6 099 02/2102/9800 @since 1.2
The interface for objects which have an adjustable numeric value contained within a bounded range of values. @version 1.8 0910 02/2102/9800 @author Amy Fowler @author Tim Prinzing
TheClass BasicStroke, constructor BasicStroke(float)BasicStroke
class defines a basic set of rendering attributes for the outlines of graphics primitives. These attributes describe the shape of the mark made by a pen drawn along the outline of a Shape object and the decorations applied at the ends and joins of path segments of theShape
object. These attributes include:@version
- width
- The pen width measured perpendicularly to the pen trajectory.
- end caps
- The decoration applied to the ends of unclosed subpaths or dash segments.
- line joins
- The decoration applied where two path segments are joined.
- dash attributes
- The definition of how to make a dash pattern by alternating between opaque and transparent sections.
10 Feb1.35199702/02/00 @author Jim Graham
Constructs a solidClass BasicStroke, constructor BasicStroke(float, int, int)BasicStroke
with the specified line width and with default values for the cap and join styles. @param width the width of theBasicStroke
@throws IllegalArgumentException ifwidth
is negative
Constructs a solidClass BasicStroke, constructor BasicStroke(float, int, int, float)BasicStroke
with the specified attributes. Themiterlimit
parameter is unnecessary in cases where the default is allowable or the line joins are not specified as JOIN_MITER. @param width the width of theBasicStroke
@param cap the decoration of the ends of aBasicStroke
@param join the decoration applied where path segments meet @throws IllegalArgumentException ifwidth
is negative @throws IllegalArgumentException ifcap
is not either CAP_BUTT CAP_ROUND or CAP_SQUARE @throws IllegalArgumentException ifjoin
is not either JOIN_ROUND JOIN_BEVEL or JOIN_MITER
Constructs a solidClass BasicStroke, constructor BasicStroke(float, int, int, float, float[], float)BasicStroke
with the specified attributes. @param width the width of theBasicStroke
@param cap the decoration of the ends of aBasicStroke
@param join the decoration applied where path segments meet @param miterlimit the limit to trim the miter join @throws IllegalArgumentException ifwidth
is negative @throws IllegalArgumentException ifcap
is not either CAP_BUTT CAP_ROUND or CAP_SQUARE @throws IllegalArgumentException ifmiterlimit
is less than 1 andjoin
is JOIN_MITER @throws IllegalArgumentException ifjoin
is not either JOIN_ROUND JOIN_BEVEL or JOIN_MITER
Constructs a newBasicStroke
with the specified attributes. @param width the width of theBasicStroke
@param cap the decoration of the ends of aBasicStroke
@param join the decoration applied where path segments meet @param miterlimit the limit to trim the miter join @param dash the array representing the dashing pattern @param dash_phase the offset to start the dashing pattern @throws IllegalArgumentException ifwidth
is negative @throws IllegalArgumentException ifcap
is not either CAP_BUTT CAP_ROUND or CAP_SQUARE @throws IllegalArgumentException ifmiterlimit
is less than 1 andjoin
is JOIN_MITER @throws IllegalArgumentException ifjoin
is not either JOIN_ROUND JOIN_BEVEL or JOIN_MITER @throws IllegalArgumentException ifdash_phase
is negative anddash
is notnull
@throws IllegalArgumentException if the length ofdash
is zero @throws IllegalArgumentException if dash lengths are all zero.
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 is identified by a corresponding constant:Class BorderLayout, String AFTER_LAST_LINENORTH
SOUTH
EAST
WEST
andCENTER
. When adding a component to a container with a border layout use one of these five constants for example:Panel p = new Panel(); p.setLayout(new BorderLayout()); p.add(new Button("Okay") BorderLayout.SOUTH);As a convenience BorderLayout interprets the absence of a string specification the same as the constantCENTER
:Panel p2 = new Panel(); p2.setLayout(new BorderLayout()); p2.add(new TextArea()); // Same as p.add(new TextArea() BorderLayout.CENTER);In addition BorderLayout supports four relative positioning constants
BEFORE_FIRST_LINE
AFTER_LAST_LINE
BEFORE_LINE_BEGINS
andAFTER_LINE_ENDS
. In a container whose ComponentOrientation is set toComponentOrientation.LEFT_TO_RIGHT
these constants map toNORTH
SOUTH
WEST
andEAST
respectivelyMixing 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
NORTH
andBEFORE_FIRST_LINE
constants in a container whose orientation isLEFT_TO_RIGHT
only theBEFORE_FIRST_LINE
will be layed out.NOTE: Currently (in
JDKthe1Java 2 platform v1.2) BorderLayout does not support vertical orientations. TheisVertical
setting on the container's ComponentOrientation is not respected.The components are laid out according to their preferred sizes and the constraints of the container's size. The
NORTH
andSOUTH
components may be stretched horizontally; theEAST
andWEST
components may be stretched vertically; theCENTER
component may stretch both horizontally and vertically to fill any space left over.Here is an example of five buttons in an applet laid out using the
BorderLayout
layout manager:
![]()
The code for this applet is as follows:
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); } }
@version 1.
2745 02/1102/9700 @author Arthur van Hoff @see java.awt.Container.#add(String Component) @see java.awt.ComponentOrientation @since JDK1.0
The component comes after the last line of the layout's content. For Western top-to-bottom left-to-right orientations this is equivalent to SOUTH. @see java.awt.Component#getComponentOrientation @sinceClass BorderLayout, String AFTER_LINE_ENDSJDK11.2
The component goes at the end of the line direction for the layout. For Western top-to-bottom left-to-right orientations this is equivalent to EAST. @see java.awt.Component#getComponentOrientation @sinceClass BorderLayout, String BEFORE_FIRST_LINEJDK11.2
The component comes before the first line of the layout's content. For Western top-to-bottom left-to-right orientations this is equivalent to NORTH. @see java.awt.Component#getComponentOrientation @sinceClass BorderLayout, String BEFORE_LINE_BEGINSJDK11.2
The component goes at the beginning of the line direction for the layout. For Western top-to-bottom left-to-right orientations this is equivalent to WEST. @see java.awt.Component#getComponentOrientation @sinceJDK11.2
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 "Quit
" button as it appears under the Solaris operating system:
![]()
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.
The gesture of clicking on a button with the mouse is associated with one instance of
ActionEvent
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 specializeprocessMouseEvent
or it can register itself as a listener for mouse events by callingaddMouseListener
. Both of these methods are defined byComponent
the abstract superclass of all components.When a button is pressed and released AWT sends an instance of
ActionEvent
to the button by callingprocessEvent
on the button. The button'sprocessEvent
method receives all events for the button; it passes an action event along by calling its ownprocessActionEvent
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.If an application wants to perform some action based on a button being pressed and released it should implement
ActionListener
and register the new listener to receive events from this button by calling the button'saddActionListener
method. The application can make use of the button's action command as a messaging protocol. @version 1.50 0858 03/1914/9800 @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
ACanvas
component represents a blank rectangular area of the screen onto which the application can draw or from which the application can trap input events from the user.An application must subclass the
Canvas
class in order to get useful functionality such as creating a custom component. Thepaint
method must be overridden in order to perform custom graphics on the canvas. @version 1.21 0728 03/1015/9800 @author Sami Shaio @since JDK1.0
ACardLayout
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 aCardLayout
object is the visible component when the container is first displayed.The ordering of cards is determined by the container's own internal ordering of its component objects.
CardLayout
defines a set of methods that allow an application to flip through these cards sequentially or to show a specified card. The CardLayou#addLayoutComponent method can be used to associate a string identifier with a given card for fast random access. @version 1.27 0929 02/1502/9800 @author Arthur van Hoff @see java.awt.Container @since JDK1.0
A check box is a graphical component that can be in either an "on" (true
) or "off" (false
) state. Clicking on a check box changes its state from "on" to "off " or from "off" to "on."The following code example creates a set of check boxes in a grid layout:
setLayout(new GridLayout(3 1)); add(new Checkbox("one" null true)); add(new Checkbox("two")); add(new Checkbox("three"));
This image depicts the check boxes and grid layout created by this code example:
![]()
The button labeled
one
is in the "on" state and the other two are in the "off" state. In this example which uses theGridLayout
class the states of the three check boxes are set independently.Alternatively several check boxes can be grouped together under the control of a single object using the
CheckboxGroup
class. In a check box group at most one button can be in the "on" state at any given time. Clicking on a check box to turn it on forces any other check box in the same group that is on into the "off" state. @version 1.49 0859 03/1914/9800 @author Sami Shaio @see java.awt.GridLayout @see java.awt.CheckboxGroup @since JDK1.0
TheCheckboxGroup
class is used to group together a set ofCheckbox
buttons.Exactly one check box button in a
CheckboxGroup
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.The following code example produces a new check box group with three check boxes:
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));
This image depicts the check box group created by this example:
![]()
@version 1.
26 0429 02/2202/9900 @author Sami Shaio @see java.awt.Checkbox @since JDK1.0
This class represents a check box that can be included in a menu. Clicking on the check box in the menu changes its state from "on" to "off" or from "off" to "on."The following picture depicts a menu which contains an instance of
CheckBoxMenuItem
:
![]()
The item labeled
Check
shows a check box menu item in its "off" state.When a check box menu item is selected AWT sends an item event to the item. Since the event is an instance of
ItemEvent
theprocessEvent
method examines the event and passes it along toprocessItemEvent
. The latter method redirects the event to anyItemListener
objects that have registered an interest in item events generated by this menu item. @version 1.39 0849 03/1914/9800 @author Sami Shaio @see java.awt.event.ItemEvent @see java.awt.event.ItemListener @since JDK1.0
TheChoice
class presents a pop-up menu of choices. The current choice is displayed as the title of the menu.The following code example produces a pop-up menu:
Choice ColorChooser = new Choice(); ColorChooser.add("Green"); ColorChooser.add("Red"); ColorChooser.add("Blue");
After this choice menu has been added to a panel it appears as follows in its normal state:
![]()
In the picture
"Green"
is the current choice. Pushing the mouse button down on the object causes a menu to appear with the current choice highlighted.Some native platforms do not support arbitrary resizing of Choice components and the behavior of setSize()/getSize() is bound by such limitations. Native GUI Choice components' size are often bound by such attributes as font size and length of items contained within the Choice.
@version 1.
53 0864 03/1914/9800 @author Sami Shaio @author Arthur van Hoff @since JDK1.0
Class Color, constructor Color(ColorSpace, float[], float)ATheColor
classtois used encapsulate colors in the default sRGB color space or colors in arbitrary color spaces identified by a 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 aColor
with an explicit alpha or getting the color/alpha components of aColor
the color components are never premultiplied by the alpha component.The default color space for the Java 2D(tm) API is sRGB a proposed standard RGB color space. For further information on sRGB see http://www.w3.org/pub/WWW/Graphics/Color/sRGB.html .
Eventually this class should supersede java.awt.Color but for now it is defined to be part of the java.java2d package so we can generate documentation for a single package for review.@version 10 Feb 1997 @author Sami Shaio @author Arthur van Hoff @see ColorSpace @see AlphaComposite
Creates a color in theClass Color, constructor Color(float, float, float)color space of the suppliedspecifiedColorSpace
with the color components specified in thefloat
array and the specified alpha. The number of components is determined by thecolor spacetype of theColorSpace
.(eg.For example RGB requires 3 components but CMYK requires 4etc.)components. @param cspaceThetheColorSpace
to be used to interpret the components @param componentsAnan arbitrary number of color components that is compatible with theColorSpace@param alphaAlphaalpha value @throws IllegalArgumentException if any of the values in thecomponents
array oralpha
is outside of the range 0.0 to 1.0 @see #getComponents @see #getColorComponents
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 renderingClass Color, constructor Color(float, float, float, float)willdependsdependon finding the best match given the color space available for agivenparticular output device. @param r the red component @param g the green component @param b the blue component @see #getRed @see #getGreen @see #getBlue @see #getRGB
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 renderingClass Color, constructor Color(int)willdependsdependon finding the best match given the color space available for agivenparticular output device. @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
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 renderingClass Color, constructor Color(int, boolean)willdependsdependon finding the best match given the color space available for agivenparticular 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
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 theClass Color, constructor Color(int, int, int)hasalpha
argument isFalsefalse
alpha is defaulted to 255. @param rgba the combined RGBA components @param hasalphatrue
if the alpha bits are valid;false
otherwise @see java.awt.image.ColorModel#getRGBdefault @see #getRed @see #getGreen @see #getBlue @see #getAlpha @see #getRGB
Creates an opaque sRGB color with the specified red green and blue values in the range (0 - 255). The actual color used in renderingClass Color, int HSBtoRGB(float, float, float)willdependsdependon finding the best match given the color space available for a given output device. Alpha is defaulted to 255. @param r the red component @param g the green component @param b the blue component @see #getRed @see #getGreen @see #getBlue @see #getRGB
Converts the components of a color as specified by the HSB model to an equivalent set of values for the default RGB model.Class Color, float[] RGBtoHSB(int, int, int, float[])The
saturation
andbrightness
components should be floating-point values between zero and one (numbers in the range 0.0-1.0). Thehue
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.The integer that is returned by
HSBtoRGB
encodes the value of a color in bits 0&endash;-23 of an integer value that is the same format used by the methodgetRGB
.This integer can be supplied as an argument to theColor
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
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.Class Color, Color brighter()If the
hsbvals
argument isnull
then a new array is allocated to return the result. Otherwise the method returns the arrayhsbvals
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 arrayto beused to return the three HSB values ornull
.@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
Creates a newClass Color, PaintContext createContext(ColorModel, Rectangle, Rectangle2D, AffineTransform, RenderingHints)Color
that is a brighter version of thiscolorColor
.This method applies an arbitrary scale factor to each of the three RGB components of
thethiscolorColor
to create a brighter version ofthe samethiscolorColor
. Althoughbrighter
anddarker
are inverse operations the results of a series of invocations of these two methodsmaymight be inconsistent because of rounding errors. @return a newColor
object that is a brighter version of thiscolorColor
. @see java.awt.Color#darker @since JDK1.0
Class Color, Color darker()CreateCreates andreturnreturns a PaintContext used to generate a solid color pattern. This enables aColor
object to be used as an argument to any method requiring an object implementing the Paint interface. The samePaintContext
is returned regardless of whether or notr
r2d
xform
orhints
arenull
. @param cm the specifiedColorModel
@param r the specified Rectangle @param r2d the specified Rectangle2D @param xform the specified AffineTransform @param hints the specified RenderingHints @return aPaintContext
that is used to generate a solid color pattern. @see Paint @see PaintContext @see Graphics2D#setPaint
Creates a newClass Color, Color decode(String)Color
that is a darker version of thiscolorColor
.This method applies an arbitrary scale factor to each of the three RGB components of
thethiscolorColor
to create a darker version ofthe samethiscolorColor
. Althoughbrighter
anddarker
are inverse operations the results of a series of invocations of these two methodsmaymight be inconsistent because of rounding errors. @return a newColor
object that is a darker version of thiscolorColor
. @see java.awt.Color#brighter @since JDK1.0
Converts aClass Color, boolean equals(Object)stringString
to an integer and returns the specified opaquecolorColor
. This method handles string formats that are used to represent octal and hexidecimal numbers. @param nm astringString
that represents an opaque color as a 24-bit integer.@return the newcolorColor
object. @see java.lang.Integer#decode @exception NumberFormatException if the specified string cannot be interpreted as a decimal octal or hexidecimal integer. @since JDK1.1
Determines whether another object is equal to thisClass Color, int getAlpha()colorColor
.The result is
true
if and only if the argument is notnull
and is aColor
object that has the same red green and blue values as this object. @param obj the object tocomparetest for equality with.thisColor
@returntrue
if the objects are the same;false
otherwise. @since JDK1.0
Returns the alpha componentClass Color, int getBlue().Inin the range 0-255. @return the alpha component. @see #getRGB
Returns the blue componentClass Color, Color getColor(String).Inin the range 0-255 in the default sRGB space. @return the blue component. @see #getRGB
Finds a color in the system properties.Class Color, Color getColor(String, Color)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
colorColor
object.If the specified property is not found or could not be parsed as an integer then
null
is returned. @param nm the name of the color property @return thecolorColor
value ofconverted 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
Finds a color in the system properties.Class Color, Color getColor(String, int)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
colorColor
object.If the specified property is not found or cannot be parsed as an integer then the
colorColor
specified by the second argument is returned instead. @param nm the name of the color property @param v the defaultcolor value.Color
@return thecolorColor
value ofconverted from the system property or the specifiedColor
. @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
Finds a color in the system properties.Class Color, float[] getColorComponents(ColorSpace, float[])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
colorColor
object.If the specified property is not found or could not be parsed as an integer then the integer value
v
is used instead and is converted to acolorColor
object. @param nm the name of the color property.@param v the default color value as an integer.@return thecolorColor
value ofconverted from the system property or theColor
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
Returns aClass Color, float[] getColorComponents(float[])float
array containing only the color components(no alpha)of theColor
in theColorSpace
specified by thecspace
parameter. IfcomponentarraycompArray
isnull
an array with length equal to the number of components incspace
is created for the return value. OtherwisecomponentarraycompArray
must have at least this length and itwill beis filled in with the components and returned. @param cspace a specifiedColorSpace
@param compArray an array that this method fills with the color components of thisColor
in the specifiedColorSpace
@return the color components in afloat
array.
Returns aClass Color, ColorSpace getColorSpace()float
array containing only the color components(no alpha)of theColor
in theColorSpace
of thecolorColor
. IfcomponentarraycompArray
isnull
an array with length equal to the number of components in the associatedColorSpace
is created for the return value. OtherwisecomponentarraycompArray
must have at least this length and itwill beis filled in with the components and returned. @param compArray an array that this method fills with the color components of thisColor
in itsColorSpace
and returns @return the color components in afloat
array.
Returns theClass Color, float[] getComponents(ColorSpace, float[])ColorSpace
ofthethisColor
. @return thisColor object's
ColorSpace
.
Returns aClass Color, float[] getComponents(float[])float
array containing the color and alpha components of theColor
in theColorSpace
specified by thecspace
parameter. IfcomponentarraycompArray
isnull
an array with length equal to the number of components incspace
plus one is created for the return value. OtherwisecomponentarraycompArray
must have at least this length and itwill beis filled in with the components and returned. @param cspace a specifiedColorSpace
@param compArray an array that this method fills with the color and alpha components of thisColor
in the specifiedColorSpace
and returns @return the color and alpha components in afloat
array.
Returns aClass Color, int getGreen()float
array containing the color and alpha components of theColor
in theColorSpace
of theColor
. IfcomponentarraycompArray
isnull
an array with length equal to the number of components in the associatedColorSpace
plus one is created for the return value. OtherwisecomponentarraycompArray
must have at least this length and itwill beis filled in with the components and returned. @param compArray an array that this method fills with the color and alpha components of thisColor
in itsColorSpace
and returns @return the color and alpha components in afloat
array.
Returns the green componentClass Color, Color getHSBColor(float, float, float).Inin the range 0-255 in the default sRGB space. @return the green component. @see #getRGB
Creates aClass Color, int getRGB()Color
object based onvaluesthe specifiedsuppliedvalues for the HSB color model.
EachTheofs
theandthreeb
components should beafloating-pointvaluevalues between zero and one (a numbernumbers in the range 0.0≤-1.0). Theh
scomponentb ≤ 1can 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 aColor
object with the specified hue saturation and brightness. @since JDK1.0
Returns the RGB value representing the color in the default sRGB ColorModelClass Color, float[] getRGBColorComponents(float[]).(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 sRGBColorModel
. @see java.awt.image.ColorModel#getRGBdefault @see #getRed @see #getGreen @see #getBlue @since JDK1.0
Returns aClass Color, float[] getRGBComponents(float[])float
array containing only the color components(no alpha)of theColor
in the default sRGB color space. IfcomponentarraycompArray
isnull
an array of length 3 is created for the return value. OtherwisecomponentarraycompArray
must have length 3 or greater and itwill beis 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 afloat
array.
Returns aClass Color, int getRed()float
array containing the color and alpha components of theColor
as represented in the default sRGB color space. IfcomponentarraycompArray
isnull
an array of length 4 is created for the return value. OtherwisecomponentarraycompArray
must have length 4 or greater and itwill beis 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 afloat
array.
Returns the red componentClass Color, int getTransparency().Inin the range 0-255 in the default sRGB space. @return the red component. @see #getRGB
Class Color, int hashCode()ReturnReturns the transparency mode for thisColor
. This is requiredinto implement thePaint
interface. @return thisColor
object's transparency mode. @see Paint @see Transparency @see #createContext
Computes the hash code for thisClass Color, String toString()colorColor
. @return a hash code value for this object. @since JDK1.0
Returns a string representation of thiscolorColor
. This method is intended to be used only for debugging purposesand.theThe content and format of the returned stringmaymight vary between implementations. The returned stringmaymight be empty butmay notcannot benull
. @return a string representation of thiscolorColor
.
A component is an object having a graphical representation that can be displayed on the screen and that can interact with the user. Examples of components are the buttons checkboxes and scrollbars of a typical graphical user interface.Class Component, void addInputMethodListener(InputMethodListener)The
Component
class is the abstract superclass of the nonmenu-related Abstract Window Toolkit components. ClassComponent
can also be extended directly to create a lightweight component. A lightweight component is a component that is not associated with a native opaque window. @version 1.226 12264 02/1502/9800 @author Arthur van Hoff @author Sami Shaio
Adds the specified input method listener to receive input method events from this component. A component will only receive input method events from input methods if it also overrides getInputMethodRequests to return an InputMethodRequests instance. If l is null no exception is thrown and no action is performed. @param l the input method listener. @see java.awt.event.InputMethodEvent @see java.awt.event.InputMethodListener @see java.awt.Component#removeInputMethodListener @see java.awt.Component#getInputMethodRequests @sinceClass Component, int checkImage(Image, int, int, ImageObserver)JDK11.2
Returns the status of the construction of a screen representation of the specified image.Class Component, AWTEvent coalesceEvents(AWTEvent, AWTEvent)This method does not cause the image to begin loading. An application must use the
prepareImage
method to force the loading of an image.The
checkImage
method ofComponent
calls its peer'scheckImage
method to calculate the flags. If this component does not yet have a peer the component's toolkit'scheckImage
method is called instead.Information on the flags returned by this method can be found with the discussion of the
ImageObserver
interface. @param image theImage
object whose status is being checked. @param width the width of the scaled version whose status is to be checked. @param height the height of the scaled version whose status is to be checked. @param observer theImageObserver
object to be notified as the image is being prepared. @return the bitwise inclusive OR ofImageObserver
flags indicating what information about the image is currently available. @see java.awt.Component#prepareImage(java.awt.Image int int java.awt.image.ImageObserver) @see java.awt.Toolkit#checkImage(java.awt.Image int int java.awt.image.ImageObserver) @see java.awt.image.ImageObserver#_top_@since JDK1.0
Potentially coalesce an event being posted with an existing event. This method is called by EventQueue.postEvent if an event with the same ID as the event to be posted is found in the queue (both events must have this component as their source). This method either returns a coalesced event which replaces the existing event (and the new event is then discarded) or null to indicate that no combining should be done (add the second event to the end of the queue). Either event parameter may be modified and returned as the other one is discarded unless null is returned.Class Component, void enableInputMethods(boolean)This implementation of coalesceEvents coalesces two event types: mouse move (and drag) events and paint (and update) events. For mouse move events the last event is always returned causing intermediate moves to be discarded. For paint events
wheretheupdate rectangle of one paintnew event iscompletely contained within the update rectanglecoalescedof the other paint eventinto a complex RepaintArea in theevent withpeer.the smaller rectangleThe new Event isdiscardedalways returned. @param existingEvent the event already on the EventQueue. @param newEvent the event being posted to the EventQueue. @return a coalesced event or null indicating that no coalescing was done.
Enables or disables input method support for this component. If input method support is enabled and the component also processes key events incoming events are offered to the current input method and will only be processed by the component or dispatched to its listeners if the input method does not consume them. By default input method support is enabled. @param enable true to enable false to disable. @see java.awt.Component#processKeyEvent @sinceClass Component, Color getForeground()JDK11.2
Gets the foreground color of this component. @return This component's foreground color. If this component does not have a foreground color the foreground color of its parent is returned. @see #Class Component, Graphics getGraphics()java.awt.Component#setForeground(java.awt.Color)@since JDK1.0
Creates a graphics context for this component. This method will returnClass Component, int getHeight()null
if this component is currently noton the screendisplayable. @return A graphics context for this component ornull
if it has none. @see java.awt.Component#paint @since JDK1.0
Return the current height of this component. This method is preferable to writing component.getBounds().height or component.getSize().height because it doesn't cause any heap allocations. @return the current height of this component. @sinceClass Component, InputContext getInputContext()JDK11.2
Gets the input context used by this component for handling the communication with input methods when text is entered in this component. By default the input context used for the parent component is returned. Components may override this to return a private input context. @return The input context used by this component. Null if no context can be determined. @sinceClass Component, InputMethodRequests getInputMethodRequests()JDK11.2
Gets the input method request handler which supports requests from input methods for this component. A component that supports on-the-spot text input must override this method to return an InputMethodRequests instance. At the same time it also has to handle input method events. @return the input method request handler for this component null by default. @see #addInputMethodListener @sinceClass Component, Point getLocation()JDK11.2
Gets the location of this component in the form of a point specifying the component's top-left corner. The location will be relative to the parent's coordinate space.Class Component, int getWidth()Due to the asynchronous nature of native event handling this method can return outdated values (for instance after several calls of
@return An instance ofsetLocation()
in rapid succession). For this reason the recommended method of obtaining a Component's position is withinjava.awt.event.ComponentListener.componentMoved()
which is called after the operating system has finished moving the Component.Point
representing the top-left corner of the component's bounds in the coordinate space of the component's parent. @see #setLocation @see #getLocationOnScreen @since JDK1.1
Return the current width of this component. This method is preferable to writing component.getBounds().width or component.getSize().width because it doesn't cause any heap allocations. @return the current width of this component. @sinceClass Component, int getX()JDK11.2
Return the current x coordinate of the components origin. This method is preferable to writing component.getBounds().x or component.getLocation().x because it doesn't cause any heap allocations. @return the current x coordinate of the components origin. @sinceClass Component, int getY()JDK11.2
Return the current y coordinate of the components origin. This method is preferable to writing component.getBounds().y or component.getLocation().y because it doesn't cause any heap allocations. @return the current y coordinate of the components origin. @sinceClass Component, boolean hasFocus()JDK11.2
Returns true if this Component has the keyboard focus. @return true if this Component has the keyboard focus. @sinceClass Component, boolean imageUpdate(Image, int, int, int, int, int)JDK11.2
Repaints the component when the image has changed. ThisClass Component, boolean isDisplayable()imageUpdate
method of anImageObserver
is called when more information about an image which had been previously requested using an asynchronous routine such as thedrawImage
method ofGraphics
becomes available. See the definition ofimageUpdate
for more information on this method and its arguments.The
imageUpdate
method ofComponent
incrementally draws an image on the component as more of the bits of the image are available.If the system property
awt.image.incrementalDraw
is missing or has the valuetrue
the image is incrementally drawn If the system property has any other value then the image is not drawn until it has been completely loaded.Also if incremental drawing is in effect the value of the system property
awt.image.redrawrate
is interpreted as an integer to give the maximum redraw rate in milliseconds. If the system property is missing or cannot be interpreted as an integer the redraw rate is once every 100ms.The interpretation of the
x
y
width
andheight
arguments depends on the value of theinfoflags
argument. @param img the image being observed. @param infoflags seeimageUpdate
for more information. @param x the x coordinate. @param y the y coordinate. @paramwidthw the width. @paramheighth the height. @returnif the
truefalseflagsinfoflags indicate that the image is completely loaded;otherwise. @see java.awt.image.ImageObserver @see java.awt.Graphics#drawImage(java.awt.Image int int java.awt.Color java.awt.image.ImageObserver) @see java.awt.Graphics#drawImage(java.awt.Image int int java.awt.image.ImageObserver) @see java.awt.Graphics#drawImage(java.awt.Image int int int int java.awt.Color java.awt.image.ImageObserver) @see java.awt.Graphics#drawImage(java.awt.Image int int int int java.awt.image.ImageObserver) @see java.awt.image.ImageObserver#imageUpdate(java.awt.Image int int int int int) @since JDK1.0
falsetrue
Determines whether this component is displayable. A component is displayable when it is connected to a native screen resource.Class Component, boolean isLightweight()A component is made displayable either when it is added to a displayable containment hierarchy or when its containment hierarchy is made displayable. A containment hierarchy is made displayable when its ancestor window is either packed or made visible.
A component is made undisplayable either when it is removed from a displayable containment hierarchy or when its containment hierarchy is made undisplayable. A containment hierarchy is made undisplayable when its ancestor window is disposed. @return
true
if the component is displayable;false
otherwise. @see java.awt.Container#add(java.awt.Component) @see java.awt.Window#pack @see java.awt.Window#show @see java.awt.Container#remove(java.awt.Component) @see java.awt.Window#dispose @sinceJDK11.2
A lightweight component doesn't have a native toolkit peer. Subclasses of Component and Container other than the ones defined in this package like Button or Scrollbar are lightweight. All of the Swing components are lightweights. This method will always returnClass Component, boolean isOpaque()false
if this Component is not displayable because it is impossible to determine the weight of an undisplayable Component. @return true if this componentdoesn'thashavea lightweight peer; false if it has a native peer or no peer. @see #isDisplayable @sinceJDK11.2
Returns true if this component is completely opaque returns false by default.Class Component, void paint(Graphics)An opaque component paints every pixel within its rectangular region. A non-opaque component paints only some of its pixels allowing the pixels underneath it to "show through". A component that does not fully paint its pixels therefore provides a degree of transparency. Only lightweight components can be transparent.
Subclasses that guarantee to always completely paint their contents should override this method and return true. All of the "heavyweight" AWT components are opaque. @return true if this component is completely opaque. @see #isLightweight @since
JDK11.2
Paints this component. This method is called when the contents of the component should be painted in response to the component first being shown or damage needing repair. The clip rectangle in the Graphics parameter will be set to the area which needs to be painted. For performance reasons Components with zero width or height aren't considered to need painting when they are first shown and also aren't considered to need repair. @param g The graphics context to use for painting. @see java.awt.Component#update @since JDK1.0Class Component, void processEvent(AWTEvent)
Processes events occurring on this component. By default this method calls the appropriate process<event type>Event
method for the given class of event. @param e the event. @see java.awt.Component#processComponentEvent @see java.awt.Component#processFocusEvent @see java.awt.Component#processKeyEvent @see java.awt.Component#processMouseEvent @see java.awt.Component#processMouseMotionEvent @see java.awt.Component#processInputMethodEvent @see java.awt.Component#processHierarchyEvent @since JDK1.1
Class Component, void processInputMethodEvent(InputMethodEvent)Processes input method events occurring on this component by dispatching them to any registeredClass Component, void removeInputMethodListener(InputMethodListener)InputMethodListener
objects.This method is not called unless input method events are enabled for this component. Input method events are enabled when one of the following occurs:
@param e the input method event @see java.awt.event.InputMethodEvent @see java.awt.event.InputMethodListener @see java.awt.Component#addInputMethodListener @see java.awt.Component#enableEvents @since
- An
InputMethodListener
object is registered viaaddInputMethodListener
.- Input method events are enabled via
enableEvents
.JDK11.2
Removes the specified input method listener so that it no longer receives input method events from this component. This method performs no function nor does it throw an exception if the listener specified by the argument was not previously added to this component. If l is null no exception is thrown and no action is performed. @param l the input method listener. @see java.awt.event.InputMethodEvent @see java.awt.event.InputMethodListener @see java.awt.Component#addInputMethodListener @sinceClass Component, void setComponentOrientation(ComponentOrientation)JDK11.2
Set the language-sensitive orientation that is to be used to order the elements or text within this component. Language-sensitive LayoutManager and Component subclasses will use this property to determine how to lay out and draw components.Class Component, void setCursor(Cursor)At construction time a component's orientation is set to ComponentOrientation.UNKNOWN indicating that it has not been specified explicitly. The UNKNOWN orientation behaves the same as ComponentOrientation.LEFT_TO_RIGHT.
To set the orientation of a single component use this method. To apply a ResourceBundle's orientation to an entire component hierarchy use java.awt.Window.applyResourceBundle. @see java.awt.ComponentOrientation @see java.awt.Window#
ApplyResourceBundleapplyResourceBundle(java.util.ResourceBundle) @author Laura Werner IBM
Sets the cursor image to the specified cursor. This cursor image is displayed when theClass Component, void setDropTarget(DropTarget)contains
method for this component returns true for the current cursor location and this Component is visible displayable and enabled. Setting the cursor of aContainer
causes that cursor to be displayed within all of the container's subcomponents except for those that have a non-null cursor. @param cursor One of the constants defined by theCursor
class. If this parameter is null then this component will inherit the cursor of its parent. @see #isEnabled @see #isShowing @see java.awt.Component#getCursor @see java.awt.Component#contains @see java.awt.Toolkit#createCustomCursor @see java.awt.Cursor @since JDK1.1
Associate a DropTarget with this Component. The Component will receive drops only if it is enabled. @see #isEnabled @param dt The DropTarget
A generic Abstract Window Toolkit(AWT) container object is a component that can contain other AWT components.Class Container, Component findComponentAt(Point)Components added to a container are tracked in a list. The order of the list will define the components' front-to-back stacking order within the container. If no index is specified when adding a component to a container it will be added to the end of the list (and hence to the bottom of the stacking order). @version 1.
161 03182 01/0821/0001 @author Arthur van Hoff @author Sami Shaio @see java.awt.Container#add(java.awt.Component int) @see java.awt.Container#getComponent(int) @see java.awt.LayoutManager @since JDK1.0
Locates the visible child component that contains the specified point. The top-most child component is returned in the case where there is overlap in the components. If the containing child component is a Container this method will continue searching for the deepest nested child component. Components which are not visible are ignored during the search.Class Container, Component findComponentAt(int, int)The findComponentAt method is different from getComponentAt in that getComponentAt only searches the Container's immediate children; if the containing component is a Container findComponentAt will search that child to find a nested component. @param p the point. @return null if the component does not contain the position. If there is no child component at the requested point and the point is within the bounds of the container the container itself is returned. @see Component#contains @see getComponentAt @since
JDK11.2
Locates the visible child component that contains the specified position. The top-most child component is returned in the case where there is overlap in the components. If the containing child component is a Container this method will continue searching for the deepest nested child component. Components which are not visible are ignored during the search.Class Container, Component getComponentAt(int, int)The findComponentAt method is different from getComponentAt in that getComponentAt only searches the Container's immediate children; if the containing component is a Container findComponentAt will search that child to find a nested component. @param x the x coordinate @param y the y coordinate @return null if the component does not contain the position. If there is no child component at the requested point and the point is within the bounds of the container the container itself is returned. @see Component#contains @see getComponentAt @since
JDK11.2
Locates the component that contains the x y position. The top-most child component is returned in the case where there is overlap in the components. This is determined by finding the component closest to the index 0 that claims to contain the given point via Component.contains() except that Components which have native peers take precedence over those which do not (i.e. lightweight Components). @param x the x coordinate @param y the y coordinate @return null if the component does not contain the position. If there is no child component at the requested point and the point is within the bounds of the container the container itself is returned; otherwise the top-most child is returned. @see Component#contains @since JDK1.1
A class to encapsulate the bitmap representation of the mouse cursor. @see Component#setCursor @version 1.Class Cursor, String getName()22 1030 02/2902/9800 @author Amy Fowler
Returns the name of this cursor. @return a localized description of this cursor. @sinceClass Cursor, String toString()JDK11.2
Returns a string representation of this cursor. @return a string representation of this cursor. @sinceClass Cursor, String nameJDK11.2
The user-visible name of the cursor. @serial @see #getName()
A Dialog is a top-level window with a title and a border that is typically used to take some form of input from the user. The size of the dialog includes any area designated for the border. The dimensions of the border area can be obtained using theClass Dialog, constructor Dialog(Dialog)getInsets
method however since these dimensions are platform-dependent a valid insets value cannot be obtained until the dialog is made displayable by either callingpack
orshow
. Since the border area is included in the overall size of the dialog the border effectively obscures a portion of the dialog constraining the area available for rendering and/or displaying subcomponents to the rectangle which has an upper-left corner location of(insets.left insets.top)
and has a size ofwidth - (insets.left + insets.right)
byheight - (insets.top + insets.bottom)
.The default layout for a dialog is BorderLayout.
A dialog must have either a frame or another dialog defined as its owner when it's constructed. When the owner window of a visible dialog is hidden or minimized the dialog will automatically be hidden from the user. When the owner window is subsequently re-opened then the dialog is made visible to the user again.
A dialog can be either modeless (the default) or modal. A modal dialog is one which blocks input to all other toplevel windows in the app context except for any windows created with the dialog as their owner.
Dialogs are capable of generating the following window events: WindowOpened WindowClosing WindowClosed WindowActivated WindowDeactivated. @see WindowEvent @see Window#addWindowListener @version 1.
60 0469 01/0621/0001 @author Sami Shaio @author Arthur van Hoff @since JDK1.0
Constructs an initially invisible non-modal Dialog with an empty title and the specified owner dialog. @param owner the owner of the dialog @exception java.lang.IllegalArgumentException ifClass Dialog, constructor Dialog(Dialog, String)owner
isnull
@sinceJDK11.2
Constructs an initially invisible non-modal Dialog with the specified owner dialog and title. @param owner the owner of the dialog @param title the title of the dialog. AClass Dialog, constructor Dialog(Dialog, String, boolean)null
value will be accepted without causing a NullPointerException to be thrown. @exception java.lang.IllegalArgumentException ifowner
isnull
@sinceJDK11.2
Constructs an initially invisible Dialog with the specified owner dialog title and modality. @param owner the owner of the dialog @param title the title of the dialog. Anull
value will be accepted without causing a NullPointerException to be thrown. @param modal if true dialog blocks input to other app windows when shown @exception java.lang.IllegalArgumentException ifowner
isnull
@sinceJDK11.2
TheClass Dimension, int hashCode()Dimension
class encapsulates the width and height of a component (in integer precision) in a single object. The class is associated with certain properties of components. Several methods defined by theComponent
class and theLayoutManager
interface return aDimension
object.Normally the values of
width
andheight
are non-negative integers. The constructors that allow you to create a dimension do not prevent you from setting a negative value for these properties. If the value ofwidth
orheight
is negative the behavior of some methods defined by other objects is undefined. @version 1.21 0926 02/2102/9800 @author Sami Shaio @author Arthur van Hoff @see java.awt.Component @see java.awt.LayoutManager @since JDK1.0
ReturnsClass Dimension, int heightathe hash codevalue for the object. This method is supported for the benefit of hashtables such as those provided by java.util.Hashtable. The general contract of hashCode is: Whenever it is invoked on the same object more than once during an execution of a Java application the hashCode method must consistently return the same integer provided no information used in equals comparisons on the object is modified. This integer need not remain consistent from one execution of an application to another execution of the same application. If two objects are equal according to the equals(Object) method then calling the hashCode method on each of the two objects must produce the same integer result. It is not required that if two objects are unequal according to the java.lang.Object#equals(java.lang.Object) method then calling the hashCode method on each of the two objects must produce distinct integer results. However the programmer should be aware that producing distinct integer results for unequal objects may improve the performance of hashtables. As much as is reasonably practical the hashCode method defined by class Object does return distinct integersfordistinct objects. (This is typically implemented by converting the internal address of the object into an integer butthisimplementation technique is not required by the JavaTM programming languageDimension.)@return a hash codevaluefor thisobject. @see java.lang.Object#equals(java.lang.Object) @see java.utilDimension.Hashtable
The height dimension. Negative values can be used. @serial @see #getSizeClass Dimension, int width()@see #setSize()
The width dimension. Negative values can be used. @serial @see #getSize()@see #setSize()
Class Event, int clickCountEvent
is a platform-independent class that encapsulates events from the platform's Graphical User Interface in the Java 1.0 event model. In Java 1.1 and later versions theEvent
class is maintained only for backwards compatibilty. The information in this class description is provided to assist programmers in converting Java 1.0 programs to the new event model.In the Java 1.0 event model an event contains an Event#id field that indicates what type of event it is and which other
Event
variables are relevant for the event.For keyboard events Event#key contains a value indicating which key was activated and Event#modifiers contains the modifiers for that event. For the KEY_PRESS and KEY_RELEASE event ids the value of
key
is the unicode character code for the key. For KEY_ACTION and KEY_ACTION_RELEASE the value ofkey
is one of the defined action-key identifiers in theEvent
class (PGUP
PGDN
F1
F2
etc). @version 1.64 0868 02/1702/9800 @author Sami Shaio @since JDK1.0
ForClass Event, int idMOUSE_DOWN
events this field indicates the number of consecutive clicks. For other events its value is0
. This field has been replaced by MouseEvent.getClickCount(). @serial @see java.awt.MouseEventevent.MouseEvent#getClickCount().
Indicates which type of event the event is and which otherClass Event, int keyEvent
variables are relevant for the event. This has been replaced by AWTEvent.getID() @serial @see java.awt.AWTEvent.#getID()
The key code of the key that was pressed in a keyboard event. This has been replaced by KeyEvent.getKeyCode() @serial @see java.awt.event.KeyEvent#getKeyCode()Class Event, int modifiers
The state of the modifier keys. This is replaced with InputEvent.getModifiers() In java 1.1 MouseEvent and KeyEvent are subclasses of InputEvent. @serial @see java.awt.event.InputEvent#getModifiers()Class Event, long when
The time stamp. Replaced by InputEvent.getWhen(). @serial @see java.awt.event.InputEvent#getWhen()Class Event, int x
The x coordinate of the event. Replaced by MouseEvent.getX() @serial @see java.awt.event.MouseEvent#getX()Class Event, int y
The y coordinate of the event. Replaced by MouseEvent.getY() @serial @see java.awt.event.MouseEvent#getY()
EventQueue is a platform-independent class that queues events both from the underlying peer classes and from trusted application classes. There is only one EventQueue for each AppContext. @Class EventQueue, void invokeAndWait(Runnable)version 1.53 03/08/00 @author Thomas Ball @author Fred Ecks @author David Mendenhall @version 1.69 01/21/01 @since 1.1
Causes runnable to have its run() method called in the dispatch thread of the EventQueue. This will happen after all pending events are processed. The call blocks until this has happened. This method will throw an Error if called from the event dispatcher thread. @param runnable the Runnable whose run() method should be executed synchronously on the EventQueue @exception InterruptedException if another thread has interrupted this thread @exception InvocationTargetException if an exception is thrown when running runnable @see #invokeLater @sinceClass EventQueue, void invokeLater(Runnable)JDK11.2
Causes runnable to have its run() method called in the dispatch thread of the EventQueue. This will happen after all pending events are processed. @param runnable the Runnable whose run() method should be executed synchronously on the EventQueue @see #invokeAndWait @sinceJDK11.2
TheClass FileDialog, FilenameFilter getFilenameFilter()FileDialog
class displays a dialog window from which the user can select a file.Since it is a modal dialog when the application calls its
show
method to display the dialog it blocks the rest of the application until the user has chosen a file. @see Window#show @version 1.40 0443 02/2202/9900 @author Sami Shaio @author Arthur van Hoff @since JDK1.0
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 Windows 95 98 or NT 4.0. @return this file dialog's filename filter. @see java.io.FilenameFilter @see java.awt.FileDialog#setFilenameFilterClass FileDialog, void setFilenameFilter(FilenameFilter)
Sets the filename filter for this file dialog window to the specified filter. Filename filters do not function in Sun's reference implementation for Windows 95 98 or NT 4.0. @param filter the specified filter. @see java.io.FilenameFilter @see java.awt.FileDialog#getFilenameFilter
A flow layout arranges components in a left-to-right flow much like lines of text in a paragraph. Flow layouts are typically used to arrange buttons in a panel. It will arrange buttons left to right until no more buttons fit on the same line. Each line is centered.Class FlowLayout, int getAlignment()For example the following picture shows an applet using the flow layout manager (its default layout manager) to position three buttons:
![]()
Here is the code for this applet:
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); } }
A flow layout lets each component assume its natural (preferred) size. @version 1.
31 0839 02/1702/9800 @author Arthur van Hoff @author Sami Shaio @since JDK1.0
Gets the alignment for this layout. Possible values areClass FlowLayout, void setAlignment(int)FlowLayout.LEFT
FlowLayout.RIGHT
orFlowLayout.CENTER
. @return the alignment value for this layout. @see* @seejava.awt.FlowLayout#setAlignment @since JDK1.1
Sets the alignment for this layout. Possible values areClass FlowLayout, int LEADINGFlowLayout.LEFT
FlowLayout.RIGHT
andFlowLayout.CENTER
. @param align the alignment value. @seejava.awt.FlowLayout#getAlignment() @since JDK1.1
This value indicates that each row of components should be justified to the leading edge of the container's orientation e.g. to the left in left-to-right orientations. @see java.awt.Component#getComponentOrientation @see java.awt.ComponentOrientation @sinceClass FlowLayout, int TRAILINGJDK11.2 Package-private pending API change approval
This value indicates that each row of components should be justified to the leading edge of the container's orientation e.g. to the right in left-to-right orientations. @see java.awt.Component#getComponentOrientation @see java.awt.ComponentOrientation @sinceJDK11.2 Package-private pending API change approval
TheClass Font, constructor Font(String, int, int)Font
class represents fonts. The capabilities of this class have been extended over the java.awt.Font class in JDK(tm) 1.1 and earlier releases to provide for developers the ability to utilize more sophisticated typographic features.It is important to present the concepts behind using the words character and glyph separately. A character is a symbol that represents items like letters and numbers in a particular writing system. For example lowercase-g is a character. When a particular character has been rendered a shape now represents this character. This shape is called a glyph.
Chararcter encoding is a conversion table that maps character codes to glyph codes in the font. The character encoding used in the Java 2D(tm)
2DAPI is Unicode. For more information on Unicode you can visit the site http://www.unicode.org.Characters and glyphs do not have one-to-one correspondence. For example lowercase-a acute can be represented by two glyphs: lowercase-a and acute. Another example is ligatures such as ligature -fi which is a single glyph representing two characters f and i.
A
Font
is a collection of glyphs. AFont
can have many faces such as heavy medium oblique gothic and regular. All of these faces have similar typographic design.There are three different names that you can get from a
Font
object. The logical font name is the same as that used by java.awt.Font in JDK 1.1 and earlier releases. The font face name or just font name for short is the name of a particular font face like Helvetica Bold. The family name is the name of the font family that determines the typographic design across several faces like Helvetica. The font face name is the one that should be used to specify fonts. This name signifies actual fonts in the host system and does not identify font names with the shape of font characters as the logical font name does.The
Font
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 severalFont
objects associated with a font face each differing in size style transform and font features. The getAllFonts method of theGraphicsEnvironment
class returns an array of all font faces available in the system. These font faces are returned asFont
objects with a size of 1 identity transform and default font features. These base fonts can then be used to derive newFont
objects with varying sizes styles transforms and font features via thederiveFont
methods in this class. @see GraphicsEnvironment#getAllFonts @version10 Feb1.139199702/02/00
Creates a newClass Font, boolean canDisplay(char)Font
from the specified name style and point size. @param name the font name. This can be a logical font name or a font face name. A logical name must be either: Dialog DialogInput Monospaced Serif SansSerif or Symbol. Ifname
isnull
thename
of the newFont
is set to Default. @param style the style constant for theFont
The style argument is an integer bitmask that may be PLAIN or a bitwise union of BOLD and/or ITALIC (for example ITALIC or BOLD|ITALIC). Any other bits set in the style parameter are ignored. If the style argument does not conform to one of the expected integer bitmasks then the style is set to PLAIN. @param size the point size of theFont
@see GraphicsEnvironment#getAllFonts @see GraphicsEnvironment#getAvailableFontFamilyNames @since JDK1.0
Checks if thisClass Font, int canDisplayUpTo(CharacterIterator, int, int)Font
has a glyph for the specified character. @param c a unicode character code @returntrue
if thisFont
can display the character;false
otherwise. @sinceJDK11.2
Indicates whether or not thisClass Font, int canDisplayUpTo(String)Font
can display the specifiedString
. For strings with Unicode encoding it is important to know if a particular font can display the string. This method returns an offset into theString
str
which is the first character thisFont
cannot display without using the missing glyph code . If thisFont
can display all characters-1
is returned. @param text a CharacterIterator object @param start the specified starting offset into the specified array of characters @param limit the specified ending offset into the specified array of characters @return an offset into theString
object that can be displayed by thisFont
. @sinceJDK11.2
Indicates whether or not thisClass Font, int canDisplayUpTo(char[], int, int)Font
can display a specifiedString
. For strings with Unicode encoding it is important to know if a particular font can display the string. This method returns an offset into theString
str
which is the first character thisFont
cannot display without using the missing glyph code. If theFont
can display all characters -1 is returned. @param str aString
object @return an offset intostr
that points to the first character instr
that thisFont
cannot display; or-1
if thisFont
can display all characters instr
. @sinceJDK11.2
Indicates whether or not thisClass Font, Font deriveFont(AffineTransform)Font
can display the characters in the specifiedtext
starting atstart
and ending atlimit
. This method is a convenience overload. @param text the specified array of characters @param start the specified starting offset into the specified array of characters @param limit the specified ending offset into the specified array of characters @sinceJDK11.2
Creates a newClass Font, Font deriveFont(Map)Font
object by replicating the currentFont
object and applying a new transform to it. @param trans theAffineTransform
associated with the newFont
@return a newFont
object. @throws IllegalArgumentException iftrans
isnull
@sinceJDK11.2
Creates a newClass Font, Font deriveFont(float)Font
object by replicating the currentFont
object and applying a new set of font attributes to it. @param attributes a map of attributes enabled for the newFont
@return a newFont
object. @sinceJDK11.2
Creates a newClass Font, Font deriveFont(int)Font
object by replicating the currentFont
object and applying a new size to it. @param size the size for the newFont
. @return a newFont
object. @sinceJDK11.2
Creates a newClass Font, Font deriveFont(int, AffineTransform)Font
object by replicating the currentFont
object and applying a new style to it. @param style the style for the newFont
@return a newFont
object. @sinceJDK11.2
Creates a newClass Font, Font deriveFont(int, float)Font
object by replicating thisFont
object and applying a new style and transform. @param style the style for the newFont
@param trans theAffineTransform
associated with the newFont
@return a newFont
object. @throws IllegalArgumentException iftrans
isnull
@sinceJDK11.2
Creates a newClass Font, Attribute[] getAvailableAttributes()Font
object by replicating thisFont
object and applying a new style and size. @param style the style for the newFont
@param size the size for the newFont
@return a newFont
object. @sinceJDK11.2
Returns the keys of all the attributes supported by thisClass Font, byte getBaselineFor(char)Font
. These attributes can be used to derive other fonts. @return an array containing the keys of all the attributes supported by thisFont
. @sinceJDK11.2
Returns the baseline appropriate for displaying this character.Class Font, String getFamily()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
JDK11.2
Returns the family name of thisClass Font, String getFamily(Locale)Font
. For example Helvetica could be returned as a family name for the font face name of Helvetica Bold. UsegetName
to get the logical name of the font. UsegetFontName
to get the font face name of the font. @return aString
that is the family name of thisFont
. @see #getName @see #getFontName @since JDK1.21
Returns the family name of thisClass Font, Font getFont(Map)Font
localized for the specified locale. For example Helvetica could be returned as a family name for the font face name of Helvetica Bold. UsegetFontName
to get the font face name of the font. @param l locale for which to get the family name @return aString
representing the family name of the font localized for the specified locale. @see #getFontName @see java.util.Locale @sinceJDK11.2
Returns aClass Font, Font getFont(String)Font
appropriate to this attribute set. @param attributes the attributes to assign to the newFont
@return a newFont
created with the specified attributes. @sinceJDK11.2
Returns aClass Font, String getFontName()Font
object from the system properties list. @param nm the property name @return aFont
object that the property name describes. @sinceJDK11.2
Returns the font face name of thisClass Font, float getItalicAngle()Font
. For example Helvetica Bold could be returned as a font face name. UsegetFamily
to get the family name of the font. UsegetName
to get the logical name of the font. @return aString
representing the font face name of thisFont
. @see #getFamily @see #getName @sinceJDK11.2
Returns the italic angle of thisClass Font, int getMissingGlyphCode()Font
. The italic angle is the inverse slope of the caret which best matches the posture of thisFont
. @see TextAttribute#POSTURE @return the angle of the ITALIC style of thisFont
.
Returns the glyphCode which is used when thisClass Font, int getNumGlyphs()Font
does not have a glyph for a specified unicode. @return the glyphCode of thisFont
. @sinceJDK11.2
Returns the number of glyphs in thisClass Font, String getPSName()Font
. Glyph codes for thisFont
range from 0 togetNumGlyphs()
- 1. @return the number of glyphs in thisFont
. @sinceJDK11.2
Returns the postscript name of thisClass Font, float getSize2D()Font
. UsegetFamily
to get the family name of the font. UsegetFontName
to get the font face name of the font. @return aString
representing the postscript name of thisFont
. @sinceJDK11.2
Returns the point size of thisClass Font, Rectangle2D getStringBounds(CharacterIterator, int, int, FontRenderContext)Font
infloat
value. @return the point size of thisFont
as afloat
value. @see #getSize @sinceJDK11.2
Returns the bounds of the characters indexed in the specified CharacterIterator in the specifiedClass Font, Rectangle2D getStringBounds(String, FontRenderContext)FontRenderContext
. The bounds is used to layout theString
. @param ci the specifiedCharacterIterator
@param beginIndex the initial offset inci
@param limit the end offset inci
@param frc the specifiedFontRenderContext
@return aRectangle2D
that is the bounding box of the characters indexed in the specifiedCharacterIterator
in the specifiedFontRenderContext
. @see FontRenderContext @see Font#createGlyphVector @sinceJDK11.2 @throws IndexOutOfBoundsException ifbeginIndex
is less than the start index ofci
orlimit
is greater than the end index ofci
orbeginIndex
is greater thanlimit
Returns the bounds of the specifiedClass Font, Rectangle2D getStringBounds(String, int, int, FontRenderContext)String
in the specifiedFontRenderContext
. The bounds is used to layout theString
. @param str the specifiedString
@param frc the specifiedFontRenderContext
@return a Rectangle2D that is the bounding box of the specifiedString
in the specifiedFontRenderContext
. @see FontRenderContext @see Font#createGlyphVector @sinceJDK11.2
Returns the bounds of the specifiedClass Font, Rectangle2D getStringBounds(char[], int, int, FontRenderContext)String
in the specifiedFontRenderContext
. The bounds is used to layout theString
. @param str the specifiedString
@param beginIndex the initial offset ofstr
@param limit the end offset ofstr
@param frc the specifiedFontRenderContext
@return aRectangle2D
that is the bounding box of the specifiedString
in the specifiedFontRenderContext
. @throws IndexOutOfBoundsException ifbeginIndex
is less than zero orlimit
is greater than the length ofstr
orbeginIndex
is greater thanlimit
. @see FontRenderContext @see Font#createGlyphVector @sinceJDK11.2
Returns the bounds of the specified array of characters in the specifiedFontRenderContext
. The bounds is used to layout theString
created with the specified array of charactersbeginIndex
andlimit
. @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 specifiedFontRenderContext
@return aRectangle2D
that is the bounding box of the specified array of characters in the specifiedFontRenderContext
. @throws IndexOutOfBoundsException ifbeginIndex
is less than zero orlimit
is greater than the length ofchars
orbeginIndex
is greater thanlimit
. @see FontRenderContext @see Font#createGlyphVector @sinceJDK11.2
TheClass FontMetrics, int bytesWidth(byte[], int, int)FontMetrics
class defines a font metrics object which encapsulates information about the rendering of a particular font on a particular screen.Note that the implementations of these methods are inefficient so they are usually overridden with more efficient toolkit-specific implementations.Note to subclassers: Since many of these methods form closed mutually recursive loops you must take care that you implement at least one of the methods in each such loop to prevent infinite recursion when your subclass is used. In particular the following is the minimal suggested set of methods to override in order to ensure correctness and prevent infinite recursion (though other subsets are equally feasible):
- {@link #getAscent()}
- {@link #getLeading()}
- {@link #getMaxAdvance()}
- {@link #charWidth(char)}
- {@link #charsWidth(char[] int int)}
Note that the implementations of these methods are inefficient so they are usually overridden with more efficient toolkit-specific implementations.
When an application asks AWT to place a character at the position (x y) the character is placed so that its reference point (shown as the dot in the accompanying image) is put at that position. The reference point specifies a horizontal line called the baseline of the character. In normal printing the baselines of characters should align.
In addition every character in a font has an ascent a descent and an advance width. The ascent is the amount by which the character ascends above the baseline. The descent is the amount by which the character descends below the baseline. The advance width indicates the position at which AWT should place the next character.
If theAncurrent character is placed with its reference point at the positionarray of characters or a string can also have an ascent(xay)descent andthe character'san advance width.isThewascentthenof thenew characterarray isplaced with its reference pointthe maximum ascent of anyatcharacter in thepositionarray.(x + wThey)descent is the maximum descent of any character in the array. The advance width isoften butthenot necessarilysum of thesameadvanceas the widthwidths of each ofathecharacter'scharacters in thebounding boxcharacter array.InTheparticular oblique andadvance of aitalicString
fonts often have characters whoseis the distance along thetop-rightbaseline ofcornertheextendsString
.slightly beyond the advanceThis distance is the width.An array of charactersthat should be used for centering oraright-aligningstringthecanString
.also have an ascent a descentNote that the advance of aandString
an advanceis notwidth.necessarilyThe ascentthe sum of thearrayadvancesis the maximumof its charactersascentmeasured in isolation because the width ofanya characterincanthevaryarraydepending on its context.The descent is the maximum descentFor example in Arabic text the shape ofanya character can change intheorderarrayto connect to other characters.The advance width is the sum of the advance widths of each ofAlso in some scripts certain character sequences can be represented by a singletheshape called a ligature. Measuring charactersin theindividually doesarraynot account for these transformations. @version 1.21 03/18/98 @author Jim Graham @see java.awt.Font @since JDK1.0
Returns the total advance width for showing the specified array of bytes in thisClass FontMetrics, int charWidth(char)Font
. The advancewidthis theamountdistancebyfrom the leftmostwhichpoint to thecurrentrightmost point on the string's baseline. The advance of aString
ismoved from one character tonot necessarily the sum of thenextadvancesinof its characters. This is equivalent to measuring alineString
oftextthe characters in the specified range. @param data the array of bytes to be measured @param off the start offset of the bytes in the array @param len the number of bytes to be measured from the array @return the advance width of the subarray of the specifiedbyte
array in theFont
described by thisFontMetrics
object. @see #charsWidth(char[] int int) @see #stringWidth(String)
Returns the advance width of the specified character in thisClass FontMetrics, int charWidth(int)Font
. The advancewidthis theamount bydistancewhichfrom thecurrentleftmost pointis moved fromto the rightmostonepoint on the character'stobaseline. Note that thenext inadvance of alineString
ofistext.not@paramnecessarilychthe sum of thecharacter to beadvances of itsmeasuredcharacters. @return the advance width of the specifiedchar
in theFont
described by thisFontMetrics
object. @see #charsWidth(char[] int int) @see #stringWidth(String)
Returns the advance width of the specified character in thisClass FontMetrics, int charsWidth(char[], int, int)Font
. The advancewidthis theamount bydistancewhichfrom thecurrentleftmost pointis moved fromto the rightmostonepoint on the character'stobaseline. Note that thenext inadvance of alineString
is not necessarily the sum of the advances oftextits characters. @param ch the character to be measured @return the advance width of the specifiedchar
in theFont
described by thisFontMetrics
object. @see #charsWidth(char[] int int) @see #stringWidth(String)
Returns the total advance width for showing the specified array of characters in thisClass FontMetrics, int getMaxAdvance()Font
. The advancewidthis theamountdistancebyfrom the leftmost pointwhichto thecurrentrightmost point on the string's baseline. The advance of aString
ismoved from one character tonot necessarily the sum of thenextadvancesinof its characters. This is equivalent to measuring alineString
oftextthe characters in the specified range. @param data the array of characters to be measured @param off the start offset of the characters in the array @param len the number of characters to be measured from the array @return the advance width of the subarray of the specifiedchar
array in the font described by thisFontMetrics
object. @see #charWidth(int) @see #charWidth(char) @see #bytesWidth(byte[] int int) @see #stringWidth(String)
Gets the maximum advance width of any character in thisClass FontMetrics, int[] getWidths()Font
. The advancewidthis theamountdistance from the leftmostby whichpoint to thecurrentrightmost pointis movedon thefromstring'sonebaseline.character toThe advance of aString
is not necessarily thenext in a linesum of the advances oftextits characters. @return the maximum advance width of any character in theFont
or-1
if the maximum advance width is not known.
Gets the advance widths of the first 256 characters in theClass FontMetrics, int stringWidth(String)Font
. The advancewidthis theamount bydistancewhichfrom thecurrentleftmost pointisto themovedrightmostfrompoint ononethe character'stobaseline. Note that thenext inadvance of alineString
is not necessarily the sum of the advances oftextits characters. @return an array storing the advance widths of the characters in theFont
described by thisFontMetrics
object.
Returns the total advance width for showing the specifiedString
in thisFont
. The advancewidthis theamountdistancebyfrom the leftmostwhichpoint to thecurrentrightmost pointison the string'smovedbaseline.Note that the total advance width returned
fromonethis methodcharacterdoestonot take into account thenextrenderingincontext. Therefore the anti-aliasing and fractional metrics hints can affect the value of the advance. When enabling the anti-aliasing and fractional metrics hints usegetStringBounds(String Graphics)
instead of this method. The advance of alineString
is not necessarily the sum of the advances oftextits characters.@param str the
String
to be measured @return the advance width of the specifiedString
in theFont
described by thisFontMetrics
. @see #bytesWidth(byte[] int int) @see #charsWidth(char[] int int) @see #getStringBounds(String Graphics)
A Frame is a top-level window with a title and a border.Class Frame, constructor Frame(String)The size of the frame includes any area designated for the border. The dimensions of the border area can be obtained using the
getInsets
method however since these dimensions are platform-dependent a valid insets value cannot be obtained until the frame is made displayable by either callingpack
orshow
. Since the border area is included in the overall size of the frame the border effectively obscures a portion of the frame constraining the area available for rendering and/or displaying subcomponents to the rectangle which has an upper-left corner location of(insets.left insets.top)
and has a size ofwidth - (insets.left + insets.right)
byheight - (insets.top + insets.bottom)
.The default layout for a frame is BorderLayout.
In a multi-screen environment you can create a
Frame
on a different screen device by constructing theFrame
with Frame(GraphicsConfiguration) or titl GraphicsConfiguration)}. TheGraphicsConfiguration
object is one of theGraphicsConfiguration
objects of the target screen device.In a virtual device multi-screen environment in which the desktop area could span multiple physical screen devices the bounds of all configurations are relative to the virtual-coordinate system. The origin of the virtual-coordinate system is at the upper left-hand corner of the primary physical screen. Depending on the location of the primary screen in the virtual device negative coordinates are possible as shown in the following figure.
ALIGN=center HSPACE=10 VSPACE=7>
In such an environment when calling
setLocation
you must pass a virtual coordinate to this method. Similarly callinggetLocationOnScreen
on aFrame
returns virtual device coordinates. Call thegetBounds
method of aGraphicsConfiguration
to find its origin in the virtual coordinate system.The following code sets the location of the
Frame
at (10 10) relative to the origin of the physical screen of the correspondingGraphicsConfiguration
. If the bounds of theGraphicsConfiguration
is not taken into account theFrame
location would be set at (10 10) relative to the virtual-coordinate system and would appear on the primary physical screen which might be different from the physical screen of the specifiedGraphicsConfiguration
.Frame f = new Frame(GraphicsConfiguration gc); Rectangle bounds = gc.getBounds(); f.setLocation(10 + bounds.x 10 + bounds.y);Frames are capable of generating the following types of window events: WindowOpened WindowClosing WindowClosed WindowIconified WindowDeiconified WindowActivated WindowDeactivated. @version 1.
96 04107 03/2215/9900 @author Sami Shaio @see WindowEvent @see Window#addWindowListener @since JDK1.0
Constructs a new initially invisibleClass Frame, Frame[] getFrames()Frame
object with the specified title. @param title the title to be displayed in the frame's border. Anull
value is treated as an empty string "". @exception IllegalArgumentException if gc is not from a screen device. @see java.awt.Component#setSize @see java.awt.Component#setVisible @see java.awt.GraphicsConfiguration#getBounds
Returns an array containing all Frames created by the application. If called from an applet the array will only include the Frames accessible by that applet. @sinceJDK11.2
TheClass Graphics, void drawString(AttributedCharacterIterator, int, int)Graphics
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.A
Graphics
object encapsulates state information needed for the basic rendering operations that Java supports. This state information includes the following properties:
- The
Component
object on which to draw.- A translation origin for rendering and clipping coordinates.
- The current clip.
- The current color.
- The current font.
- The current logical pixel operation function (XOR or Paint).
- The current XOR alternation color (see
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.
The graphics pen hangs down and to the right from the path it traverses. This has the following implications:
- 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.
- If you draw a horizontal line along the same y coordinate as the baseline of a line of text that line is drawn entirely below the text except for any descenders.
All coordinates that appear as arguments to the methods of this
Graphics
object are considered relative to the translation origin of thisGraphics
object prior to the invocation of the method.All rendering operations modify only pixels which lie within the area bounded by the current clip which is specified by a Shape in user space and is controlled by the program using the
Graphics
object. This user clip is transformed into device space and combined with the device clip which is defined by the visibility of windows and device extents. The combination of the user clip and device clip defines the composite clip 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 thesetClip
orclipRect
methods. All drawing or writing is done in the current color using the current paint mode and in the current font. @version 1.56 0461 03/2223/9900 @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
Draws the text given by the specified iterator using this graphics context's current color. The iterator has to specify a font for each character. The baseline of theClass Graphics, void drawString(String, int, int)firstleftmost character is at position (x y) in this graphics context's coordinate system. @param iterator the iterator whose text is to be drawn @param x the x coordinate. @param y the y coordinate. @see java.awt.Graphics#drawBytes @see java.awt.Graphics#drawChars
Draws the text given by the specified string using this graphics context's current font and color. The baseline of theClass Graphics, Rectangle getClipBounds(Rectangle)firstleftmost character is at position (x y) in this graphics context's coordinate system. @param str the string to be drawn. @param x the x coordinate. @param y the y coordinate. @see java.awt.Graphics#drawBytes @see java.awt.Graphics#drawChars
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 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 usingClass Graphics, void setFont(Font)setClip(null)
this method returns the specifiedRectangle
. @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.
Sets this graphics context's font to the specified font. All subsequent text operations using this graphics context use this font. @param font the font. @see java.awt.Graphics#getFont @see java.awt.Graphics#drawCharsdrawString(java.lang.String int int) @see java.awt.Graphics#drawStringdrawBytes(byte[] int int int int) @see java.awt.Graphics#drawBytesdrawChars(char[] int int int int)
ThisClass Graphics2D, void drawString(String, float, float)Graphics2D
class extends the 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.
Coordinate Spaces
All coordinates passed to aGraphics2D
object are specified in a device-independent coordinate system called User Space which is used by applications. TheGraphics2D
object contains an AffineTransform object as part of its rendering state that defines how to convert coordinates from user space to device-dependent coordinates in Device Space.Coordinates in device space usually refer to individual device pixels and are aligned on the infinitely thin gaps between these pixels. Some
Graphics2D
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 theGraphics2D
Transform
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.Some of the operations performed by the rendering attribute objects occur in the device space but all
Graphics2D
methods take user space coordinates.Every
Graphics2D
object is associated with a target that defines where rendering takes place. A 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 aGraphics2D
object.When creating a
Graphics2D
object theGraphicsConfiguration
specifies the default transform for the target of theGraphics2D
(a Component or Thi 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 theIdentity
transform.Rendering Process
The Rendering Process can be broken down into four phases that are controlled by theGraphics2D
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.The steps in the rendering process are:
- Determine what to render.
- Constrain the rendering operation to the current
Clip
. TheClip
is specified by a Shape in user space and is controlled by the program using the various clip manipulation methods ofGraphics
andGraphics2D
. This user clip is transformed into device space by the currentTransform
and combined with the device clip which is defined by the visibility of windows and device extents. The combination of the user clip and device clip defines the composite clip which determines the final clipping region. The user clip is not modified by the rendering system to reflect the resulting composite clip.- Determine what colors to render.
- Apply the colors to the destination drawing surface using the current Composite attribute in the
Graphics2D
context.
The three types of rendering operations along with details of each of their particular rendering processes are:
Shape
operations
- If the operation is a
draw(Shape)
operation then the createStrokedShape method on the current Stroke attribute in theGraphics2D
context is used to construct a newShape
object that contains the outline of the specifiedShape
.- The
Shape
is transformed from user space to device space using the currentTransform
in theGraphics2D
context.- The outline of the
Shape
is extracted using the getPathIterator method ofShape
which returns a PathIterator object that iterates along the boundary of theShape
.- If the
Graphics2D
object cannot handle the curved segments that thePathIterator
object returns then it can call the alternate double getPathIterator} method ofShape
which flattens theShape
.- The current Paint in the
Graphics2D
context is queried for a PaintContext which specifies the colors to render in device space.- Text operations
- The following steps are used to determine the set of glyphs required to render the indicated
String
:
- If the argument is a
String
then the currentFont
in theGraphics2D
context is asked to convert the Unicode characters in theString
into a set of glyphs for presentation with whatever basic layout and shaping algorithms the font implements.- If the argument is an AttributedCharacterIterator the iterator is asked to convert itself to a TextLayout using its embedded font attributes. The
TextLayout
implements more sophisticated glyph layout algorithms that perform Unicode bi-directional layout adjustments automatically for multiple fonts of differing writing directions.- If the argument is a GlyphVector then the
GlyphVector
object already contains the appropriate font-specific glyph codes with explicit coordinates for the position of each glyph.- The current
Font
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.- The character outlines are filled as indicated above under
Shape
operations.- The current
Paint
is queried for aPaintContext
which specifies the colors to render in device space.Image
Operations
- The region of interest is defined by the bounding box of the source
Image
. This bounding box is specified in Image Space which is theImage
object's local coordinate system.- If an
AffineTransform
is passed to java.awt.geom.AffineTransfor java.awt.image.ImageObserver) drawImage(Image AffineTransform ImageObserver)} theAffineTransform
is used to transform the bounding box from image space to user space. If noAffineTransform
is supplied the bounding box is treated as if it is already in user space.- The bounding box of the source
Image
is transformed from user space into device space using the currentTransform
. Note that the result of transforming the bounding box does not necessarily result in a rectangular region in device space.- The
Image
object determines what colors to render sampled according to the source to destination coordinate mapping specified by the currentTransform
and the optional image transform.Default Rendering Attributes
The default values for theGraphics2D
rendering attributes are:
Paint
- The color of the
Component
.Font
- The
Font
of theComponent
.Stroke
- A square pen with a linewidth of 1 no dashing miter segment joins and square end caps.
Transform
- The getDefaultTransform for the
GraphicsConfiguration
of theComponent
.Composite
- The AlphaComposite#SRC_OVER rule.
Clip
- No rendering
Clip
the output is clipped to theComponent
.Rendering Compatibility Issues
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.The Java 2D(tm)
2D(JDKJava(tm)1.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 offwithby setting the KEY_ANTIALIASING hint key to the 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 theANTIALIASKEY_ANTIALIASING hint key to 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.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
draw
andfill
methods are defined which clearly indicates howGraphics2D
extendsGraphics
based on settings ofStroke
andTransform
attributes and rendering hints. The definition performs identically under default attribute settings. For example the defaultStroke
is aBasicStroke
with a width of 1 and no dashing and the default Transform for screen drawing is an Identity transform.The following two rules provide predictable rendering behavior whether aliasing or antialiasing is being used.
- 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.
TheLines and paths stroked using theBasicStroke
objectalways appliesmay bea"normalized"(0.5to0.5)provideuser space translation to its pen before stroking aconsistent rendering of the outlines when positioned at variouspathpoints on the drawable and whether drawn with aliased or antialiased rendering. This normalization process is controlled by the KEY_STROKE_CONTROL hint. Theresultexact normalization algorithm is not specified but the goals of thistranslation is that for the defaultnormalization are to ensure that linesBasicStrokeare rendered withaconsistentwidthvisual appearance regardless of1 user space unithow they fall on thelinepixelis offset entirely below and to the right of thegrid and to promote more solid horizontal and vertical linespath.inThis rule also maintains similar visual resultsantialiased mode so that they resemble theirwhennon-antialiasedthe samecounterparts morepathclosely.is stroked in a scaled coordinate system such as whenA typical normalization step might promote antialiased line endpoints torenderedpixel centers toa printer and also when antialiasing is turnedreduce the amount of blending or adjust theon.subpixelInpositioningallof non-antialiased3 caseslines so that thebias that was required when the line was drawn in afloating point line widths round to even or odd pixel counts1:1withcoordinateequalsystemlikelihood.and discreteThis processpixelscan move endpoints byhadup tobehalfchosen area pixelconsistent(usuallyregardless of coordinate scaling ortowards positive infinity along bothchoiceaxes)of antialiasingto promotehintthese consistent results.The following definitions of general legacy methods perform identically to previously specified behavior under default attribute settings:
The
- For
fill
operations includingfillRect
fillRoundRect
fillOval
fillArc
fillPolygon
andclearRect
fill can now be called with the desiredShape
. For example when filling a rectangle:fill(new Rectangle(x y w h));is called.
- Similarly for draw operations including
drawLine
drawRect
drawRoundRect
drawOval
drawArc
drawPolyline
anddrawPolygon
draw can now be called with the desiredShape
. For example when drawing a rectangle:draw(new Rectangle(x y w h));is called.
- The
draw3DRect
andfill3DRect
methods were implemented in terms of thedrawLine
andfillRect
methods in theGraphics
class which would predicate their behavior upon the currentStroke
andPaint
objects in aGraphics2D
context. This class overrides those implementations with versions that use the currentColor
exclusively overriding the currentPaint
and which usesfillRect
to describe the exact same behavior as the preexisting methods regardless of the setting of the currentStroke
.Graphics
class defines only thesetColor
method to control the color to be painted. Since the Java 2D API extends theColor
object to implement the newPaint
interface the existingsetColor
method is now a convenience method for setting the currentPaint
attribute to aColor
object.setColor(c)
is equivalent tosetPaint(c)
.The
Graphics
class defines two methods for controlling how colors are applied to the destination.@version
- The
setPaintMode
method is implemented as a convenience method to set the defaultComposite
equivalent tosetComposite(new AlphaComposite.SrcOver)
.- The
setXORMode(Color xorcolor)
method is implemented as a convenience method to set a specialComposite
object that ignores theAlpha
components of source colors and sets the destination color to the value:dstpixel = (PixelOf(srccolor) ^ PixelOf(xorcolor) ^ dstpixel);10-Feb-971.70 02/02/00 @author Jim Graham @see java.awt.RenderingHints
Renders the text specified by the specifiedClass Graphics2D, void drawString(String, int, int)String
using the currentFont
andPaint
attributes in theGraphics2D
context. The baseline of the first character is at position (x y) in the User Space. The rendering attributes applied include theClip
Transform
Paint
Font
andComposite
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 s theString
to be rendered @param x y the coordinates where theString
should be rendered @throws NullPointerException ifstr
isnull
@see #setPaint @see java.awt.Graphics#setColor @see java.awt.Graphics#setFont @see #setTransform @see #setComposite @see #setClip
Renders the text of the specifiedClass Graphics2D, FontRenderContext getFontRenderContext()String
using the currentFont
andPaint
attributes in theGraphics2D
context. The baseline of the first character is at position (x y) in the User Space. The rendering attributes applied include theClip
Transform
Paint
Font
andComposite
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 y the coordinates where theString
should be rendered @throws NullPointerException ifstr
isnull
@see java.awt.Graphics#drawBytes @see java.awt.Graphics#drawChars @since JDK1.0
Get the rendering context of theFont
within thisGraphics2D
context. The 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 asFont
andTextLayout
. 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 @sinceJDK11.2
TheGraphicsConfigTemplate
class is used to obtain a valid GraphicsConfiguration A user instantiates one of these objects and then sets all non-default attributes as desired. The GraphicsDevice#getBestConfiguration method found in the GraphicsDevice class is then called with thisGraphicsConfigTemplate
. A validGraphicsConfiguration
is returned that meets or exceeds what was requested in theGraphicsConfigTemplate
. @see GraphicsDevice @see GraphicsConfiguration @version 1.2 0313 02/1802/9800 @sinceJDK11.2
TheGraphicsConfiguration
class describes the characteristics of a graphics destination such as a printer or monitor. There can be manyGraphicsConfiguration
objects associated with a single graphics device. For example on X11 windowing systems each visual is a differentGraphicsConfiguration
. On PCs and Macintoshes the different screen resolution/color resolution combinations would be differentGraphicsConfiguration
objects.In a virtual device multi-screen environment in which the desktop area could span multiple physical screen devices the bounds of the
GraphicsConfiguration
objects are relative to the virtual coordinate system. When setting the location of a component use getBounds to get the bounds of the desiredGraphicsConfiguration
and offset the location with the coordinates of theGraphicsConfiguration
as the following code sample illustrates:Frame f = new Frame(GraphicsConfiguration gc); Rectangle bounds = gc.getBounds(); f.setLocation(10 + bounds.x 10 + bounds.y);To determine if your environment is a virtual device environment callgetBounds
on all of theGraphicsConfiguration
objects in your system. If any of the origins of the returned bounds are not (0 0) your environment is a virtual device environment.You can also use
getBounds
to determine the bounds of the virtual device. CallgetBounds
on all of theGraphicsConfiguration
objects in your system. Then calculate the union of all of the bounds returned from the calls togetBounds
. The union is the bounds of the virtual device. The following code sample calculates the bounds of the virtual device.Rectangle virtualBounds = new Rectangle(); GraphicsEnvironment ge = GraphicsEnvironment. getLocalGraphicsEnvironment(); GraphicsDevice[] gs = ge.getScreenDevices(); for (int j = 0; j@see GraphicsEnvironment @see GraphicsDevice@see Window @see Frame
TheGraphicsDevice
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 GraphicsEnvironment Each graphics device has one or more GraphicsConfiguration objects associated with it. These objects specify the different configurations in which theGraphicsDevice
can be used.In a multi-screen environment the
GraphicsConfiguration
objects can be used to render components on multiple screens. The following code sample demonstrates how to create aJFrame
object for eachGraphicsConfiguration
on each screen device in theGraphicsEnvironment
:GraphicsEnvironment ge = GraphicsEnvironment. getLocalGraphicsEnvironment(); GraphicsDevice[] gs = ge.getScreenDevices(); for (int j = 0; j@see GraphicsEnvironment @see GraphicsConfiguration @version10 Feb1.19199702/02/00
TheClass GraphicsEnvironment, Font[] getAllFonts()GraphicsEnvironment
class describes the collection of GraphicsDevice objects and java.awt.Font objects available to a Java(tm) application on a particular platform. The resources in thisGraphicsEnvironment
might be local or on a remote machine.GraphicsDevice
objects can be screens printers or image buffers and are the destination of Graphics2D drawing methods. EachGraphicsDevice
has a number of GraphicsConfiguration objects associated with it. These objects specify the different configurations in which theGraphicsDevice
can be used. @see GraphicsDevice @see GraphicsConfiguration @version10 Feb1.42199702/02/00
Returns an array containing a one-point size instance of all fonts available in thisClass GraphicsEnvironment, String[] getAvailableFontFamilyNames()GraphicsEnvironment
. Typical usage would be to allow a user to select a particular font. Then the application can size the font and set various font attributes by calling thederiveFont
method on the choosen instance.This method provides for the application the most precise control over which
Font
instance is used to render text. If a font in thisGraphicsEnvironment
has multiple programmable variations only one instance of thatFont
is returned in the array and other variations must be derived by the application.If a font in this environment has multiple programmable variations such as Multiple-Master fonts only one instance of that font is returned in the
Font
array. The other variations must be derived by the application. @return an array ofFont
objects. @see #getAvailableFontFamilyNames @see java.awt.Font @see java.awt.Font#deriveFont @see java.awt.Font#getFontName @sinceJDK1.2
Returns an array containing the names of all font families available in thisClass GraphicsEnvironment, String[] getAvailableFontFamilyNames(Locale)GraphicsEnvironment
. Typical usage would be to allow a user to select a particular family name and allow the application to choose related variants of the same family when the user specifies style attributes such as Bold or Italic.This method provides for the application some control over which
Font
instance is used to render text but allows theFont
object more flexibility in choosing its own best match among multiple fonts in the same font family. @return an array ofString
containing names of font families. @see #getAllFonts @see java.awt.Font @see java.awt.Font#getFamily @sinceJDK1.2
Returns an array containing the localized names of all font families available in thisGraphicsEnvironment
. Typical usage would be to allow a user to select a particular family name and allow the application to choose related variants of the same family when the user specifies style attributes such as Bold or Italic.This method provides for the application some control over which
Font
instance used to render text but allows theFont
object more flexibility in choosing its own best match among multiple fonts in the same font family. Ifl
isnull
this method returns an array containing all font family names available in thisGraphicsEnvironment
. @param l a Locale object that represents a particular geographical political or cultural region @return an array ofString
objects containing names of font families specific to the specifiedLocale
. @see #getAllFonts @see java.awt.Font @see java.awt.Font#getFamily @sinceJDK1.2
TheClass GridBagConstraints, constructor GridBagConstraints(int, int, int, int, double, double, int, int, Insets, int, int)GridBagConstraints
class specifies constraints for components that are laid out using theGridBagLayout
class. @version 1.9 0626 02/1602/9700 @author Doug Stein @see java.awt.GridBagLayout @since JDK1.0
Creates aClass GridBagConstraints, int anchorGridBagConstraints
object with all of its fields set to the passed-in arguments. Note: Because the use of this constructor hinders readability of source code this constructor should only be used by automatic source code generation tools. @param gridx The initial gridx value. @param gridy The initial gridy value. @param gridwidth The initial gridwidth value. @param gridheight The initial gridheight value. @param weightx The initial weightx value. @param weighty The initial weighty value. @param anchor The initial anchor value. @param fill The initial fill value. @param insets The initial insets value. @param ipadx The initial ipadx value. @param ipady The initial ipady value. @see java.awt.GridBagConstraints#gridx @see java.awt.GridBagConstraints#gridy @see java.awt.GridBagConstraints#gridwidth @see java.awt.GridBagConstraints#gridheight @see java.awt.GridBagConstraints#weightx @see java.awt.GridBagConstraints#weighty @see java.awt.GridBagConstraints#anchor @see java.awt.GridBagConstraints#fill @see java.awt.GridBagConstraints#insets @see java.awt.GridBagConstraints#ipadx @see java.awt.GridBagConstraints#ipady @sinceJDK11.2
This field is used when the component is smaller than its display area. It determines where within the display area to place the component. Possible values areClass GridBagConstraints, int fillCENTER
NORTH
NORTHEAST
EAST
SOUTHEAST
SOUTH
SOUTHWEST
WEST
andNORTHWEST
. The default value isCENTER
. @serial @see #clone()
This field is used when the component's display area is larger than the component's requested size. It determines whether to resize the component and if so how.Class GridBagConstraints, int gridheightThe following values are valid for
fill
:
NONE
: Do not resize the component.HORIZONTAL
: Make the component wide enough to fill its display area horizontally but do not change its height.VERTICAL
: Make the component tall enough to fill its display area vertically but do not change its width.BOTH
: Make the component fill its display area entirely.The default value is
NONE
. @serial @see #clone()
Specifies the number of cells in a column for the component's display area.Class GridBagConstraints, int gridwidthUse
REMAINDER
to specify that the component be the last one in its column. UseRELATIVE
to specify that the component be the next-to-last one in its column.gridheight should be a non-negative value and the default value is 1. @serial @see #clone() @see java.awt.GridBagConstraints#gridwidth
Specifies the number of cells in a row for the component's display area.Class GridBagConstraints, int gridxUse
REMAINDER
to specify that the component be the last one in its row. UseRELATIVE
to specify that the component be the next-to-last one in its row.gridwidth should be non-negative and the default value is 1. @serial @see #clone() @see java.awt.GridBagConstraints#gridheight
Specifies the cell at the left of the component's display area where the leftmost cell hasClass GridBagConstraints, int gridygridx=0
. The valueRELATIVE
specifies that the component be placed just to the right of the component that was added to the container just before this component was added.The default value is
RELATIVE
. gridx should be a non-negative value. @serial @see #clone() @see java.awt.GridBagConstraints#gridy
Specifies the cell at the top of the component's display area where the topmost cell hasClass GridBagConstraints, Insets insetsgridy=0
. The valueRELATIVE
specifies that the component be placed just below the component that was added to the container just before this component was added.The default value is
RELATIVE
. gridy should be a non-negative value. @serial @see #clone() @see java.awt.GridBagConstraints#gridx
This field specifies the external padding of the component the minimum amount of space between the component and the edges of its display area.Class GridBagConstraints, int ipadxThe default value is
new Insets(0 0 0 0)
. @serial @see #clone()
This field specifies the internal padding of the component how much space to add to the minimum width of the component. The width of the component is at least its minimum width plusClass GridBagConstraints, int ipady(ipadx * 2)
pixels.The default value is
0
. @serial @see #clone() @see java.awt.GridBagConstraints#ipady
This field specifies the internal padding that is how much space to add to the minimum height of the component. The height of the component is at least its minimum height plusClass GridBagConstraints, double weightx(ipady * 2)
pixels.The default value is 0. @serial @see #clone() @see java.awt.GridBagConstraints#ipadx
Specifies how to distribute extra horizontal space.Class GridBagConstraints, double weightyThe grid bag layout manager calculates the weight of a column to be the maximum
of all the components in a
weightyweightxrowcolumn. If the resulting layout is smaller horizontally than the area it needs to fill the extra space is distributed to each column in proportion to its weight. A column that has a weight of zero receives no extra space.If all the weights are zero all the extra space appears between the grids of the cell and the left and right edges.
The default value of this field is
0
. weightx should be a non-negative value. @serial @see #clone() @see java.awt.GridBagConstraints#weighty
Specifies how to distribute extra vertical space.The grid bag layout manager calculates the weight of a row to be the maximum
of all the components in a row. If the resulting layout is smaller vertically than the area it needs to fill the extra space is distributed to each row in proportion to its weight. A row that has a weight of zero receives no extra space.
weightxweightyIf all the weights are zero all the extra space appears between the grids of the cell and the top and bottom edges.
The default value of this field is
0
. weighty should be a non-negative value. @serial @see #clone() @see java.awt.GridBagConstraints#weightx
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(Container) @see #preferredLayoutSize(Container)Class GridBagLayout, double[] columnWeights
This field holds the overrides to the column weights. If this field is non-null the values are applied to the gridbag after all of the columns weights have been calculated. If columnWeights[i] >Class GridBagLayout, int[] columnWidthsthenweight for column i then column i is assigned the weight in columnWeights[i]. If columnWeights has more elements than the number of columns the excess elements are ignored - they do not cause more columns to be created. @serial@see
This field holds the overrides to the column minimum width. If this field is non-null 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()Class GridBagLayout, GridBagConstraints defaultConstraints
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 defaultConstraints
. @serial @see #getConstraints(Component) @see #setConstraints(Component GridBagConstraints) @see #lookupConstraints(Component)
Class GridBagLayout, GridBagLayoutInfo layoutInfoThis field holds tha layout information for the gridbag. The information in this field is based on the most recent validation of the gridbag. IfClass GridBagLayout, int[] rowHeightslayoutInfo
isnull
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)
This field holds the overrides to the row minimum heights. If this field is non-null the values are applied to the gridbag after all of the minimum row heights have been calculated. If rowHeights has more elements than the number of rows rowa are added to the gridbag to match the number of elements in rowHeights. @serial @see #getLayoutDimensions()Class GridBagLayout, double[] rowWeights
This field holds the overrides to the row weights. If this field is non-null the values are applied to the gridbag after all of the rows weights have been calculated. If rowWeights[i] >thenweight for row i then row i is assigned the weight in rowWeights[i]. If rowWeights has more elements than the number of rows the excess elements are ignored - they do not cause more rows to be created. @serial@see
TheGridLayout
class is a layout manager that lays out a container's components in a rectangular grid.The container is divided into equal-sized rectangles and one component is placed in each rectangle.
For example the following is an applet that lays out six buttons into three rows and two columns:
import java.awt.*; import java.applet.Applet; public class ButtonGrid extends Applet { public void init() { setLayout(new GridLayout(3 2)); add(new Button("1")); add(new Button("2")); add(new Button("3")); add(new Button("4")); add(new Button("5")); add(new Button("6")); } }
It produces the following output:
![]()
When both the number of rows and the number of columns have been set to non-zero values either by a constructor or by the setRows and setColumns methods the number of columns specified is ignored. Instead the number of columns is determined from the specified number or rows and the total number of components in the layout. So for example if three rows and two columns have been specified and nine components are added to the layout then they will be displayed as three rows of three columns. Specifying the number of columns affects the layout only when the number of rows is set to zero. @version 1.
25 0428 02/2202/9900 @author Arthur van Hoff @since JDK1.0
Signals that an AWT component is not in an appropriate state for the requested operation. @version 1.7 099 02/2102/9800 @author Jonni Kanerva
The abstract classClass Image, Image getScaledInstance(int, int, int)Image
is the superclass of all classes that represent graphical images. The image must be obtained in a platform-specific manner. @version 1.28 0431 02/2202/9900 @author Sami Shaio @author Arthur van Hoff @since JDK1.0
Creates a scaled version of this image. A newImage
object is returned which will render the image at the specifiedwidth
andheight
by default. The newImage
object may be loaded asynchronously even if the original source image has already been loaded completely. If either thewidth
orheight
is a negative number then a value is substituted to maintain the aspect ratio of the original image dimensions. @param width the width to which to scale the image. @param height the height to which to scale the image. @param hints flags to indicate the type of algorithm to use for image resampling. @return a scaled version of the image. @see java.awt.Image#SCALE_DEFAULT @see java.awt.Image#SCALE_FAST @see java.awt.Image#SCALE_SMOOTH @see java.awt.Image#SCALE_REPLICATE @see java.awt.Image#SCALE_AVERAGEAREA_AVERAGING @since JDK1.1
AnClass Insets, int hashCode()Insets
object is a representation of the borders of a container. It specifies the space that a container must leave at each of its edges. The space can be a border a blank space or a title. @version 1.20 0925 02/2102/9800 @author Arthur van Hoff @author Sami Shaio @see java.awt.LayoutManager @see java.awt.Container @since JDK1.0
ReturnsClass Insets, int bottomathe hash codevalue for the object. This method is supported for the benefit of hashtables such as those provided by java.util.Hashtable. The general contract of hashCode is: Whenever it is invoked on the same object more than once during an execution of a Java application the hashCode method must consistently return the same integer provided no information used in equals comparisons on the object is modified. This integer need not remain consistent from one execution of an application to another execution of the same application. If two objects are equal according to the equals(Object) method then calling the hashCode method on each of the two objects must produce the same integer result. It is not required that if two objects are unequal according to the java.lang.Object#equals(java.lang.Object) method then calling the hashCode method on each of the two objects must produce distinct integer results. However the programmer should be aware that producing distinct integer results for unequal objects may improve the performance of hashtables. As much as is reasonably practical the hashCode method defined by class Object does return distinct integersfordistinct objects. (This is typically implemented by converting the internal address of the object into an integer butthisimplementation technique is not required by the JavaTM programming languageInsets.)@return a hash codevaluefor thisobject. @see java.lang.Object#equals(java.lang.Object) @see java.utilInsets.Hashtable
The inset from the bottom. This value isClass Insets, int leftadded tosubtracted from the Bottom of the rectangle to yield a new location for the Bottom. @serial @see #clone()
The inset from the left. This value is added to theClass Insets, int rightleftLeft of the rectangle to yield a new location for theleftLeft edge. @serial @see #clone()
The inset from the right. This value isClass Insets, int topadded tosubtracted from the Right of the rectangle to yield a new location for the Right edge. @serial @see #clone()
The inset from the top. This value is added to the Top of the rectangle to yield a new location for the Top. @serial @see #clone()
The interface for objects which contain a set of items for which zero or more can be selected. @version 1.9 0911 02/2102/9800 @author Amy Fowler
ALabel
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.For example the code . . .
setLayout(new FlowLayout(FlowLayout.CENTER 10 10)); add(new Label("Hi There ")); add(new Label("Another Label"));
produces the following label:
@version 1.
41 0846 03/3114/9800 @author Sami Shaio @since JDK1.0
Defines the interface for classes that know how to layout Containers. @see Container @version 1.19 0421 02/2202/9900 @author Sami Shaio @author Arthur van Hoff
Defines an interface for classes that know how to layout Containers based on a layout constraints object. This interface extends the LayoutManager interface to deal with layouts explicitly in terms of constraint objects that specify how and where components should be added to the layout.This minimal extension to LayoutManager is intended for tool providers who wish to the creation of constraint-based layouts. It does not yet provide full general support for custom constraint-based layout managers. @see LayoutManager @see Container @version 1.
8 0910 02/2102/9800 @author Jonni Kanerva
TheClass List, int[] getSelectedIndexes()List
component presents the user with a scrolling list of text items. The list can be set up so that the user can choose either one item or multiple items.For example the code . . .
List lst = new List(4 false); lst.add("Mercury"); lst.add("Venus"); lst.add("Earth"); lst.add("JavaSoft"); lst.add("Mars"); lst.add("Jupiter"); lst.add("Saturn"); lst.add("Uranus"); lst.add("Neptune"); lst.add("Pluto"); cnt.add(lst);
where
cnt
is a container produces the following scrolling list:
![]()
Clicking on an item that isn't selected selects it. Clicking on an item that is already selected deselects it. In the preceding example only one item from the scrolling list can be selected at a time since the second argument when creating the new scrolling list is
false
. Selecting an item causes any other selected item to be automatically deselected.Beginning with Java 1.1 the Abstract Window Toolkit sends the
List
object all mouse keyboard and focus events that occur over it. (The old AWT event model is being maintained only for backwards compatibility and its use is discouraged.)When an item is selected or deselected AWT sends an instance of
ItemEvent
to the list. When the user double-clicks on an item in a scrolling list AWT sends an instance ofActionEvent
to the list following the item event. AWT also generates an action event when the user presses the return key while an item in the list is selected.If an application wants to perform some action based on an item in this list being selected or activated it should implement
ItemListener
orActionListener
as appropriate and register the new listener to receive events from this list.For multiple-selection scrolling lists it is considered a better user interface to use an external gesture (such as clicking on a button) to trigger the action. @version 1.
71 0477 03/2214/9900 @author Sami Shaio @see java.awt.event.ItemEvent @see java.awt.event.ItemListener @see java.awt.event.ActionEvent @see java.awt.event.ActionListener @since JDK1.0
Gets the selected indexes on the list. @return an array of the selected indexes of this scrolling list. If no items are selected a zero-length array is returned. @see java.awt.List#select @see java.awt.List#deselect @see java.awt.List#isIndexSelected
TheMediaTracker
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.To use a media tracker create an instance of
MediaTracker
and call itsaddImage
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.Here is an example:
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); } } }
@version 1.
32 0935 01/2921/0001 @author Jim Graham @since JDK1.0
AClass Menu, void remove(MenuComponent)Menu
object is a pull-down menu component that is deployed from a menu bar.A menu can optionally be a tear-off 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.
Each item in a menu must belong to the
MenuItem
class. It can be an instance ofMenuItem
a submenu (an instance ofMenu
) or a check box (an instance ofCheckboxMenuItem
). @version 1.50 0960 03/0414/9800 @author Sami Shaio @see java.awt.MenuItem @see java.awt.CheckboxMenuItem @since JDK1.0
Removes the specified menu item from this menu. @param item the item to be removed from the menu. Ifitem
isnull
or is not in this menu this method does nothing.
TheClass MenuBar, void setHelpMenu(Menu)MenuBar
class encapsulates the platform's concept of a menu bar bound to a frame. In order to associate the menu bar with aFrame
object call the frame'ssetMenuBar
method.<-- target for cross references --> This is what a menu bar might look like:
![]()
A menu bar handles keyboard shortcuts for menu items passing them along to its child menus. (Keyboard shortcuts which are optional provide the user with an alternative to the mouse for invoking a menu item and the action that is associated with it.) Each menu item can maintain an instance of
MenuShortcut
. TheMenuBar
class defines several methods MenuBar#shortcuts and MenuBar#getShortcutMenuItem that retrieve information about the shortcuts a given menu bar is managing. @version 1.46 0953 03/0414/9800 @author Sami Shaio @see java.awt.Frame @see java.awt.Frame#setMenuBar(java.awt.MenuBar) @see java.awt.Menu @see java.awt.MenuItem @see java.awt.MenuShortcut @since JDK1.0
Sets the specified menu to be this menu bar's help menu.onIf this menu bartohasbean existing help menu the old help menu is removed from the menu bar and replaced with the specified menu. @param m the menu to be set as the help menu.
The abstract classMenuComponent
is the superclass of all menu-related components. In this respect the classMenuComponent
is analogous to the abstract superclassComponent
for AWT components.Menu components receive and process AWT events just as components do through the method
processEvent
. @version 1.43 0855 02/3117/9800 @author Arthur van Hoff @since JDK1.0
The super class of all menu related containers. @version 1.9 0912 02/2102/9800 @author Arthur van Hoff
All items in a menu must belong to the classMenuItem
or one of its subclasses.The default
MenuItem
object embodies a simple labeled menu item.This picture of a menu bar shows five menu items:
![]()
The first two items are simple menu items labeled"Basic"
and"Simple"
. Following these two items is a separator which is itself a menu item created with the label"-"
. Next is an instance ofCheckboxMenuItem
labeled"Check"
. The final menu item is a submenu labeled"More Examples"
and this submenu is an instance ofMenu
.When a menu item is selected AWT sends an action event to the menu item. Since the event is an instance of
ActionEvent
theprocessEvent
method examines the event and passes it along toprocessActionEvent
. The latter method redirects the event to anyActionListener
objects that have registered an interest in action events generated by this menu item.Note that the subclass
Menu
overrides this behavior and does not send any event to the frame until one of its subitems is selected. @version 1.59 1267 03/14/9800 @author Sami Shaio
A class which represents a keyboard accelerator for a MenuItem. @version 1.15 0718 02/2802/9800 @author Thomas Ball
ThisPaint
interface defines how color patterns can be generated for Graphics2D operations. A class implementing thePaint
interface is added to theGraphics2D
context in order to define the color pattern used by thedraw
andfill
methods.Instances of classes implementing
Paint
must be read-only because theGraphics2D
does not clone these objects when they are set as an attribute with thesetPaint
method or when theGraphics2D
object is itself cloned. @see PaintContext @see Color @see GradientPaint @see TexturePaint @see Graphics2D#setPaint @version10 Feb1.23199702/02/00
Panel
is the simplest container class. A panel provides space in which an application can attach any other component including other panels.The default layout manager for a panel is the
FlowLayout
layout manager. @version 1.23 0829 03/2514/9800 @author Sami Shaio @see java.awt.FlowLayout @since JDK1.0
A point representing a location in (x y) coordinate space specified in integer precision. @version 1.Class Point, void translate(int, int)22 0926 02/2102/9800 @author Sami Shaio @since JDK1.0
Translates this point at location (x y) byClass Point, int xdx
along the x axis anddy
along the y axis so that it now represents the point (x
+
dx
y
+
dy
). @paramdxx the distance to move this point along the x axis. @paramdyy the distance to move this point along the y axis.
The x coordinate. If no x coordinate is set it will default to '0'. @serial @see #getLocation() @seeClass Point, int yMove#move(int int)
The y coordinate. If no y coordinate is set it will default to '0'. @serial @see #getLocation() @seeMove#move(int int)
A class that implements a menu which can be dynamically popped up at a specified position within a component.As the inheritance hierarchy implies a PopupMenu can be used anywhere a Menu can be used. However if you use a PopupMenu like a Menu (e.g. you add it to a MenuBar) then you cannot call
show
on that PopupMenu. @version 1.17 0723 03/2114/9800 @author Amy Fowler
An abstract class which provides a print graphics context for a page. @version 1.7 099 02/2102/9800 @author Amy Fowler
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 @version 1.8 0910 02/2102/9800 @author Amy Fowler
AClass Rectangle, Rectangle2D createIntersection(Rectangle2D)Rectangle
specifies an area in a coordinate space that is enclosed by theRectangle
object's top-left point (x y) in the coordinate space its width and its height.A
Rectangle
object'swidth
andheight
arepublic
fields. The constructors that create aRectangle
and the methods that can modify one do not prevent setting a negative value for width or height.A
Rectangle
whose width or height is negative is considered empty. If theRectangle
is empty then theisEmpty
method returnstrue
. No point can be contained by or inside an emptyRectangle
. The values ofwidth
andheight
however are still valid. An emptyRectangle
still has a location in the coordinate space and methods that change its size or location remain valid. The behavior of methods that operate on more than oneRectangle
is undefined if any of the participatingRectangle
objects has a negativewidth
orheight
. These methods includeintersects
intersection
andunion
. @version 1.39 0652 02/2402/9800 @author Sami Shaio @since JDK1.0
Returns a new Rectangle2D object representing the intersection of thisClass Rectangle, Rectangle2D createUnion(Rectangle2D)Rectangle
with the specifiedRectangle2D
. @param r theRectangle2D
to be intersected with thisRectangle
@return the largestRectangle2D
contained in both the specifiedRectangle2D
and in thisRectangle
. @sinceJDK11.2
Returns a newClass Rectangle, Rectangle2D getBounds2D()Rectangle2D
object representing the union of thisRectangle
with the specifiedRectangle2D
. @param r theRectangle2D
to be combined with thisRectangle
@return the smallestRectangle2D
containing both the specifiedRectangle2D
and thisRectangle
. @sinceJDK11.2
Return the high precision bounding box of this rectangle. @sinceClass Rectangle, int outcode(double, double)JDK11.2
Determines where the specified coordinates lie with respect to thisRectangle
. This method computes a binary OR of the appropriate mask values indicating for each side of thisRectangle
whether or not the specified coordinates are on the same side of the edge as the rest of thisRectangle
. @param x y the specified coordinates @return the logical OR of all appropriate out codes. @see #OUT_LEFT @see #OUT_TOP @see #OUT_RIGHT @see #OUT_BOTTOM @sinceJDK11.2
A container class which implements automatic horizontal and/or vertical scrolling for a single child component. The display policy for the scrollbars can be set to:
- as needed: scrollbars created and shown only when needed by scrollpane
- always: scrollbars created and always shown by the scrollpane
- never: scrollbars never created or shown by the scrollpane
The state of the horizontal and vertical scrollbars is represented by two objects (one for each dimension) which implement the Adjustable interface. The API provides methods to access those objects such that the attributes on the Adjustable object (such as unitIncrement value etc.) can be manipulated.
Certain adjustable properties (minimum maximum blockIncrement and visibleAmount) are set internally by the scrollpane in accordance with the geometry of the scrollpane and its child and these should not be set by programs using the scrollpane.
If the scrollbar display policy is defined as "never" then the scrollpane can still be programmatically scrolled using the setScrollPosition() method and the scrollpane will move and clip the child's contents appropriately. This policy is useful if the program needs to create and manage its own adjustable controls.
The placement of the scrollbars is controlled by platform-specific properties set by the user outside of the program.
The initial size of this container is set to 100x100 but can be reset using setSize().
Insets are used to define any space used by scrollbars and any borders created by the scroll pane. getInsets() can be used to get the current value for the insets. If the value of scrollbarsAlwaysVisible is false then the value of the insets will change dynamically depending on whether the scrollbars are currently visible or not. @version 1.
67 0874 03/1914/9800 @author Tom Ball @author Amy Fowler @author Tim Prinzing
TheClass Scrollbar, void setMaximum(int)Scrollbar
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:
![]()
Each scroll bar in this example could be created with code similar to the following:
redSlider=new Scrollbar(Scrollbar.VERTICAL 0 1 0 255); add(redSlider);
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" or "thumb" can represent the amount of text that is visible. Here is an example of a scroll bar that represents a range:
![]()
The value range represented by the bubble is the visible range of the scroll bar. The horizontal scroll bar in this example could be created with code like the following:
ranger = new Scrollbar(Scrollbar.HORIZONTAL 0 60 0 300); add(ranger);
Note that the actual maximum value of the scroll bar is the
maximum
minus thevisible
. In the previous example because themaximum
is 300 and thevisible
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.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 Page Up and Page Down keys are equivalent to clicking in the scroll bar's block increment and block decrement areas.
When the user changes the value of the scroll bar the scroll bar receives an instance of
AdjustmentEvent
. The scroll bar processes this event passing it along to any registered listeners.Any object that wishes to be notified of changes to the scroll bar's value should implement
AdjustmentListener
an interface defined in the packagejava.awt.event
. Listeners can be added and removed dynamically by calling the methodsaddAdjustmentListener
andremoveAdjustmentListener
.The
AdjustmentEvent
class defines five types of adjustment event listed here:
AdjustmentEvent.TRACK
is sent out when the user drags the scroll bar's bubble.AdjustmentEvent.UNIT_INCREMENT
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.AdjustmentEvent.UNIT_DECREMENT
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.AdjustmentEvent.BLOCK_INCREMENT
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 Page Up key is equivalent if the user is using a keyboard that defines a Page Up key.AdjustmentEvent.BLOCK_DECREMENT
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 Page Down key is equivalent if the user is using a keyboard that defines a Page Down key.The JDK 1.0 event system is supported for backwards compatibility but its use with newer versions of
JDKthe platform is discouraged. The fives types of adjustment event introduced with JDK 1.1 correspond to the five event types that are associated with scroll bars in previousJDKplatform versions. The following list gives the adjustment event type and the corresponding JDK 1.0 event type it replaces.
AdjustmentEvent.TRACK
replacesEvent.SCROLL_ABSOLUTE
AdjustmentEvent.UNIT_INCREMENT
replacesEvent.SCROLL_LINE_UP
AdjustmentEvent.UNIT_DECREMENT
replacesEvent.SCROLL_LINE_DOWN
AdjustmentEvent.BLOCK_INCREMENT
replacesEvent.SCROLL_PAGE_UP
AdjustmentEvent.BLOCK_DECREMENT
replacesEvent.SCROLL_PAGE_DOWN
@version 1.
65760803/2414/9800 @author Sami Shaio @see java.awt.event.AdjustmentEvent @see java.awt.event.AdjustmentListener @since JDK1.0
Sets the maximum value of this scroll bar.Normally a program should change a scroll bar's maximum value only by calling
setValues
. ThesetValues
method simultaneously and synchronously sets the minimum maximum visible amount and value properties of a scroll bar so that they are mutually consistent. @param newMaximum the new maximum value for this scroll bar. @see java.awtScrollbarawt.Scrollbar#setValues @see java.awtScrollbarawt.Scrollbar#setMinimum @since JDK1.1
TheStroke
interface allows a Graphics2D object to obtain a Shape that is the decorated outline or stylistic representation of the outline of the specifiedShape
. Stroking aShape
is like tracing its outline with a marking pen of the appropriate size and shape. The area where the pen would place ink is the area enclosed by the outlineShape
.The methods of the
Graphics2D
interface that use the outlineShape
returned by aStroke
object includedraw
and any other methods that are implemented in terms of that method such asdrawLine
drawRect
drawRoundRect
drawOval
drawArc
drawPolyline
anddrawPolygon
.The objects of the classes implementing
Stroke
must be read-only becauseGraphics2D
does not clone these objects either when they are set as an attribute with thesetStroke
method or when theGraphics2D
object is itself cloned. If aStroke
object is modified after it is set in theGraphics2D
context then the behavior of subsequent rendering would be undefined. @see BasicStroke @see Graphics2D#setStroke @version10 Feb1.19199702/02/00
A class to encapsulate symbolic colors representing the color of GUI objects on a system. For systems which support the dynamic update of the system colors (when the user changes the colors) the actual RGB values of these symbolic colors will also change dynamically. In order to compare the "current" RGB value of a SystemColor object with a non-symbolic Color object getRGB() should be used rather than equals(). @version 1.Class SystemColor, int getRGB()15 0818 02/3102/9800 @author Carl Quinn @author Amy Fowler
Gets the "current" RGB value representing the symbolic color. (Bits 24-31 are 0xff 16-23 are red 8-15 are green 0-7 are blue). @see java.awt.image.ColorModel#getRGBdefault @see java.awt.Color#getBlue(int) @see java.awt.Color#getGreen(int) @see java.awt.Color#getRed(int)
ATextArea
object is a multi-line region that displays text. It can be set to allow editing or to be read-only.The following image shows the appearance of a text area:
![]()
This text area could be created by the following line of code:
new TextArea("Hello" 5 40);
@version 1.
52 0456 03/2214/9900 @author Sami Shaio @since JDK1.0
TheClass TextComponent, Color getBackground()TextComponent
class is the superclass of any component that allows the editing of some text.A text component embodies a string of text. The
TextComponent
class defines a set of methods that determine whether or not this text is editable. If the component is editable it defines another set of methods that supports a text insertion caret.In addition the class defines methods that are used to maintain a current selection from the text. The text selection a substring of the component's text is the target of editing operations. It is also referred to as the selected text. @version 1.
51 0461 03/2214/9900 @author Sami Shaio @author Arthur van Hoff @since JDK1.0
Gets the background color of this text component. @return This text component's background color. If this text component does not have a background color the background color of its parent is returned. @seeClass TextComponent, boolean isEditable()java.awt.Component#setBackground(java.awt.Color)@since JDK1.0
Indicates whether or not this text component is editable. @returnClass TextComponent, void processTextEvent(TextEvent)true
if this text component is editable;false
otherwise. @see java.awt.TextComponent#setEditable @sinceJDK1bleJDK1.0
Processes text events occurring on this text component by dispatching them to any registered TextListener objects. NOTE: This method will not be called unless text events are enabled for this componentClass TextComponent, void removeTextListener(TextListener); this. This happens when one of the following occurs: a) A TextListener object is registered via addTextListener() b) Text events are enabled via enableEvents() @see Component#enableEvents @param e the text event
Removes the specified text event listener so that it no longer receives text events from this text component If l is null no exception is thrown and no action is performed. @param l the text listener. @see java.awt.event.TextListener @see java.awt.Class TextComponent, void selectAll()ButtonTextComponent#addTextListener @since JDK1.1
Selects all the text in this text component. @see java.awt.TextComponentClass TextComponent, void setBackground(Color)@#select
Sets the background color of this text component. @param c The color to become this text component's color. If this parameter is null then this text component will inherit the background color of its parent.Class TextComponent, void setCaretPosition(int)background color.@see #getBackground @since JDK1.0
Sets the position of the text insertion caret for this text component. The caret position is constrained to be at or before the current selection end. If the caller supplies a value forClass TextComponent, void setEditable(boolean)position
that is greater than the end of the component's text the caret position is set to the end of the component's text. This happens silently and without failure. The caret position also cannot be set to less than zero the beginning of the component's text. If the caller supplies a value forposition
that is less than zero an IllegalArgumentException is thrown. @param position the position of the text insertion caret. @exception IllegalArgumentException if the value supplied forposition
is less than zero. @since JDK1.1
Sets the flag that determines whether or not this text component is editable.If the flag is set to
true
this text component becomes user editable. If the flag is set tofalse
the user cannot change the text of this text component. @param b a flag indicating whether this text component is user editable. @see java.awt.TextComponent#isEditable @since JDK1.0
ATextField
object is a text component that allows for the editing of a single line of text.For example the following image depicts a frame with four text fields of varying widths. Two of these text fields display the predefined text
"Hello"
.
![]()
Here is the code that produces these four text fields:
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);
Every time the user types a key in the text field one or more key events are sent to the text field. A
KeyEvent
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.The key event is passed to every
KeyListener
orKeyAdapter
object which registered to receive such events using the component'saddKeyListener
method. (KeyAdapter
objects implement theKeyListener
interface.)It is also possible to fire an
ActionEvent
. If action events are enabled for the text field they may be fired by pressing theReturn
key.The
TextField
class'sprocessEvent
method examines the action event and passes it along toprocessActionEvent
. The latter method redirects the event to anyActionListener
objects that have registered to receive action events generated by this text field. @version 1.57 0462 03/2214/9900 @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
TheTexturePaint
class provides a way to fill a Shape with a texture that is specified as a BufferedImage The size of theBufferedImage
object should be small because theBufferedImage
data is copied by theTexturePaint
object. At construction time the texture is anchored to the upper left corner of a Rectangle2D that is specified in user space. Texture is computed for locations in the device space by conceptually replicating the specifiedRectangle2D
infinitely in all directions in user space and mapping theBufferedImage
to each replicatedRectangle2D
. @see Paint @see Graphics2D#setPaint @version10 Feb1.36199702/02/00
This class is the abstract superclass of all actual implementations of the Abstract Window Toolkit. Subclasses ofClass Toolkit, void addAWTEventListener(AWTEventListener, long)Toolkit
are used to bind the various components to particular native toolkit implementations.Most applications should not call any of the methods in this class directly. The methods defined by
Toolkit
are the "glue" that joins the platform-independent classes in thejava.awt
package with their counterparts injava.awt.peer
. Some methods defined byToolkit
query the native operating system directly. @version 1.125 04151 02/2202/9900 @author Sami Shaio @author Arthur van Hoff @author Fred Ecks @since JDK1.0
Adds an AWTEventListener to receive all AWTEvents dispatched system-wide that conform to the givenClass Toolkit, Cursor createCustomCursor(Image, Point, String)eventMask
.First if there is a security manager its
checkPermission
method is called with anAWTPermission("listenToAllAWTEvents")
permission. This may result in a SecurityException.
eventMask
is a bitmask of event types to receive. It is constructed by bitwise OR-ing together the event masks defined inAWTEvent
.Note: event listener use is not recommended for normal application use but are intended solely to support special purpose facilities including support for accessibility event record/playback and diagnostic tracing. If listener is null no exception is thrown and no action is performed. @param listener the event listener. @param eventMask the bitmask of event types to receive @throws SecurityException if a security manager exists and its
checkPermission
method doesn't allow the operation. @see java.awt.event.AWTEventListener @see java.awt.Toolkit#addEventListeneraddAWTEventListener @see java.awt.AWTEvent @see SecurityManager#checkPermission @see java.awt.AWTPermission @sinceJDK11.2
Creates a new custom cursor object. If the image to display is invalid the cursor will be hidden (made completely transparent) and the hotspot will be set to (0 0). @param image the image to display when the cursor is active. @param hotSpot the X and Y of the large cursor's hot spot. The hotSpot values must be less than the Dimension returned by getBestCursorSize(). @param name a localized description of the cursor for Java Accessibility use. @exception IndexOutOfBoundsException if the hotSpot values are outside the bounds of the cursor. @sinceClass Toolkit, Image createImage(String)JDK11.2
Returns an image which gets pixel data from the specified file. The returned Image is a new object which will not be shared with any other caller of this method or its getImage variant. @param filename the name of a file containing pixel data in a recognized file format. @return an image which gets its pixel data from the specified file. @see #getImage(java.lang.String)Class Toolkit, Image createImage(URL)
Returns an image which gets pixel data from the specified URL. The returned Image is a new object which will not be shared with any other caller of this method or its getImage variant. @param url the URL to use in fetching the pixel data. @return an image which gets its pixel data from the specified URL. @see #getImage(java.net.URL)Class Toolkit, Dimension getBestCursorSize(int, int)
Returns the supported cursor dimension which is closest to the desired sizes. Systems which only support a single cursor size will return that size regardless of the desired sizes. Systems which don't support custom cursors will return a dimension of 0 0.Class Toolkit, FontMetrics getFontMetrics(Font)Note: if an image is used whose dimensions don't match a supported size (as returned by this method) the Toolkit implementation will attempt to resize the image to a supported size. Since converting low-resolution images is difficult no guarantees are made as to the quality of a cursor image which isn't a supported size. It is therefore recommended that this method be called and an appropriate image used so no image conversion is made. @param desiredWidth the preferred cursor width the component would like to use. @param desiredHeight the preferred cursor height the component would like to use. @return the closest matching supported cursor size or a dimension of 0 0 if the Toolkit implementation doesn't support custom cursors. @since
JDK11.2
Gets the screen device metrics for rendering of the font. @param font a font. @return the screen metrics of the specified font in this toolkit. @deprecated This returns integer metrics for the default screen. @see java.awt.Class Toolkit, Image getImage(String)Font#font.LineMetrics @see java.awt.Font#retreiveLineMetricsgetLineMetrics @see java.awt.GraphicsEnvironment#getScreenDevices;
Returns an image which gets pixel data from the specified file whose format can be either GIF JPEG or PNG. The underlying toolkit attempts to resolve multiple requests with the same filename to the same returned Image. Since the mechanism required to facilitate this sharing of Image objects may continue to hold onto images that are no longer of use for an indefinate period of time developers are encouraged to implement their own caching of images by using the createImage variant wherever available. @param filename the name of a file containing pixel data in a recognized file format. @return an image which gets its pixel data from the specified file. @see #createImage(java.lang.String)Class Toolkit, Image getImage(URL)
Returns an image which gets pixel data from the specified URL. The pixel data referenced by the specified URL must be in one of the following formats: GIF JPEG or PNG. The underlying toolkit attempts to resolve multiple requests with the same URL to the same returned Image. Since the mechanism required to facilitate this sharing of Image objects may continue to hold onto images that are no longer of use for an indefinate period of time developers are encouraged to implement their own caching of images by using the createImage variant wherever available. @param url the URL to use in fetching the pixel data. @return an image which gets its pixel data from the specified URL. @see #createImage(java.net.URL)Class Toolkit, int getMaximumCursorColors()
Returns the maximum number of colors the Toolkit supports in a custom cursor palette.Class Toolkit, PrintJob getPrintJob(Frame, String, Properties)Note: if an image is used which has more colors in its palette than the supported maximum the Toolkit implementation will attempt to flatten the palette to the maximum. Since converting low-resolution images is difficult no guarantees are made as to the quality of a cursor image which has more colors than the system supports. It is therefore recommended that this method be called and an appropriate image used so no image conversion is made. @return the maximum number of colors or zero if custom cursors are not supported by this Toolkit implementation. @since
JDK11.2
Gets aClass Toolkit, void loadSystemColors(int[])PrintJob
object which is the result of initiating a print operation on the toolkit's platform.Each actual implementation of this method should first check if there is a security manager installed. If there is the method should call the security manager's
checkPrintJobAccess
method to ensure initiation of a print operation is allowed. If the default implementation ofcheckPrintJobAccess
is used (that is that method is not overriden) then this results in a call to the security manager'scheckPermission
method with aRuntimePermission("queuePrintJob")
permission. @param frame the parent of the print dialog. May not be null. @param jobtitle the title of the PrintJob. A null title is equivalent to "". @param props a Properties object containing zero or more properties. Properties are not standardized and are not consistent across implementations. Because of this PrintJobs which require job and page control should use the version of this function which takes JobAttributes and PageAttributes objects. This object may be updated to reflect the user's job choices on exit. May be null. @return aPrintJob
object ornull
if the user cancelled the print job. @throws NullPointerException if frame is null @throws SecurityException if this thread is not allowed to initiate a print job request @see java.awt.PrintJob @see java.lang.RuntimePermission @since JDK1.1
Fills in the integer array that is supplied as an argument with the current system color values.Class Toolkit, void removeAWTEventListener(AWTEventListener)This method is called by the method updateSystemColors in the SystemColor class.@param an integer array. @see java.awt.SystemColor#updateSystemColors @since JDK1.1
Removes an AWTEventListener from receiving dispatched AWTEvents.First if there is a security manager its
checkPermission
method is called with anAWTPermission("listenToAllAWTEvents")
permission. This may result in a SecurityException.Note: event listener use is not recommended for normal application use but are intended solely to support special purpose facilities including support for accessibility event record/playback and diagnostic tracing. If listener is null no exception is thrown and no action is performed. @param listener the event listener. @throws SecurityException if a security manager exists and its
checkPermission
method doesn't allow the operation. @see java.awt.event.AWTEventListener @see java.awt.Toolkit#addEventListeneraddAWTEventListener @see java.awt.AWTEvent @see SecurityManager#checkPermission @see java.awt.AWTPermission @sinceJDK11.2
TheTransparency
interface defines the common transparency modes for implementing classes. @version10 Feb1.17199702/02/00
AClass Window, constructor Window(Frame)Window
object is a top-level window with no borders and no menubar. The default layout for a window isBorderLayout
.A window must have either a frame dialog or another window defined as its owner when it's constructed.
In a multi-screen environment you can create a
Window
on a different screen device by constructing theWindow
with GraphicsConfiguration) TheGraphicsConfiguration
object is one of theGraphicsConfiguration
objects of the target screen device.In a virtual device multi-screen environment in which the desktop area could span multiple physical screen devices the bounds of all configurations are relative to the virtual device coordinate system. The origin of the virtual-coordinate system is at the upper left-hand corner of the primary physical screen. Depending on the location of the primary screen in the virtual device negative coordinates are possible as shown in the following figure.
![]()
In such an environment when calling
setLocation
you must pass a virtual coordinate to this method. Similarly callinggetLocationOnScreen
on aWindow
returns virtual device coordinates. Call thegetBounds
method of aGraphicsConfiguration
to find its origin in the virtual coordinate system.The following code sets the location of a
Window
at (10 10) relative to the origin of the physical screen of the correspondingGraphicsConfiguration
. If the bounds of theGraphicsConfiguration
is not taken into account theWindow
location would be set at (10 10) relative to the virtual-coordinate system and would appear on the primary physical screen which might be different from the physical screen of the specifiedGraphicsConfiguration
.Window w = new Window(Window owner GraphicsConfiguration gc); Rectangle bounds = gc.getBounds(); w.setLocation(10 + bounds.x 10 + bounds.y);Windows are capable of generating the following window events: WindowOpened WindowClosed. @version 1.
110 12137 01/1521/9801 @author Sami Shaio @author Arthur van Hoff @see WindowEvent @see #addWindowListener @see java.awt.BorderLayout @since JDK1.0
Constructs a new invisible windowClass Window, constructor Window(Window). The window is not initially visible.Callwith theshow method to cause thespecifiedwindow to become visibleFrame as its owner.If there is a security manager this method first calls the security manager's
checkTopLevelWindow
method withthis
as its argument to determine whether or not the window must be displayed with a warning banner. @param owner themainFrame
toapplicationactframe.as owner @exceptionjava.lang.IllegalArgumentException ifis
ownergcnullnot@seefromjava.awta screen device.Window#show@seeexception java.awtlang.Component#setSizeIllegalArgumentException ifowner
isnull
@see java.lang.SecurityManager#checkTopLevelWindow
Constructs a new invisible window with the specifiedClass Window, void applyResourceBundle(ResourceBundle)windowWindow as its owner.If there is a security manager this method first calls the security manager's
checkTopLevelWindow
method withthis
as its argument to determine whether or not the window must be displayed with a warning banner. @param owner thewindowWindow to act as owner @exception java.lang.IllegalArgumentException ifowner
isnull
@see java.lang.SecurityManager#checkTopLevelWindow @sinceJDK11.2
Apply the settings in the given ResourceBundle to this Window. Currently this applies the ResourceBundle's ComponentOrientation to this Window and all components contained within it. @see java.awt.ComponentOrientation @sinceClass Window, void applyResourceBundle(String)JDK11.2
Load the ResourceBundle with the given name using the default locale and apply its settings to this window. Currently this applies the ResourceBundle's ComponentOrientation to this Window and all components contained within it. @see java.awt.ComponentOrientation @sinceClass Window, InputContext getInputContext()JDK11.2
Gets the input context for this window. A window always has an input context which is shared by subcomponents unless they create and set their own. @see Component#getInputContext @sinceClass Window, Window[] getOwnedWindows()JDK11.2
Return an array containing all the windows this window currently owns. @sinceJDK11.2