|
Generated by JDiff |
||||||||
| PREV PACKAGE NEXT PACKAGE FRAMES NO FRAMES | |||||||||
This file contains all the changes in documentation in the packagejava.awtas 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.12 0213 12/0203/0001 @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.Class AWTEvent, String paramString()The event masks defined in this class are needed by Component 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.InputMethodEvent @see java.awt.event.InvocationEvent @see java.awt.event.ItemEvent @see java.awt.event.HierarchyEvent @see java.awt.event.KeyEvent @see java.awt.event.MouseEvent @see java.awt.event.MouseWheelEvent @see java.awt.event.PaintEvent @see java.awt.event.TextEvent @see java.awt.event.WindowEvent @author Carl Quinn @author Amy Fowler @version 1.
38 0248 12/1103/0001 @since 1.1
Returns a string representing the state of thiseventEvent. This method is intended to be used only for debugging purposes and the content and format of the returned string may vary between implementations. The returned string may be empty but may not benull. @return a string representation of this event.
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:@author John Rose @author Amy Fowler @version 1.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()); } }25 0231 12/0203/0001 @since 1.1
Signals that an Absract Window Toolkit exception has occurred. @version 1.13 0214 12/0203/0001 @author Arthur van Hoff
This class is for AWT permissions. AnClass AWTPermission, constructor AWTPermission(String)AWTPermissioncontains 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
AWTPermissiontarget 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 or 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. fullScreenExclusive Enter full-screen exclusive mode Entering full-screen exclusive mode allows direct access to low-level graphics card memory. This could be used to spoof the system since the program is in direct control of rendering. 18 0221 12/0203/0001 @author Marianne Mueller @author Roland Schemers
Creates a newClass AWTPermission, constructor AWTPermission(String, String)AWTPermissionwith the specified name. The name is the symbolic name of theAWTPermissionsuch as "topLevelWindow" "systemClipboard" etc. An asterisk may be used to indicate all AWT permissions. @param name the name of the AWTPermission.
Creates a newAWTPermissionobject with the specified name. The name is the symbolic name of theAWTPermissionand the actionsStringstring is currently unused and should benull. This constructor exists for use by thePolicyobject to instantiate newPermissionpermission objects. @param name the name of theAWTPermission@param actions should be.null.
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
ActiveEventcan 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
ActiveEventto 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.9 0210 12/0203/0001 @since 1.2
The interface for objects which have an adjustable numeric value contained within a bounded range of values. @version 1.Class Adjustable, void addAdjustmentListener(AdjustmentListener)10 0214 12/0203/0001 @author Amy Fowler @author Tim Prinzing
Class Adjustable, int getBlockIncrement()AddAdds a listener torecievereceive adjustment events when the value of the adjustable object changes. @param l the listener torecievereceive events @see AdjustmentEvent
Gets the block value increment for the adjustable object. @return the block value increment for the adjustable objectClass Adjustable, int getMaximum()
Gets the maximum value of the adjustable object. @return the maximum value of the adjustable objectClass Adjustable, int getMinimum()
Gets the minimum value of the adjustable object. @return the minimum value of the adjustable objectClass Adjustable, int getOrientation()
Gets the orientation of the adjustable object. @return the orientation of the adjustable object; eitherClass Adjustable, int getUnitIncrement()HORIZONTALVERTICALorNO_ORIENTATION
Gets the unit value increment for the adjustable object. @return the unit value increment for the adjustable objectClass Adjustable, int getValue()
Gets the current value of the adjustable object. @return the current value of the adjustable objectClass Adjustable, int getVisibleAmount()
Gets the length of theClass Adjustable, void setVisibleAmount(int)propertionalproportional indicator. @return the length of the proportional indicator
Sets the length of theClass Adjustable, int HORIZONTALproportionlproportional indicator of the adjustable object. @param v the length of the indicator
Class Adjustable, int VERTICALTheIndicates that theAdjustablehas horizontal orientation.
TheIndicates that theAdjustablehas vertical orientation.
ThisClass AlphaComposite, AlphaComposite getInstance(int)AlphaCompositeclass implements the basic alpha compositing rules for combining source and destination pixels to achieve blending and transparency effects with graphics and images. The rules implemented by this class area subsetthe set ofthePorter-Duff rules described in T. Porter and T. Duff "Compositing Digital Images" SIGGRAPH 84 253-259.If any input does not have an alpha channel an alpha value of 1.0 which is completely opaque is assumed for all pixels. A constant alpha value can also be specified to be multiplied with the alpha value of the source pixels.
The following abbreviations are used in the description of the rules:
- Cs = one of the color components of the source pixel.
- Cd = one of the color components of the destination pixel.
- As = alpha component of the source pixel.
- Ad = alpha component of the destination pixel.
- Fs = fraction of the source pixel that contributes to the output.
- Fd = fraction of the input destination pixel that contributes to the output.
The color and alpha components produced by the compositing operation are calculated as follows:
Cd = Cs*Fs + Cd*Fd Ad = As*Fs + Ad*Fdwhere Fs and Fd are specified by each rule. The above equations assume that both source and destination pixels have the color components premultiplied by the alpha component. Similarly the equations expressed in the definitions of compositing rules below assume premultiplied alpha.For performance reasons it is preferrable that Rasters passed to the compose method of a CompositeContext object created by the
AlphaCompositeclass have premultiplied data. If either source or destination Rasters are not premultiplied however appropriate conversions are performed before and after the compositing operation.The alpha resulting from the compositing operation is stored in the destination if the destination has an alpha channel. Otherwise the resulting color is divided by the resulting alpha before being stored in the destination and the alpha is discarded. If the alpha value is 0.0 the color values are set to 0.0. @see Composite @see CompositeContext @version 10 Feb 1997
Creates anAlphaCompositeobject with the specified rule. @param rule the compositing rule @throws IllegalArgumentException ifruleis not one of the following: #CLEAR #SRC #DST #SRC_OVER #DST_OVER #SRC_IN #DST_IN #SRC_OUTor#DST_OUT #SRC_ATOP #DST_ATOP or #XOR
TheBasicStrokeclass defines a basic set of rendering attributes for the outlines of graphics primitives which are rendered with a Graphics2D object that has its Stroke attribute set to thisBasicStroke. The rendering attributes defined byBasicStrokedescribe the shape of the mark made by a pen drawn along the outline of a Shape and the decorations applied at the ends and joins of path segments of theShape. These rendering attributes include:All attributes that specify measurements and distances controlling the shape of the returned outline are measured in the same coordinate system as the original unstroked
- width
- The pen width measured perpendicularly to the pen trajectory.
- end caps
- The decoration applied to the ends of unclosed subpaths and dash segments. Subpaths that start and end on the same point are still considered unclosed if they do not have a CLOSE segment. See SEG_CLOSE for more information on the CLOSE segment. The three different decorations are: #CAP_BUTT #CAP_ROUND and #CAP_SQUARE
- line joins
- The decoration applied at the intersection of two path segments and at the intersection of the endpoints of a subpath that is closed using SEG_CLOSE The three different decorations are: #JOIN_BEVEL #JOIN_MITER and #JOIN_ROUND
- miter limit
- The limit to trim a line join that has a JOIN_MITER decoration. A line join is trimmed when the ratio of miter length to stroke width is greater than the miterlimit value. The miter length is the diagonal length of the miter which is the distance between the inside corner and the outside corner of the intersection. The smaller the angle formed by two line segments the longer the miter length and the sharper the angle of intersection. The default miterlimit value of 10.0f causes all angles less than 11 degrees to be trimmed. Trimming miters converts the decoration of the line join to bevel.
- dash attributes
- The definition of how to make a dash pattern by alternating between opaque and transparent sections.
Shapeargument. When aGraphics2Dobject uses aStrokeobject to redefine a path during the execution of one of itsdrawmethods the geometry is supplied in its original form before theGraphics2Dtransform attribute is applied. Therefore attributes such as the pen width are interpreted in the user space coordinate system of theGraphics2Dobject and are subject to the scaling and shearing effects of the user-space-to-device-space transform in that particularGraphics2D. For example the width of a rendered shape's outline is determined not only by the width attribute of thisBasicStrokebut also by the transform attribute of theGraphics2Dobject. Consider this code:// sets the Graphics2D object's Tranform attribute g2d.scale(10 10); // sets the Graphics2D object's Stroke attribute g2d.setStroke(new BasicStroke(1.5f));Assuming there are no other scaling transforms added to theGraphics2Dobject the resulting line will be approximately 15 pixels wide. As the example code demonstrates a floating-point line offers better precision especially when large transforms are used with aGraphics2Dobject. When a line is diagonal the exact width depends on how the rendering pipeline chooses which pixels to fill as it traces the theoretical widened outline. The choice of which pixels to turn on is affected by the antialiasing attribute because the antialiasing rendering pipeline can choose to color partially-covered pixels.For more information on the user space coordinate system and the rendering process see the
Graphics2Dclass comments. @see Graphics2D @version 1.370212/0903/01 @author Jim Graham
A border layout lays out a container arranging and resizing its components to fit in five regions: north south east west and center. Each region may contain no more than one component and is identified by a corresponding constant:Class BorderLayout, String AFTER_LAST_LINENORTHSOUTHEASTWESTandCENTER. 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 convenienceBorderLayoutinterprets 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
BorderLayoutsupportsfourthe relative positioning constantsBEFORE_FIRSTPAGE_LINESTARTAFTERPAGE_LAST_LINEENDandBEFORE_LINE_BEGINSSTART. In a container whoseAFTER_LINE_ENDSENDComponentOrientationis set toComponentOrientation.LEFT_TO_RIGHTthese constants map toNORTHSOUTHWESTandEASTrespectively.
MixingFor compatibility with previous releasesBorderLayoutalso includes thetwo typesrelative positioningofconstantsBEFORE_FIRST_LINEAFTER_LAST_LINEBEFORE_LINE_BEGINSandAFTER_LINE_ENDS. These are equivalent toPAGE_STARTPAGE_ENDLINE_STARTandLINE_ENDrespectively. For consistency with the relative positioning constants used by other components the latter constants are preferred.Mixing
both absolute and relative positioning constants can lead to unpredicable results. If you use both types the relative constants will take precedence. For example if you add components using both theNORTHandconstants in a container whose orientation isBEFORE_FIRSTPAGE_LINESTARTLEFT_TO_RIGHTonly thewill be layed out.BEFORE_FIRSTPAGE_LINESTARTNOTE: Currently (in the Java 2 platform v1.2)
BorderLayoutdoes not support vertical orientations. TheisVerticalsetting on the container'sComponentOrientationis not respected.The components are laid out according to their preferred sizes and the constraints of the container's size. The
NORTHandSOUTHcomponents may be stretched horizontally; theEASTandWESTcomponents may be stretched vertically; theCENTERcomponent 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
BorderLayoutlayout 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.
45 0249 12/0203/0001 @author Arthur van Hoff @see java.awt.Container#add(String Component) @see java.awt.ComponentOrientation @since JDK1.0
Class BorderLayout, String AFTER_LINE_ENDSThe componentSynonym forcomes after thePAGE_END.last line of theExists for compatibility withlayout'spreviouscontentversions.For Western top-to-bottom left-to-rightPAGE_ENDorientations thisisequivalent to SOUTHpreferred. @seejava.awt.Component#getComponentOrientationPAGE_END @since 1.2
Class BorderLayout, String BEFORE_FIRST_LINETheSynonymcomponent goes at the end of the line directionforthe layoutLINE_END.For WesternExiststop-to-bottomforleft-to-rightcompatibilityorientations thiswith previousisversions.equivalentLINE_ENDto EASTis preferred. @seejava.awt.Component#getComponentOrientationLINE_END @since 1.2
Class BorderLayout, String BEFORE_LINE_BEGINSThe componentSynonym forcomes before thePAGE_START.first line of theExists for compatibility withlayout'spreviouscontentversions.For Western top-to-bottom left-to-rightPAGE_STARTorientations thisisequivalent to NORTHpreferred. @seejava.awt.Component#getComponentOrientationPAGE_START @since 1.2
TheSynonymcomponent goes at the beginning of the line directionforthe layoutLINE_START.For WesternExiststop-to-bottomforleft-to-rightcompatibilityorientations thiswith previousisversions.equivalentLINE_STARTto WESTis preferred. @seejava.awt.Component#getComponentOrientationLINE_START @since 1.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 "Class Button, constructor Button()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
ActionEventwhich 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 specializeprocessMouseEventor it can register itself as a listener for mouse events by callingaddMouseListener. Both of these methods are defined byComponentthe abstract superclass of all components.When a button is pressed and released AWT sends an instance of
ActionEventto the button by callingprocessEventon the button. The button'sprocessEventmethod receives all events for the button; it passes an action event along by calling its ownprocessActionEventmethod. 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
ActionListenerand register the new listener to receive events from this button by calling the button'saddActionListenermethod. The application can make use of the button's action command as a messaging protocol. @version 1.58 0368 12/1403/0001 @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
Constructs a Button with no label. @exception HeadlessException if GraphicsEnvironment.isHeadless() returns true @see java.awt.GraphicsEnvironment#isHeadlessClass Button, constructor Button(String)
Constructs a Button with the specified label. @param label A string label for the button. @exception HeadlessException if GraphicsEnvironment.isHeadless() returns true @see java.awt.GraphicsEnvironment#isHeadlessClass Button, void addActionListener(ActionListener)
Adds the specified action listener to receive action events from this button. Action events occur when a user presses or releases the mouse over this button. If l is null no exception is thrown and no action is performed. @param l the action listener @seeClass Button, AccessibleContext getAccessibleContext()java.awt.event.ActionListener#removeActionListener @see #getActionListeners @see java.awt.Button#removeActionListenerevent.ActionListener @since JDK1.1
Gets theClass Button, EventListener[] getListeners(Class)AccessibleContextassociated with thisButton. For buttons theAccessibleContexttakes the form of anAccessibleAWTButton. A newAccessibleAWTButtoninstance is created if necessary. @return anAccessibleAWTButtonthat serves as theAccessibleContextof thisButton@beaninfo expert: true description: The AccessibleContext associated with this Button.
Class Button, String paramString()ReturnReturns an array of all thelistenersobjectsthat were addedcurrently registered astoFooListenersthe Buttonupon thiswithButton.addXXXListener()FooListenerswhere XXX isare registered using thenameaddFooListenerofmethod. You can specify thelistenerTypeargument.For example to get all ofwith a class literal such astheFooListener.class.ActionListener(s)Forforexampletheyou can querygivenaButtonbonefor itswouldactionwritelisteners with the following code:If no suchActionListener[] als = (ActionListener[])(b.getListeners(ActionListener.class));listenerlisteners existlist exists thenthis method returns an empty arrayis returned. @param listenerTypeTypethe type of listeners requested; this parameter should specify an interface that descends fromjava.util.EventListener@returnallan array oftheall objects registered asFooListeners on this button or an empty array if no such listenersof the specifiedhave been addedtype@exceptionsupported byClassCastException ifthislistenerTypebuttondoesn't specify a class or interface that implementsjava.util.EventListener@see #getActionListeners @since 1.3
ReturnsClass Button, void processActionEvent(ActionEvent)the parametera string representing the state of thisbuttonButton. Thisstringmethod isusefulintended to be used only for debugging purposes and the content and format of the returned string may vary between implementations. The returned string may be empty but may not benull. @return the parameter string of this button.
Processes action events occurring on this button by dispatching them to any registeredClass Button, void processEvent(AWTEvent)ActionListenerobjects.This method is not called unless action events are enabled for this button. Action events are enabled when one of the following occurs:
- An
ActionListenerobject is registered viaaddActionListener.- Action events are enabled via
enableEvents.Note that if the event parameter is
nullthe behavior is unspecified and may result in an exception. @param e the action event.@see java.awt.event.ActionListener @see java.awt.Button#addActionListener @see java.awt.Component#enableEvents @since JDK1.1
Processes events on this button. If an event is an instance ofClass Button, void removeActionListener(ActionListener)ActionEventthis method invokes theprocessActionEventmethod. Otherwise it invokesprocessEventon the superclass.Note that if the event parameter is
nullthe behavior is unspecified and may result in an exception. @param e the event.@see java.awt.event.ActionEvent @see java.awt.Button#processActionEvent @since JDK1.1
Removes the specified action listener so that it no longer receives action events from this button. Action events occur when a user presses or releases the mouse over this button. If l is null no exception is thrown and no action is performed. @param l the action listener @seejava.awt.event.ActionListener#addActionListener @see #getActionListeners @see java.awt.Button#addActionListenerevent.ActionListener @since JDK1.1
AClass Canvas, void paint(Graphics)Canvascomponent 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
Canvasclass in order to get useful functionality such as creating a custom component. Thepaintmethod must be overridden in order to perform custom graphics on the canvas. @version 1.28 0332 12/1503/0001 @author Sami Shaio @since JDK1.0
Class Canvas, void update(Graphics)ThisPaintsmethod is called to repaintthis canvas.Most applications that subclass
Canvasshould override this method in order to perform some useful operation. The paint method provided by Canvas redrawsthis(typicallycanvas'scustomrectangle inpainting of thebackground colorcanvas).Thegraphics context's origin (0default0)operation isthe top-leftsimplycorner of thisto clear the canvas.ItsApplicationsclipping region is the area of the contextthat override this method need not call super.paint(g). @param g thegraphicsspecified Graphics context.@seejava.awt.#update(Graphics) @see Component#paint(Graphics)
Updates thiscomponentcanvas.
The AWT callsThisthemethodupdateismethodcalled in response to a call torepaint.update or paintYou can assume that theThebackgroundcanvas isnotfirst cleared. The updatemethod ofComponent does the following: Clears this componentby filling it with the background color. Sets the color of the graphics context to bethe foregroundandcolor of thisthen completely redrawncomponent.byCallscalling thiscomponentcanvas'spaintmethodto completely redraw this component. Note:The origin of the graphics context itsapplications that override this method should either call super.update(0 0g)coordinate point is the top-left corner of this component. The clipping regionorofincorporate thegraphicsfunctionalitycontext is thedescribedbounding rectangle of this componentabove into their own code. @param g the specifiedcontext to use forGraphicsupdating.context @seejava.awt.Component#paint(Graphics) @seejava.awt.Component#repaintupdate(Graphics)@since JDK1.0
AClass CardLayout, void removeLayoutComponent(Component)CardLayoutobject 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 aCardLayoutobject 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.
CardLayoutdefines a set of methods that allow an application to flip through these cards sequentially or to show a specified card. TheCardLayouCardLayout#addLayoutComponent method can be used to associate a string identifier with a given card for fast random access. @version 1.30 0635 12/3003/0001 @author Arthur van Hoff @see java.awt.Container @since JDK1.0
Removes the specified component from the layout.If the card was visible on top the next card underneath it is shown.@param comp the component to be removed. @see java.awt.Container#remove(java.awt.Component) @see java.awt.Container#removeAll()
A check box is a graphical component that can be in either an "on" (Class Checkbox, constructor Checkbox()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
oneis in the "on" state and the other two are in the "off" state. In this example which uses theGridLayoutclass 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
CheckboxGroupclass. 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.59 0372 12/1403/0001 @author Sami Shaio @see java.awt.GridLayout @see java.awt.CheckboxGroup @since JDK1.0
Creates a check box with no label. The state of this check box is set to "off " and it is not part of any check box group. @exception HeadlessException if GraphicsEnvironment.isHeadless() returns true @see java.awt.GraphicsEnvironment#isHeadlessClass Checkbox, constructor Checkbox(String)
Creates a check box with the specified label. The state of this check box is set to "off " and it is not part of any check box group. @param label a string label for this check box orClass Checkbox, constructor Checkbox(String, CheckboxGroup, boolean)nullfor no label. @exception HeadlessException ifGraphicsEnvironment.isHeadlessreturnstrue@see java.awt.GraphicsEnvironment#isHeadless
Class Checkbox, constructor Checkbox(String, boolean)ConstructsCreates aCheckboxcheck box with the specified labelset toin the specifiedstatecheck box group andinset to the specifiedcheck box groupstate. @param label a string label for this check box ornullfor no label. @param group a check box group for this check box ornullfor no group. @param state the initial state of this check box. @exception HeadlessException ifGraphicsEnvironment.isHeadlessreturnstrue@see java.awt.GraphicsEnvironment#isHeadless @since JDK1.1
Creates a check box with the specified label and sets the specified state. This check box is not part of any check box group. @param label a string label for this check box orClass Checkbox, constructor Checkbox(String, boolean, CheckboxGroup)nullfor no label.@param state the initial state of this check box @exception HeadlessException ifGraphicsEnvironment.isHeadlessreturnstrue@see java.awt.GraphicsEnvironment#isHeadless
Class Checkbox, void addItemListener(ItemListener)CreatesConstructs acheck boxCheckbox with the specified labelinset to the specifiedcheck box groupstate andset toin the specifiedstatecheck box group. @param label a string label for this check box ornullfor no label. @param state the initial state of this check box. @param group a check box group for this check box ornullfor no group. @exception HeadlessException ifGraphicsEnvironment.isHeadlessreturnstrue@see java.awt.GraphicsEnvironment#isHeadless @since JDK1.1
Adds the specified item listener to receive item events from this check box. Item events are sent to listeners in response to user input but not in response to calls to setState(). If l is null no exception is thrown and no action is performed. @param l the item listener @seeClass Checkbox, CheckboxGroup getCheckboxGroup()java.awt.event.ItemEvent#removeItemListener @see #getItemListeners @see #setState @see java.awt.event.ItemListenerItemEvent @see java.awt.Checkbox#removeItemListenerevent.ItemListener @since JDK1.1
Determines this check box's group. @return this check box's group orClass Checkbox, String getLabel()nullif the check box is not part of a check box group. @seejava.awt.Checkbox#setCheckboxGroup
Gets the label of this check box. @return the label of this check box orClass Checkbox, EventListener[] getListeners(Class)nullif this check box has no label. @seejava.awt.Checkbox#setLabel
Class Checkbox, boolean getState()ReturnReturns an array of all thelistenersobjectsthat were addedcurrently registered astoFooListenersthe Checkboxupon thiswithCheckbox.addXXXListener()FooListenerswhere XXX isare registered using thenameaddFooListenerofmethod. You can specify thelistenerTypeargument.For example to get all ofwith a class literal such astheFooListener.class.ItemListener(s)Forforexampletheyou can querygivenaCheckboxconefor itswoulditemwritelisteners with the following code:If no suchItemListener[] ils = (ItemListener[])(c.getListeners(ItemListener.class));listenerlisteners existlist exists thenthis method returns an empty arrayis returned. @param listenerTypeTypethe type of listeners requested; this parameter should specify an interface that descends fromjava.util.EventListener@returnallan array oftheall objects registered asFooListeners on this checkbox or an empty array if no such listenersof the specifiedhave been addedtype@exceptionsupported byClassCastException ifthislistenerTypecheckboxdoesn't specify a class or interface that implementsjava.util.EventListener@see #getItemListeners @since 1.3
Determines whether this check box is in the "on" or "off" state. The boolean valueClass Checkbox, String paramString()trueindicates the "on" state andfalseindicates the "off" state. @return the state of this check box as a boolean value.@seejava.awt.Checkbox#setState
ReturnsClass Checkbox, void processEvent(AWTEvent)the parametera string representing the state of thischeck boxCheckbox. Thisstringmethod isusefulintended to be used only for debugging purposes and the content and format of the returned string may vary between implementations. The returned string may be empty but may not benull. @return the parameter string of this check box.
Processes events on this check box. If the event is an instance ofClass Checkbox, void processItemEvent(ItemEvent)ItemEventthis method invokes theprocessItemEventmethod. Otherwise it calls its superclass'sprocessEventmethod.Note that if the event parameter is
nullthe behavior is unspecified and may result in an exception. @param e the event.@see java.awt.event.ItemEvent @seejava.awt.Checkbox#processItemEvent @since JDK1.1
Processes item events occurring on this check box by dispatching them to any registeredClass Checkbox, void removeItemListener(ItemListener)ItemListenerobjects.This method is not called unless item events are enabled for this component. Item events are enabled when one of the following occurs:
- An
ItemListenerobject is registered viaaddItemListener.- Item events are enabled via
enableEvents.Note that if the event parameter is
nullthe behavior is unspecified and may result in an exception. @param e the item event.@see java.awt.event.ItemEvent @see java.awt.event.ItemListener @seejava.awt.Checkbox#addItemListener @see java.awt.Component#enableEvents @since JDK1.1
Removes the specified item listener so that the item listener no longer receives item events from this check box. If l is null no exception is thrown and no action is performed. @param l the item listener @seeClass Checkbox, void setCheckboxGroup(CheckboxGroup)java.awt.event.ItemEvent#addItemListener @see #getItemListeners @see java.awt.event.ItemListenerItemEvent @see java.awt.Checkbox#addItemListenerevent.ItemListener @since JDK1.1
Sets this check box's group to be the specified check box group. If this check box is already in a different check box group it is first taken out of that group. @param g the new check box group orClass Checkbox, void setLabel(String)nullto remove this check box from any check box group. @seejava.awt.Checkbox#getCheckboxGroup
Sets this check box's label to be the string argument. @param label a string to set as the new label orClass Checkbox, void setState(boolean)nullfor no label. @seejava.awt.Checkbox#getLabel
Sets the state of this check box to the specified state. The boolean valuetrueindicates the "on" state andfalseindicates the "off" state.Note that this method should be primarily used to initialize the state of the checkbox. Programmatically setting the state of the checkbox will not trigger an
ItemEvent. The only way to trigger anItemEventis by user interaction. @param state the boolean state of the check box.@seejava.awt.Checkbox#getState
TheCheckboxGroupclass is used to group together a set ofCheckboxbuttons.Exactly one check box button in a
CheckboxGroupcan 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.
29 0230 12/0203/0001 @author Sami Shaio @see java.awt.Checkbox @since JDK1.0
This class represents a check box that can be included in a menu.Class CheckboxMenuItem, constructor CheckboxMenuItem()ClickingSelectingonthe 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
Checkshows 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
ItemEventtheprocessEventmethod examines the event and passes it along toprocessItemEvent. The latter method redirects the event to anyItemListenerobjects that have registered an interest in item events generated by this menu item. @version 1.49 0362 12/1403/0001 @author Sami Shaio @see java.awt.event.ItemEvent @see java.awt.event.ItemListener @since JDK1.0
Create a check box menu item with an empty label. The item's state is initially set to "off." @exception HeadlessException if GraphicsEnvironment.isHeadless() returns true @see java.awt.GraphicsEnvironment#isHeadless @since JDK1.1Class CheckboxMenuItem, constructor CheckboxMenuItem(String)
Create a check box menu item with the specified label. The item's state is initially set to "off." @param label a string label for the check box menu item or null for an unlabeled menu item. @exception HeadlessException if GraphicsEnvironment.isHeadless() returns true @see java.awt.GraphicsEnvironment#isHeadless
Class CheckboxMenuItem, constructor CheckboxMenuItem(String, boolean)Create a check box menu item with the specified label and state. @param label a string label for the check box menu item orClass CheckboxMenuItem, void addItemListener(ItemListener)nullfor an unlabeled menu item. @param state the initial state of the menu item wheretrueindicates "on" andfalseindicates "off." @exception HeadlessException if GraphicsEnvironment.isHeadless() returns true @see java.awt.GraphicsEnvironment#isHeadless @since JDK1.1
Adds the specified item listener to receive item events from this check box menu item. Item events are sent in response to user actions but not in response to calls to setState(). If l is null no exception is thrown and no action is performed. @param l the item listener @seeClass CheckboxMenuItem, EventListener[] getListeners(Class)java.awt.event.ItemEvent#removeItemListener @see #getItemListeners @see #setState @see java.awt.event.ItemListenerItemEvent @see java.awt.Choice#removeItemListenerevent.ItemListener @since JDK1.1
Class CheckboxMenuItem, boolean getState()ReturnReturns an array of all thelistenersobjectsthat were addedcurrently registered astoFooListenersthe CheckboxMenuItemupon thiswithCheckboxMenuItem.addXXXListener()FooListenerswhere XXX isare registered using thenameaddFooListenerofmethod. You can specify thelistenerTypeargument.For example to get all ofwith a class literal such astheFooListener.class.ItemListener(s)Forforexampletheyou cangivenquery aCheckboxMenuItemconefor its item listeners withwouldthe followingwritecode:If no suchItemListener[] ils = (ItemListener[])(c.getListeners(ItemListener.class));listenerlisteners existlist exists thenthis method returns an empty arrayis returned. @param listenerTypeTypethe type of listeners requested; this parameter should specify an interface that descends fromjava.util.EventListener@returnallan array oftheall objects registered asFooListeners on this checkbox menuitem or an empty array if no such listenersof the specifiedhave been addedtype@exceptionsupported byClassCastException ifthislistenerTypecheckboxdoesn'tmenuspecifyitema class or interface that implementsjava.util.EventListener@see #getItemListeners @since 1.3
Determines whether the state of this check box menu item is "on" or "off." @return the state of this check box menu item whereClass CheckboxMenuItem, String paramString()trueindicates "on" andfalseindicates "off." @seejava.awt.CheckboxMenuItem#setState
ReturnsClass CheckboxMenuItem, void processEvent(AWTEvent)the parametera string representing the state of thischeck box menu itemCheckBoxMenuItem. Thisstringmethod isusefulintended to be used only for debugging purposes and the content and format of the returned string may vary between implementations. The returned string may be empty but may not benull. @return the parameter string of this check box menu item.
Processes events on this check box menu item. If the event is an instance ofClass CheckboxMenuItem, void processItemEvent(ItemEvent)ItemEventthis method invokes theprocessItemEventmethod. If the event is not an item event it invokesprocessEventon the superclass.Check box menu items currently support only item events.
Note that if the event parameter is
nullthe behavior is unspecified and may result in an exception. @param e the event @see java.awt.event.ItemEvent @seejava.awt.CheckboxMenuItem#processItemEvent @since JDK1.1
Processes item events occurring on this check box menu item by dispatching them to any registeredClass CheckboxMenuItem, void removeItemListener(ItemListener)ItemListenerobjects.This method is not called unless item events are enabled for this menu item. Item events are enabled when one of the following occurs:
- An
ItemListenerobject is registered viaaddItemListener.- Item events are enabled via
enableEvents.Note that if the event parameter is
nullthe behavior is unspecified and may result in an exception. @param e the item event.@see java.awt.event.ItemEvent @see java.awt.event.ItemListener @seejava.awt.CheckboxMenuItem#addItemListener @see java.awt.MenuItem#enableEvents @since JDK1.1
Removes the specified item listener so that it no longer receives item events from this check box menu item. If l is null no exception is thrown and no action is performed. @param l the item listener @seeClass CheckboxMenuItem, void setState(boolean)java.awt.event.ItemEvent#addItemListener @see #getItemListeners @see java.awt.event.ItemListenerItemEvent @see java.awt.Choice#addItemListenerevent.ItemListener @since JDK1.1
Sets this check box menu item to the specifed state. The boolean valuetrueindicates "on" whilefalseindicates "off."@paramNote
bthat this method should be primarily used to initialize thebooleanstate of the check box menu item. Programmatically setting the state ofthisthe check box menu item will not trigger anItemEvent. The only way to trigger anItemEventis by user interaction. @param btrueif the check box menu item is on otherwisefalse@seejava.awt.CheckboxMenuItem#getState
TheClass Choice, constructor Choice()Choiceclass 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
Choicecomponents and the behavior ofsetSize()/getSize()is bound by such limitations. Native GUIChoicecomponents' size are often bound by such attributes as font size and length of items contained within theChoice.@version 1.
64 0378 12/1403/0001 @author Sami Shaio @author Arthur van Hoff @since JDK1.0
Creates a new choice menu. The menu initially has no items in it.Class Choice, void add(String)By default the first item added to the choice menu becomes the selected item until a different selection is made by the user by calling one of the
selectmethods. @exception HeadlessException if GraphicsEnvironment.isHeadless() returns true @see java.awt.ChoiceGraphicsEnvironment#isHeadless @see #select(int) @seejava.awt.Choice#select(java.lang.String)
Adds an item to thisClass Choice, void addItem(String)Choicemenu. @param item the item to be added @exception NullPointerException if the item's value isnull.@since JDK1.1
Obsolete as of Java 2 platform v1.1. Please use theClass Choice, void addItemListener(ItemListener)addmethod instead.Adds an item to this
Choicemenu. @param item the item to be added @exception NullPointerExceptionIfif the item's value is equal tonull.
Adds the specified item listener to receive item events from thisClass Choice, void addNotify()Choicemenu. Item events are sent in response to user input but not in response to calls toselect. If l isnullno exception is thrown and no action is performed. @param l the item listener.@seejava.awt.event.ItemEvent#removeItemListener @see #getItemListeners @see #select @see java.awt.event.ItemListenerItemEvent @see java.awt.Choice#removeItemListenerevent.ItemListener @since JDK1.1
Creates theClass Choice, AccessibleContext getAccessibleContext()Choice's peer. This peer allows us to change the look of theChoicewithout changing its functionality. @see java.awt.Toolkit#createChoice(java.awt.Choice) @see java.awt.Component#getToolkit()
Gets theClass Choice, String getItem(int)AccessibleContextassociated with thisChoice. ForChoicecomponents theAccessibleContexttakes the form of anAccessibleAWTChoice. A newAccessibleAWTChoiceinstance is created if necessary. @return anAccessibleAWTChoicethat serves as theAccessibleContextof thisChoice
Gets the string at the specified index in thisClass Choice, int getItemCount()Choicemenu. @param index the index at which to begin.@seejava.awt.Choice#getItemCount
Returns the number of items in thisClass Choice, EventListener[] getListeners(Class)Choicemenu. @seereturnjava.awt.the number of items in thisChoice menu @see #getItem @since JDK1.1
Class Choice, String getSelectedItem()ReturnReturns an array of all thelistenersobjectsthat were addedcurrently registered astoFooListenersthe Choiceupon thiswithChoice.addXXXListener()FooListenerswhere XXX isare registered using thenameaddFooListenerofmethod. You can specify thelistenerTypeargument.For example to get all ofwith a class literal such astheFooListener.class.ItemListener(s)Forforexampletheyou can querygivenaChoiceconefor itswoulditemwritelisteners with the following code:If no suchItemListener[] ils = (ItemListener[])(c.getListeners(ItemListener.class));listenerlisteners existlist exists thenthis method returns an empty arrayis returned. @param listenerTypeTypethe type of listeners requested; this parameter should specify an interface that descends fromjava.util.EventListener@returnallan array oftheall objects registered asFooListeners on this choice or an empty array if no such listenersof the specifiedhave been addedtype@exceptionsupported byClassCastException ifthislistenerTypechoicedoesn't specify a class or interface that implementsjava.util.EventListener@see #getItemListeners @since 1.3
Gets a representation of the current choice as a string. @return a string representation of the currently selected item in this choice menuClass Choice, Object[] getSelectedObjects().@seejava.awt.Choice#getSelectedIndex
Returns an array (length 1) containing the currently selected item. If this choice has no items returns null. @see ItemSelectable
Class Choice, void insert(String, int)Inserts the item into this choice at the specified position. Existing items at an index greater than or equal toClass Choice, String paramString()indexare shifted up by one to accommodate the new item. Ifindexis greater than or equal to the number of items in this choiceitemis added to the end of this choice.If the item is the first one being added to the choice then the item becomes selected. Otherwise if the selected item was one of the items shifted the first item in the choice becomes the selected item. If the selected item was no among those shifted it remains the selected item.
@param item the non-nullitem to be inserted @param index the position at which the item should be inserted @exception IllegalArgumentException if index is less than 0.
ReturnsClass Choice, void processEvent(AWTEvent)the parametera string representing the state of thischoiceChoicemenu. Thisstringmethod isusefulintended to be used only for debugging purposes and the content and format of the returned string may vary between implementations. The returned string may be empty but may not benull. @return the parameter string of thisChoicemenu.
Processes events on this choice. If the event is an instance ofClass Choice, void processItemEvent(ItemEvent)ItemEventit invokes theprocessItemEventmethod. Otherwise it calls its superclass'sprocessEventmethod.Note that if the event parameter is
nullthe behavior is unspecified and may result in an exception. @param e the event.@see java.awt.event.ItemEvent @seejava.awt.Choice#processItemEvent @since JDK1.1
Processes item events occurring on thisClass Choice, void remove(String)Choicemenu by dispatching them to any registeredItemListenerobjects.This method is not called unless item events are enabled for this component. Item events are enabled when one of the following occurs:
- An
ItemListenerobject is registered viaaddItemListener.- Item events are enabled via
enableEvents.Note that if the event parameter is
nullthe behavior is unspecified and may result in an exception. @param e the item event.@see java.awt.event.ItemEvent @see java.awt.event.ItemListener @seejava.awt.Choice#addItemListener @see java.awt.Component#enableEvents @since JDK1.1
Class Choice, void remove(int)RemoveRemoves the first occurrence ofitemfrom theChoicemenu. If the item being removed is the currently selected item then the first item in the choice becomes the selected item. Otherwise the currently selected item remains selected (and the selected index is updated accordingly). @param item the item to remove from thisChoicemenu.@exception IllegalArgumentException if the item doesn't exist in the choice menu.@since JDK1.1
Removes an item from the choice menu at the specified position. If the item being removed is the currently selected item then the first item in the choice becomes the selected item. Otherwise the currently selected item remains selected (and the selected index is @param position the position of the itemClass Choice, void removeAll().@throws IndexOutOfBoundsException if the specified position is out of bounds @since JDK1.1
Removes all items from the choice menu. @seeClass Choice, void removeItemListener(ItemListener)java.awt.Choice#remove @since JDK1.1
Removes the specified item listener so that it no longer receives item events from thisClass Choice, void select(String)Choicemenu. If l isnullno exception is thrown and no action is performed. @param l the item listener.@seejava.awt.event.ItemEvent#addItemListener @see #getItemListeners @see java.awt.event.ItemListenerItemEvent @see java.awt.Choice#addItemListenerevent.ItemListener @since JDK1.1
Sets the selected item in thisClass Choice, void select(int)Choicemenu to be the item whose name is equal to the specified string. If more than one item matches (is equal to) the specified string the one with the smallest index is selected.Note that this method should be primarily used to initially select an item in this component. Programmatically calling this method will not trigger an
ItemEvent. The only way to trigger anItemEventis by user interaction. @param str the specified string @seejava.awt.Choice#getSelectedItem @seejava.awt.Choice#getSelectedIndex
Sets the selected item in thisChoicemenu to be the item at the specified position.Note that this method should be primarily used to initially select an item in this component. Programmatically calling this method will not trigger an
ItemEvent. The only way to trigger anItemEventis by user interaction. @param pos the positon of the selected item.@exception IllegalArgumentException if the specified position isinvalid.greater than the number of items or less than zero @seejava.awt.Choice#getSelectedItem @seejava.awt.Choice#getSelectedIndex
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.The
Componentclass is the abstract superclass of the nonmenu-related Abstract Window Toolkit components. ClassComponentcan also be extended directly to create a lightweight component. A lightweight component is a component that is not associated with a native opaque window.
Serialization
It is important to note that only AWT listeners which conform to theSerializableprotocol will be saved when the object is stored. If an AWT object has listeners that aren't marked serializable they will be dropped atwriteObjecttime. Developers will need as always to consider the implications of making an object serializable. One situation to watch out for is this:import java.awt.*; import java.awt.event.*; import java.io.Serializable; class MyApp implements ActionListener Serializable { BigObjectThatShouldNotBeSerializedWithAButton bigOne; Button aButton = new Button(); MyApp() { // Oops now aButton has a listener with a reference // to bigOne aButton.addActionListener(this); } public void actionPerformed(ActionEvent e) { System.out.println("Hello There"); } }In this example serializingaButtonby itself will causeMyAppand everything it refers to to be serialized as well. The problem is that the listener is serializable by coincidence not by design. To separate the decisions aboutMyAppand theActionListenerbeing serializable one can use a nested class as in the following example:import java.awt.*; import java.awt.event.*; import java.io.Serializable; class MyApp java.io.Serializable { BigObjectThatShouldNotBeSerializedWithAButton bigOne; Button aButton = new Button(); class MyActionListener implements ActionListener { public void actionPerformed(ActionEvent e) { System.out.println("Hello There"); } } MyApp() { aButton.addActionListener(new MyActionListener()); } }@version 1.265 02330 12/2803/0001 @author Arthur van Hoff @author Sami Shaio
Checks whether the specified point is within this object's bounds where the point's x and y coordinates are defined to be relative to the coordinate system of the object. @param p theClass Component.AccessibleAWTComponent, Accessible getAccessibleAt(Point)Pointrelative to the coordinate system of the object @return true if object containsPoint; otherwise false
Returns theClass Component.AccessibleAWTComponent, Accessible getAccessibleChild(int)Accessiblechild if one exists contained at the local coordinatePoint. Otherwise returnsnull. @param pThethe point defining the top-left corner of theAccessiblegiven in the coordinate space of the object's parent.@return theAccessibleif it exists at the specified location; elsenull
Class Component.AccessibleAWTComponent, int getAccessibleChildrenCount()ReturnReturns the nthAccessiblechild of the object. @param i zero-based index of child @return the nthAccessiblechild of the object
Returns the number of accessible children in the object. If all of the children of this object implementClass Component.AccessibleAWTComponent, AccessibleComponent getAccessibleComponent()Accessiblethanthen this method should return the number of children of this object. @return the number of accessible children in the object.
Class Component.AccessibleAWTComponent, String getAccessibleDescription()GetGets theAccessibleComponentassociated with this object if one exists. Otherwise returnnull. @return the component
Class Component.AccessibleAWTComponent, int getAccessibleIndexInParent()GetGets the accessible description of this object. This should be a concise localized description of what this object is - what is its meaning to the user. If the object has a tooltip the tooltip text may be an appropriate string to return assuming it contains a concise description of the object (instead of just the name of the object - e.g. a "Save" icon on a toolbar that had "save" as the tooltip text shouldn't return the tooltip text as the description but something like "Saves the current text document" instead). @return the localized description of the object -- can benullif this object does not have a description @see javax.accessibility.AccessibleContext#setAccessibleDescription
Class Component.AccessibleAWTComponent, String getAccessibleName()GetGets the index of this object in its accessible parent. @return the index of this object in its parent; or -1 if this object does not have an accessible parent.@see #getAccessibleParent
Class Component.AccessibleAWTComponent, Accessible getAccessibleParent()GetGets the accessible name of this object. This should almost never returnjava.awt.Component.getName()as that generally isn't a localized name and doesn't have meaning for the user. If the object is fundamentally a text object (e.g. a menu item) the accessible name should be the text of the object (e.g. "save"). If the object has a tooltip the tooltip text may also be an appropriate String to return. @return the localized name of the object -- can benullif this object does not have a name @see javax.accessibility.AccessibleContext#setAccessibleName
Class Component.AccessibleAWTComponent, AccessibleRole getAccessibleRole()GetGets theAccessibleparent of this object. If the parent of this object implementsAccessiblethis method should simply returngetParent. @return the()Accessibleparent of this object -- can benullif this object does not have anAccessibleparent
Class Component.AccessibleAWTComponent, AccessibleStateSet getAccessibleStateSet()GetGets the role of this object. @return an instance ofAccessibleRoledescribing the role of the object @see javax.accessibility.AccessibleRole
Class Component.AccessibleAWTComponent, Color getBackground()GetGets the state of this object. @return an instance ofAccessibleStateSetcontaining the current state set of the object @see javax.accessibility.AccessibleState
Class Component.AccessibleAWTComponent, Rectangle getBounds()GetGets the background color of this object. @return the background color if supported of the object; otherwisenull
Gets the bounds of this object in the form of a Rectangle object. The bounds specify this object's width height and location relative to its parent. @returnClass Component.AccessibleAWTComponent, Cursor getCursor()Aa rectangle indicating this component's bounds;nullif this object is not on the screen.
Class Component.AccessibleAWTComponent, Font getFont()GetGets theCursorof this object. @return theCursorif supported of the object; otherwisenull
Class Component.AccessibleAWTComponent, FontMetrics getFontMetrics(Font)GetGets theFontof this object. @return theFontif supported for the object; otherwisenull
Class Component.AccessibleAWTComponent, Color getForeground()GetGets theFontMetricsof this object. @param f theFont@return theFontMetricsif supported the object; otherwisenull@see #getFont
Class Component.AccessibleAWTComponent, Locale getLocale()GetGets the foreground color of this object. @return the foreground color if supported of the object; otherwisenull
Class Component.AccessibleAWTComponent, Point getLocation()ReturnReturns the locale of this object. @return the locale of this object
Gets the location of the object relative to the parent in the form of a point specifying the object's top-left corner in the screen's coordinate space. @returnClass Component.AccessibleAWTComponent, Point getLocationOnScreen()Anan instance of Point representing the top-left corner of theobjectsobject's bounds in the coordinate space of the screen;nullif this object or its parent are not on the screen
Returns the location of the object on the screen. @return location of object on screen -- can be null if this object is not on the screen
Class Component.AccessibleAWTComponent, Dimension getSize()Returns the size of this object in the form of aClass Component.AccessibleAWTComponent, boolean isEnabled()Dimensionobject. The height field of theDimensionobject contains this objects's height and the width field of theDimensionobject contains this object's width. @returnAaDimensionobject that indicates the size of this component;nullif this object is not on the screen
Class Component.AccessibleAWTComponent, boolean isShowing()DetermineDetermines if the object is enabled. @return true if object is enabled; otherwise false
Class Component.AccessibleAWTComponent, boolean isVisible()DetermineDetermines if the object is showing. This is determined by checking the visibility of the object and ancestors of the object. Note: this will return true even if the object is obscured by another (for example it happens to be underneath a menu that was pulled down). @return true if object is showing; otherwise false
Class Component.AccessibleAWTComponent, void setBackground(Color)DetermineDetermines if the object is visible. Note: this means that the object intends to be visible; however it may not in fact be showing on the screen because one of the objects that this object is contained by is not visible. To determine if an object is showing on the screen useisShowing. @return true if object is visible; otherwise false()
Class Component.AccessibleAWTComponent, void setBounds(Rectangle)SetSets the background color of this object. (For transparency seeisOpaque.) @param c the newColorfor the background @see Component#isOpaque
Sets the bounds of this object in the form of aClass Component.AccessibleAWTComponent, void setCursor(Cursor)Rectangleobject. The bounds specify this object's width height and location relative to its parent. @paramAa rectangle indicating this component's bounds
Class Component.AccessibleAWTComponent, void setEnabled(boolean)SetSets theCursorof this object. @param c the newCursorfor the object
Class Component.AccessibleAWTComponent, void setFont(Font)SetSets the enabled state of the object. @param b if true enables this object; otherwise disables it
Class Component.AccessibleAWTComponent, void setForeground(Color)SetSets theFontof this object. @param f the newFontfor the object
Class Component.AccessibleAWTComponent, void setLocation(Point)SetSets the foreground color of this object. @param c the newColorfor the foreground
Sets the location of the object relative to the parent. @param p the coordinates of the objectClass Component.AccessibleAWTComponent, void setSize(Dimension)
Resizes this object so that it has width width and height. @param d -Class Component.AccessibleAWTComponent, void setVisible(boolean)Thethe dimension specifying the new size of the object.
SetSets the visible state of the object. @param b if true shows this object; otherwise hides it
Adds the specified popup menu to the component. @param popup the popup menu to be added to the component. @seeClass Component, void addComponentListener(ComponentListener)java.awt.Component#remove(java.awt.MenuComponent) @since JDK1.1
Adds the specified component listener to receive component events from this component. If listenerClass Component, void addFocusListener(FocusListener)l isnullno exception is thrown and no action is performed. @param l the componentlistenerlistene. @see java.awt.event.ComponentEvent @see java.awt.event.ComponentListener @seejava.awt.Component#removeComponentListener @see #getComponentListeners @since JDK1.1
Adds the specified focus listener to receive focus events from this component when this component gains input focus. If listenerClass Component, void addHierarchyBoundsListener(HierarchyBoundsListener)l isnullno exception is thrown and no action is performed. @param l the focus listener.@see java.awt.event.FocusEvent @see java.awt.event.FocusListener @seejava.awt.Component#removeFocusListener @see #getFocusListeners @since JDK1.1
Adds the specified hierarchy bounds listener to receive hierarchy bounds events from this component when the hierarchy to which this container belongs changes. If listenerClass Component, void addHierarchyListener(HierarchyListener)l isnullno exception is thrown and no action is performed. @param l the hierarchy bounds listener.@see java.awt.event.HierarchyEvent @see java.awt.event.HierarchyBoundsListener @seejava.awt.Component#removeHierarchyBoundsListener @see #getHierarchyBoundsListeners @since 1.3
Adds the specified hierarchy listener to receive hierarchy changed events from this component when the hierarchy to which this container belongs changes. If listenerClass Component, void addInputMethodListener(InputMethodListener)l isnullno exception is thrown and no action is performed. @param l the hierarchy listener.@see java.awt.event.HierarchyEvent @see java.awt.event.HierarchyListener @seejava.awt.Component#removeHierarchyListener @see #getHierarchyListeners @since 1.3
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 overridesClass Component, void addKeyListener(KeyListener)getInputMethodRequeststo return anInputMethodRequestsinstance. If listenerl isnullno exception is thrown and no action is performed. @param l the input method listener.@see java.awt.event.InputMethodEvent @see java.awt.event.InputMethodListener @seejava.awt.Component#removeInputMethodListener @seejava.awt.Component#getInputMethodListeners @see #getInputMethodRequests @since 1.2
Adds the specified key listener to receive key events from this component. If l is null no exception is thrown and no action is performed. @param l the key listener. @see java.awt.event.KeyEvent @see java.awt.event.KeyListener @seeClass Component, void addMouseListener(MouseListener)java.awt.Component#removeKeyListener @see #getKeyListeners @since JDK1.1
Adds the specified mouse listener to receive mouse events from this component. If listenerClass Component, void addMouseMotionListener(MouseMotionListener)l isnullno exception is thrown and no action is performed. @param l the mouse listener.@see java.awt.event.MouseEvent @see java.awt.event.MouseListener @seejava.awt.Component#removeMouseListener @see #getMouseListeners @since JDK1.1
Adds the specified mouse motion listener to receive mouse motion events from this component. If listenerClass Component, void addNotify()l isnullno exception is thrown and no action is performed. @param l the mouse motion listener.@see java.awt.event.MouseMotionEvent @see java.awt.event.MouseMotionListener @seejava.awt.Component#removeMouseMotionListener @see #getMouseMotionListeners @since JDK1.1
Makes thisClass Component, void addPropertyChangeListener(PropertyChangeListener)Componentdisplayable by connecting it to a native screen resource. This method is called internally by the toolkit and should not be called directly by programs. @seejava.awt.Component#isDisplayable @seejava.awt.Component#removeNotify @since JDK1.0
Class Component, void addPropertyChangeListener(String, PropertyChangeListener)AddAdds a PropertyChangeListener to the listener list. The listener is registered for all bound properties.A PropertyChangeEvent will getof this class including thefiredfollowing:inNote that if this Component is inheriting a bound property then no event will be fired in response to a change in the inherited property.
response- this
toComponent'sanfontexplicit("font")- this Component's
setFont setBackgroundbackground coloror("background")- this Component's
SetForeground onforeground colorthe("foreground")current- this
component.Component'sNotefocusabilitythat("focusable")if- this
theComponent'scurrent component is inheriting itsfocus traversal keys enabled stateforeground("focusTraversalKeysEnabled")background- this
orComponent'sfontSet of FORWARD_TRAVERSAL_KEYS ("forwardFocusTraversalKeys")- this Component's Set of BACKWARD_TRAVERSAL_KEYS ("backwardFocusTraversalKeys")
- this Component's Set
fromofitsUP_CYCLE_TRAVERSAL_KEYScontainer("upCycleFocusTraversalKeys")If listener is null no exception is thrown and no action is performed. @param listener
Thethe PropertyChangeListener to be added @see #removePropertyChangeListener @see #getPropertyChangeListeners @see #addPropertyChangeListener(java.lang.String java.beans.PropertyChangeListener)
Class Component, int checkImage(Image, ImageObserver)AddAdds a PropertyChangeListener to the listener list for a specific property. Thelistenerspecifiedwillproperty may beinvokeduser-definedonly whenor oneaof thecallfollowing:onNote that
firePropertyChange- this
namesComponent's font ("font")- this Component's background color ("background")
- this Component's foreground color ("foreground")
- this Component's focusability ("focusable")
- this Component's focus traversal keys enabled state ("focusTraversalKeysEnabled")
- this Component's Set of FORWARD_TRAVERSAL_KEYS ("forwardFocusTraversalKeys")
- this Component's Set of BACKWARD_TRAVERSAL_KEYS ("backwardFocusTraversalKeys")
- this Component's Set of UP_CYCLE_TRAVERSAL_KEYS ("upCycleFocusTraversalKeys")
specificif this Component is inheriting a bound property then no event will be fired in response to a change in the inherited property.If listener is null no exception is thrown and no action is performed. @param propertyName
The nameone of the propertyto listennames listedon.above @param listenerThethe PropertyChangeListener to be added @see #removePropertyChangeListener(java.lang.String) @see #getPropertyChangeListeners(java.lang.String) @see #addPropertyChangeListener(java.beans.PropertyChangeListener)
Returns the status of the construction of a screen representation of the specified image.Class Component, int checkImage(Image, int, int, ImageObserver)This method does not cause the image to begin loading. An application must use the
prepareImagemethod to force the loading of an image.Information on the flags returned by this method can be found with the discussion of the
ImageObserverinterface. @param image theImageobject whose status is being checked.@param observer theImageObserverobject to be notified as the image is being prepared.@return the bitwise inclusive OR ofImageObserverflags indicating what information about the image is currently available.@seejava.awt.Component#prepareImage(java.awt.Image int int java.awt.image.ImageObserver) @seejava.awt.Toolkit#checkImage(java.awt.Image int int java.awt.image.ImageObserver) @see java.awt.image.ImageObserver @since JDK1.0
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
prepareImagemethod to force the loading of an image.The
checkImagemethod ofComponentcalls its peer'scheckImagemethod to calculate the flags. If this component does not yet have a peer the component's toolkit'scheckImagemethod is called instead.Information on the flags returned by this method can be found with the discussion of the
ImageObserverinterface. @param image theImageobject 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 theImageObserverobject to be notified as the image is being prepared.@return the bitwise inclusive OR ofImageObserverflags indicating what information about the image is currently available.@seejava.awt.Component#prepareImage(java.awt.Image int int java.awt.image.ImageObserver) @seejava.awt.Toolkit#checkImage(java.awt.Image int int java.awt.image.ImageObserver) @see java.awt.image.ImageObserver @since JDK1.0
Potentially coalesce an event being posted with an existing event. This method is called byClass Component, boolean contains(Point)EventQueue.postEventif 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) ornullto 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 unlessnullis returned.This implementation of
coalesceEventscoalesces 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 the new event is coalesced into a complexRepaintAreain the peer. The newEventAWTEventis always returned. @param existingEvent the event already on theEventQueue@param newEvent the event being posted to the.EventQueue@return a coalesced event or.nullindicating that no coalescing was done.
Checks whether this component "contains" the specified point where the point's x and y coordinates are defined to be relative to the coordinate system of this component. @param p the pointClass Component, boolean contains(int, int).@seejava.awt.Component#getComponentAt(java.awt.Point) @since JDK1.1
Checks whether this component "contains" the specified point whereClass Component, Image createImage(ImageProducer)xandyare defined to be relative to the coordinate system of this component. @param x the x coordinate of the point.@param y the y coordinate of the point.@seejava.awt.Component#getComponentAt(int int) @since JDK1.1
Creates an image from the specified image producer. @param producer the image producer @return the image producedClass Component, Image createImage(int, int).@since JDK1.0
Creates an off-screen drawable image to be used for double buffering. @param width the specified widthClass Component, void disableEvents(long).@param height the specified height.@return an off-screen drawable image which can be used for double buffering. The return value may benullif the component is not displayable. This will always happen ifGraphicsEnvironment.isHeadless()returnstrue. @see #isDisplayable @see GraphicsEnvironment#isHeadless @since JDK1.0
Disables the events defined by the specified event mask parameter from being delivered to this component. @param eventsToDisable the event mask defining the event types @seeClass Component, void dispatchEvent(AWTEvent)java.awt.Component#enableEvents @since JDK1.1
Dispatches an event to this component or one of its sub components. CallsClass Component, void enableEvents(long)processEventbefore returning for 1.1-style events which have been enabled for the()Component. @param e the event
Enables the events defined by the specified event mask parameter to be delivered to this component.Class Component, void enableInputMethods(boolean)Event types are automatically enabled when a listener for that event type is added to the component.
This method only needs to be invoked by subclasses of
Componentwhich desire to have the specified event types delivered toprocessEventregardless of whether or not a listener is registered. @param eventsToEnable the event mask defining the event types.@seejava.awt.Component#processEvent @seejava.awt.Component#disableEvents @see AWTEvent @since JDK1.1
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 disableClass Component, AccessibleContext getAccessibleContext().@seejava.awt.Component#processKeyEvent @since 1.2
Class Component, Color getBackground()GetGets theAccessibleContextassociated with thisComponent. The method implemented by this base class returns null. Classes that extendComponentshould implement this method to return theAccessibleContextassociated with the subclass. @return theAccessibleContextof thisComponent
Gets the background color of this component. @returnClass Component, Rectangle getBounds()Thisthis component's background color.;Ifif this component does not have a background color the background color of its parent is returned.@seejava.awt.Component#setBackground(java.awt.Color)@since JDK1.0
Gets the bounds of this component in the form of aClass Component, Rectangle getBounds(Rectangle)Rectangleobject. The bounds specify this component's width height and location relative to its parent. @returnAa rectangle indicating this component's bounds.@see #setBounds @see #getLocation @see #getSize
Class Component, ColorModel getColorModel()StoreStores the bounds of this component into "return value" rv and return rv. If rv isnulla newRectangleis allocated. This version ofgetBoundsis useful if the caller wants to avoid allocating a new()Rectangleobject on the heap. @param rv the return value modified to the components bounds @return rv
Gets the instance ofClass Component, Component getComponentAt(Point)ColorModelused to display the component on the output device. @returnThethe color model used by this component.@see java.awt.image.ColorModel @see java.awt.peer.ComponentPeer#getColorModel() @seejava.awt.Toolkit#getColorModel() @since JDK1.0
Returns the component or subcomponent that contains the specified point. @param p the pointClass Component, Component getComponentAt(int, int).@see java.awt.Component#contains @since JDK1.1
Determines if this component or one of its immediate subcomponents contains the (x y) location and if so returns the containing component. This method only looks one level deep. If the point (x y) is inside a subcomponent that itself has subcomponents it does not go looking down the subcomponent tree.Class Component, ComponentOrientation getComponentOrientation()The
locatemethod ofComponentsimply returns the component itself if the (x y) coordinate location is inside its bounding box andnullotherwise. @param x the x coordinate.@param y the y coordinate.@return the component or subcomponent that contains the (x y) location;nullif the location is outside this component.@seejava.awt.Component#contains(int int) @since JDK1.0
Class Component, Cursor getCursor()RetrieveRetrieves the language-sensitive orientation that is to be used to order the elements or text within this component.LayoutManagerandComponentsubclasses that wish to respect orientation should call this method to get the component's orientation before performing layout or drawing. @seejava.awt.ComponentOrientation @author Laura Werner IBM
Gets the cursor set in the component. If the component does not have a cursor set the cursor of its parent is returned. If noClass Component, DropTarget getDropTarget()Cursorcursor is set in the entire hierarchyCursor.DEFAULT_CURSORis returned. @see #setCursor @since JDK1.1
Class Component, Font getFont()GetGets theDropTargetassociated with thisComponent.
Gets the font of this component. @returnClass Component, FontMetrics getFontMetrics(Font)Thisthis component's font.;Ifif a font has not been set for this component the font of its parent is returned.@see #setFont @since JDK1.0
Gets the font metrics for the specified font. @param fontClass Component, Color getForeground()Thethe font for which font metrics is to be obtained.@returnThethe font metrics forfont.@param font the font.@return the font metrics for the specified font.@seejava.awt.Component#getFont @seejava.awt.Component#getPeer()@see java.awt.peer.ComponentPeer#getFontMetrics(java.awt.Font) @seejava.awt.Toolkit#getFontMetrics(java.awt.Font) @since JDK1.0
Gets the foreground color of this component. @returnClass Component, Graphics getGraphics()Thisthis component's foreground color.;Ifif this component does not have a foreground color the foreground color of its parent is returned.@see #setForeground @since JDK1.0 @beaninfo bound: true
Creates a graphics context for this component. This method will returnClass Component, GraphicsConfiguration getGraphicsConfiguration()nullif this component is currently not displayable. @returnAa graphics context for this component ornullif it has none.@seejava.awt.Component#paint @since JDK1.0
Class Component, int getHeight()GetGets theGraphicsConfigurationassociated with thisComponent. If theComponenthas not been assigned a specificGraphicsConfigurationtheGraphicsConfigurationof theComponentobject's top-level container is returned. If theComponenthas been created but not yet added to aContainerthis method returnsnull. @return theGraphicsConfigurationused by thisComponentornull@since 1.3
Class Component, InputContext getInputContext()ReturnReturns the current height of this component. This method is preferable to writingcomponent.getBounds().heightbecause it doesn't cause any heap allocations. @return the current height of this componentorcomponent.getSize().height.@since 1.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. @returnClass Component, InputMethodRequests getInputMethodRequests()Thethe input context used by this component.;Nullnullif no context can be determined.@since 1.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 anClass Component, EventListener[] getListeners(Class)InputMethodRequestsinstance. At the same time it also has to handle input method events. @return the input method request handler for this componentnullby default.@see #addInputMethodListener @since 1.2
Class Component, Locale getLocale()ReturnReturns an array of all thelistenersobjectsthat were addedcurrently registered astoFooListenersthe Componentupon thiswithComponent.addXXXListener()FooListenerswhere XXX isare registered using thenameaddFooListenermethod.
ofYou can specify thelistenerTypeargument.For example to get all ofwith a class literal such astheFooListener.class. ForMouseListeners for the givenexample you can query aComponentconefor its mouse listeners with thewould writefollowing code:If no suchMouseListener[] mls = (MouseListener[])(c.getListeners(MouseListener.class));listenerlisteners existlist exists thenthis method returns an empty arrayis returned. @param listenerTypeTypethe type of listeners requested. This; this parametermustshouldbe aspecify an interface that descends fromjava.util.EventListeneror subclass.@returnsreturn an array of alllistenersobjectsadded toregistered asthisFooListenersComponent using addXXXListeneron this component or an empty array if no such listeners have been addedto this Component.@throwsexception ClassCastException ifthelistenerTypeparameterisdoesn'tnotspecify a class or interface that implementsjava.util.EventListeneror@seesubclass.#getComponentListeners @see #getFocusListeners @see #getHierarchyListeners @see #getHierarchyBoundsListeners @see #getKeyListeners @see #getMouseListeners @see #getMouseMotionListeners @see #getMouseWheelListeners @see #getInputMethodListeners @see #getPropertyChangeListeners @since 1.3
Gets the locale of this component. @returnClass Component, Point getLocation()Thisthis component's locale.;Ifif this component does not have a locale the locale of its parent is returned.@see #setLocale @exception IllegalComponentStateExceptionIfif theComponentdoes not have its own locale and has not yet been added to a containment hierarchy such that the locale can be determined from the containing parent.@since JDK1.1
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, Point getLocation(Point)Due to the asynchronous nature of native event handling this method can return outdated values (for instance after several calls of
@returnsetLocation()in rapid succession). For this reason the recommended method of obtaining aComponentcomponent's position is withinjava.awt.event.ComponentListener.componentMoved()which is called after the operating system has finished moving theComponentcomponent.Anan instance ofPointrepresenting 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
Class Component, Point getLocationOnScreen()StoreStores the x y origin of this component into "return value" rv and return rv. If rv isnulla newPointis allocated. This version ofgetLocationis useful if the caller wants to avoid allocating a new()Pointobject on the heap. @param rv the return value modified to the components location @return rv
Gets the location of this component in the form of a point specifying the component's top-left corner in the screen's coordinate space. @returnClass Component, Dimension getMaximumSize()Anan instance ofPointrepresenting the top-left corner of the component's bounds in the coordinate space of the screen.@throwsIllegalComponentStateExceptionif the component is not showing on the screen @see #setLocation @see #getLocation
Gets the maximum size of this component. @returnClass Component, Dimension getMinimumSize()Aa dimension object indicating this component's maximum size.@see #getMinimumSize @see #getPreferredSize @see LayoutManager
Gets the mininimum size of this component. @returnClass Component, String getName()Aa dimension object indicating this component's minimum size.@see #getPreferredSize @seejava.awtLayoutManagerLayoutManager
Gets the name of the component. @returnClass Component, Container getParent()Thisthis component's name.@see #setName @since JDK1.1
Gets the parent of this component. @returnClass Component, ComponentPeer getPeer()Thethe parent container of this component.@since JDK1.0
@deprecated As of JDK version 1.1 programs should not directly manipulate peersClass Component, Dimension getPreferredSize().; replaced byboolean isDisplayable().
Gets the preferred size of this component. @returnClass Component, Dimension getSize()Aa dimension object indicating this component's preferred size.@see #getMinimumSize @seejava.awt.LayoutManager
Returns the size of this component in the form of aClass Component, Dimension getSize(Dimension)Dimensionobject. Theheightfield of theDimensionobject contains this component's height and thewidthfield of theDimensionobject contains this component's width. @returnAaDimensionobject that indicates the size of this component.@see #setSize @since JDK1.1
Class Component, Toolkit getToolkit()StoreStores the width/height of this component into "return value" rv and return rv. If rv isnulla newDimensionobject is allocated. This version ofgetSizeis useful if the caller wants to avoid allocating a new()Dimensionobject on the heap. @param rv the return value modified to the components size @return rv
Gets the toolkit of this component. Note that the frame that contains a component controls which toolkit is used by that component. Therefore if the component is moved from one frame to another the toolkit it uses may change. @returnClass Component, Object getTreeLock()Thethe toolkit of this component.@since JDK1.0
GetsClass Component, int getWidth()the locking object for AWT component-tree and layout Getsthis component's locking object (the object that owns the thread sychronization monitor) for AWT component-tree and layout operations. @returnThisthis component's locking object.
Class Component, int getX()ReturnReturns the current width of this component. This method is preferable to writingcomponent.getBounds().widthorcomponent.getSize().widthbecause it doesn't cause any heap allocations. @return the current width of this component.@since 1.2
Class Component, int getY()ReturnReturns the current x coordinate of the components origin. This method is preferable to writingcomponent.getBounds().xorcomponent.getLocation().xbecause it doesn't cause any heap allocations. @return the current x coordinate of the components origin.@since 1.2
Class Component, boolean hasFocus()ReturnReturns the current y coordinate of the components origin. This method is preferable to writingcomponent.getBounds().yorcomponent.getLocation().ybecause it doesn't cause any heap allocations. @return the current y coordinate of the components origin.@since 1.2
ReturnsClass Component, boolean imageUpdate(Image, int, int, int, int, int)trueif thisComponenthasis thekeyboardfocus owner. This method is obsolete and has been replaced byisFocusOwner(). @returntrueif thisComponenthasis thekeyboardfocus.owner;falseotherwise @since 1.2
Repaints the component when the image has changed. ThisClass Component, void invalidate()imageUpdatemethod of anImageObserveris called when more information about an image which had been previously requested using an asynchronous routine such as thedrawImagemethod ofGraphicsbecomes available. See the definition ofimageUpdatefor more information on this method and its arguments.The
imageUpdatemethod ofComponentincrementally draws an image on the component as more of the bits of the image are available.If the system property
awt.image.incrementalDrawis missing or has the valuetruethe 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.redrawrateis 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
xywidthandheightarguments depends on the value of theinfoflagsargument. @param img the image being observed.@param infoflags seeimageUpdatefor more information.@param x the x coordinate.@param y the y coordinate.@param w the width.@param h the height.@returnfalseif the infoflags indicate that the image is completely loaded;trueotherwise. @see java.awt.image.ImageObserver @seejava.awt.Graphics#drawImage(java.awt.Image int intjava.awt.Color java.awt.image.ImageObserver) @seejava.awt.Graphics#drawImage(java.awt.Image int int java.awt.image.ImageObserver) @seejava.awt.Graphics#drawImage(java.awt.Image int int int intjava.awt.Color java.awt.image.ImageObserver) @seejava.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
Invalidates this component. This component and all parents above it are marked as needing to be laid out. This method can be called often so it needs to execute quickly. @seeClass Component, boolean isDisplayable()java.awt.Component#validate @seejava.awt.Component#doLayout @seejava.awt.LayoutManager @since JDK1.0
Determines whether this component is displayable. A component is displayable when it is connected to a native screen resource.Class Component, boolean isEnabled()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
trueif the component is displayable;falseotherwise.@seejava.awt.Container#add(java.awt.Component) @seejava.awt.Window#pack @seejava.awt.Window#show @seejava.awt.Container#remove(java.awt.Component) @seejava.awt.Window#dispose @since 1.2
Determines whether this component is enabled. An enabled component can respond to user input and generate events. Components are enabled initially by default. A component may be enabled or disabled by calling itsClass Component, boolean isFocusTraversable()setEnabledmethod. @returntrueif the component is enabled;falseotherwise.@see #setEnabled @since JDK1.0
ReturnsClass Component, boolean isLightweight()the value of a flag that indicateswhether thiscomponent can be traversed using Tab or Shift-Tab keyboard focus traversal. If this method returns "false" this component may still request the keyboard focus usingrequestFocus()Componentbut it will not automaticallycanbe assignedbecome the focusduring tab traversalowner. @returntrueif thiscomponentComponentisfocus-traverablefocusable;falseotherwise.@see #setFocusable @since JDK1.1 @deprecated As of 1.4 replaced byisFocusable().
A lightweight component doesn't have a native toolkit peer. Subclasses ofClass Component, boolean isOpaque()ComponentandContainerother than the ones defined in this package likeButtonorScrollbarare lightweight. All of the Swing components are lightweights.This method will always return
falseif thisComponentcomponent is not displayable because it is impossible to determine the weight of an undisplayableComponentcomponent. @return true if this component has a lightweight peer; false if it has a native peer or no peer.@see #isDisplayable @since 1.2
Returns true if this component is completely opaque returns false by default.Class Component, boolean isShowing()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 1.2
Determines whether this component is showing on screen. This means that the component must be visible and it must be in a container that is visible and showing. @returnClass Component, boolean isValid()trueif the component is showing;falseotherwise.@see #setVisible @since JDK1.0
Determines whether this component is valid. A component is valid when it is correctly sized and positioned within its parent container and all its children are also valid. Components are invalidated when they are first shown on the screen. @returnClass Component, boolean isVisible()trueif the component is valid;falseotherwise.@see #validate @see #invalidate @since JDK1.0
Determines whether this component should be visible when its parent is visible. Components are initially visible with the exception of top level components such asClass Component, void list(PrintStream)Frameobjects. @returntrueif the component is visible;falseotherwise.@see #setVisible @since JDK1.0
Prints a listing of this component to the specified output stream. @param out a print streamClass Component, void list(PrintStream, int).@since JDK1.0
Prints out a list starting at the specifiedClass Component, void list(PrintWriter)indentionindentation to the specified print stream. @param out a print stream.@param indent number of spaces to indent.@see java.io.PrintStream#println(java.lang.Object) @since JDK1.0
Prints a listing to the specified print writer. @param outClass Component, void list(PrintWriter, int)Thethe print writer to print to.@since JDK1.1
Prints out a list starting at the specifiedClass Component, void paint(Graphics)indentionindentation to the specified print writer. @param outThethe print writer to print to.@param indentThethe number of spaces to indent.@see java.io.PrintStream#println(java.lang.Object) @since JDK1.1
Paints this component.Class Component, void paintAll(Graphics)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
Graphicsparameter will be set to the area which needs to be painted. Subclasses of Component that override this method need not call super.paint(g).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
Thethe graphics context to use for painting.@seejava.awt.Component#update @since JDK1.0
Paints this component and all of its subcomponents.Class Component, String paramString()The origin of the graphics context its (
00) coordinate point is the top-left corner of this component. The clipping region of the graphics context is the bounding rectangle of this component. @param g the graphics context to use for painting.@seejava.awt.Component#paint @since JDK1.0
Returns a string representing the state of this component. This method is intended to be used only for debugging purposes and the content and format of the returned string may vary between implementations. The returned string may be empty but may not beClass Component, boolean prepareImage(Image, ImageObserver)null. @return a string representation of this component's state.@since JDK1.0
Prepares an image for rendering on this component. The image data is downloaded asynchronously in another thread and the appropriate screen representation of the image is generated. @param image theClass Component, boolean prepareImage(Image, int, int, ImageObserver)Imagefor which to prepare a screen representation.@param observer theImageObserverobject to be notified as the image is being prepared.@returntrueif the image has already been fully prepared;falseotherwise.@since JDK1.0
Prepares an image for rendering on this component at the specified width and height.Class Component, void print(Graphics)The image data is downloaded asynchronously in another thread and an appropriately scaled screen representation of the image is generated. @param image the instance of
Imagefor which to prepare a screen representation.@param width the width of the desired screen representation.@param height the height of the desired screen representation.@param observer theImageObserverobject to be notified as the image is being prepared.@returntrueif the image has already been fully prepared;falseotherwise.@see java.awt.image.ImageObserver @since JDK1.0
Prints this component. Applications should override this method for components that must do special processing before being printed or should be printed differently than they are painted.Class Component, void printAll(Graphics)The default implementation of this method calls the
paintmethod.The origin of the graphics context its (
00) coordinate point is the top-left corner of this component. The clipping region of the graphics context is the bounding rectangle of this component. @param g the graphics context to use for printing.@seejava.awt.Component#paint(java.awt.Graphics) @since JDK1.0
Prints this component and all of its subcomponents.Class Component, void processComponentEvent(ComponentEvent)The origin of the graphics context its (
00) coordinate point is the top-left corner of this component. The clipping region of the graphics context is the bounding rectangle of this component. @param g the graphics context to use for printing.@seejava.awt.Component#print(java.awt.Graphics) @since JDK1.0
Processes component events occurring on this component by dispatching them to any registeredClass Component, void processEvent(AWTEvent)ComponentListenerobjects.This method is not called unless component events are enabled for this component. Component events are enabled when one of the following occurs:
- A
ComponentListenerobject is registered viaaddComponentListener.- Component events are enabled via
enableEvents.Note that if the event parameter is
nullthe behavior is unspecified and may result in an exception. @param e the component event.@see java.awt.event.ComponentEvent @see java.awt.event.ComponentListener @seejava.awt.Component#addComponentListener @seejava.awt.Component#enableEvents @since JDK1.1
Processes events occurring on this component. By default this method calls the appropriateClass Component, void processFocusEvent(FocusEvent)process<event type>Eventmethod for the given class of event.Note that if the event parameter is
nullthe behavior is unspecified and may result in an exception. @param e the event.@seejava.awt.Component#processComponentEvent @seejava.awt.Component#processFocusEvent @seejava.awt.Component#processKeyEvent @seejava.awt.Component#processMouseEvent @seejava.awt.Component#processMouseMotionEvent @seejava.awt.Component#processInputMethodEvent @seejava.awt.Component#processHierarchyEvent @see #processMouseWheelEvent @since JDK1.1
Processes focus events occurring on this component by dispatching them to any registeredClass Component, void processHierarchyBoundsEvent(HierarchyEvent)FocusListenerobjects.This method is not called unless focus events are enabled for this component. Focus events are enabled when one of the following occurs:
- A
FocusListenerobject is registered viaaddFocusListener.- Focus events are enabled via
enableEvents.Note that if the event parameter is
nullthe behavior is unspecified and may result in an exception. @param e the focus event.@see java.awt.event.FocusEvent @see java.awt.event.FocusListener @seejava.awt.Component#addFocusListener @seejava.awt.Component#enableEvents @since JDK1.1
Processes hierarchy bounds events occurring on this component by dispatching them to any registeredClass Component, void processHierarchyEvent(HierarchyEvent)HierarchyBoundsListenerobjects.This method is not called unless hierarchy bounds events are enabled for this component. Hierarchy bounds events are enabled when one of the following occurs:
- An
HierarchyBoundsListenerobject is registered viaaddHierarchyBoundsListener.- Hierarchy bounds events are enabled via
enableEvents.Note that if the event parameter is
nullthe behavior is unspecified and may result in an exception. @param e the hierarchy event @see java.awt.event.HierarchyEvent @see java.awt.event.HierarchyBoundsListener @seejava.awt.Component#addHierarchyBoundsListener @seejava.awt.Component#enableEvents @since 1.3
Processes hierarchy events occurring on this component by dispatching them to any registeredClass Component, void processInputMethodEvent(InputMethodEvent)HierarchyListenerobjects.This method is not called unless hierarchy events are enabled for this component. Hierarchy events are enabled when one of the following occurs:
- An
HierarchyListenerobject is registered viaaddHierarchyListener.- Hierarchy events are enabled via
enableEvents.Note that if the event parameter is
nullthe behavior is unspecified and may result in an exception. @param e the hierarchy event @see java.awt.event.HierarchyEvent @see java.awt.event.HierarchyListener @seejava.awt.Component#addHierarchyListener @seejava.awt.Component#enableEvents @since 1.3
Processes input method events occurring on this component by dispatching them to any registeredClass Component, void processKeyEvent(KeyEvent)InputMethodListenerobjects.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:
- An
InputMethodListenerobject is registered viaaddInputMethodListener.- Input method events are enabled via
enableEvents.Note that if the event parameter is
nullthe behavior is unspecified and may result in an exception. @param e the input method event @see java.awt.event.InputMethodEvent @see java.awt.event.InputMethodListener @seejava.awt.Component#addInputMethodListener @seejava.awt.Component#enableEvents @since 1.2
Processes key events occurring on this component by dispatching them to any registeredClass Component, void processMouseEvent(MouseEvent)KeyListenerobjects.This method is not called unless key events are enabled for this component. Key events are enabled when one of the following occurs:
- A
KeyListenerobject is registered viaaddKeyListener.- Key events are enabled via
enableEvents.Note that this method is not called by the event dispatch thread if the component is not the focus owner of if the component is not showing. This method is called when key events are registered via the
addKeyListenerorenableEventsmethods but as of release 1.4 the implementation of the AWT event dispatching thread redirectsKeyEventto the focus owner. Please see the Focus Specification for further information.If the event parameter is
@param e the key eventnullthe behavior is unspecified and may result in an exception..@see java.awt.event.KeyEvent @see java.awt.event.KeyListener @seejava.awt.Component#addKeyListener @seejava.awt.Component#enableEvents @see #isShowing @since JDK1.1
Processes mouse events occurring on this component by dispatching them to any registeredClass Component, void processMouseMotionEvent(MouseEvent)MouseListenerobjects.This method is not called unless mouse events are enabled for this component. Mouse events are enabled when one of the following occurs:
- A
MouseListenerobject is registered viaaddMouseListener.- Mouse events are enabled via
enableEvents.Note that if the event parameter is
nullthe behavior is unspecified and may result in an exception. @param e the mouse event.@see java.awt.event.MouseEvent @see java.awt.event.MouseListener @seejava.awt.Component#addMouseListener @seejava.awt.Component#enableEvents @since JDK1.1
Processes mouse motion events occurring on this component by dispatching them to any registeredClass Component, void remove(MenuComponent)MouseMotionListenerobjects.This method is not called unless mouse motion events are enabled for this component. Mouse motion events are enabled when one of the following occurs:
- A
MouseMotionListenerobject is registered viaaddMouseMotionListener.- Mouse motion events are enabled via
enableEvents.Note that if the event parameter is
nullthe behavior is unspecified and may result in an exception. @param e the mouse motion event.@see java.awt.event.MouseMotionEvent @see java.awt.event.MouseMotionListener @seejava.awt.Component#addMouseMotionListener @seejava.awt.Component#enableEvents @since JDK1.1
Removes the specified popup menu from the component. @param popup the popup menu to be removedClass Component, void removeComponentListener(ComponentListener).@seejava.awt.Component#add(java.awt.PopupMenu) @since JDK1.1
Removes the specified component listener so that it no longer receives component 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 listenerClass Component, void removeFocusListener(FocusListener)l isnullno exception is thrown and no action is performed. @param l the component listener.@see java.awt.event.ComponentEvent @see java.awt.event.ComponentListener @seejava.awt.Component#addComponentListener @see #getComponentListeners @since JDK1.1
Removes the specified focus listener so that it no longer receives focus 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 listenerClass Component, void removeHierarchyBoundsListener(HierarchyBoundsListener)l isnullno exception is thrown and no action is performed. @param l the focus listener.@see java.awt.event.FocusEvent @see java.awt.event.FocusListener @seejava.awt.Component#addFocusListener @see #getFocusListeners @since JDK1.1
Removes the specified hierarchy bounds listener so that it no longer receives hierarchy bounds 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 listenerClass Component, void removeHierarchyListener(HierarchyListener)l isnullno exception is thrown and no action is performed. @param l the hierarchy bounds listener.@see java.awt.event.HierarchyEvent @see java.awt.event.HierarchyBoundsListener @seejava.awt.Component#addHierarchyBoundsListener @see #getHierarchyBoundsListeners @since 1.3
Removes the specified hierarchy listener so that it no longer receives hierarchy changed 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 listenerClass Component, void removeInputMethodListener(InputMethodListener)l isnullno exception is thrown and no action is performed. @param l the hierarchy listener.@see java.awt.event.HierarchyEvent @see java.awt.event.HierarchyListener @seejava.awt.Component#addHierarchyListener @see #getHierarchyListeners @since 1.3
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 listenerClass Component, void removeKeyListener(KeyListener)l isnullno exception is thrown and no action is performed. @param l the input method listener.@see java.awt.event.InputMethodEvent @see java.awt.event.InputMethodListener @seejava.awt.Component#addInputMethodListener @see #getInputMethodListeners @since 1.2
Removes the specified key listener so that it no longer receives key 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 listenerClass Component, void removeMouseListener(MouseListener)l isnullno exception is thrown and no action is performed. @param l the key listener.@see java.awt.event.KeyEvent @see java.awt.event.KeyListener @seejava.awt.Component#addKeyListener @see #getKeyListeners @since JDK1.1
Removes the specified mouse listener so that it no longer receives mouse 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 listenerClass Component, void removeMouseMotionListener(MouseMotionListener)l isnullno exception is thrown and no action is performed. @param l the mouse listener.@see java.awt.event.MouseEvent @see java.awt.event.MouseListener @seejava.awt.Component#addMouseListener @see #getMouseListeners @since JDK1.1
Removes the specified mouse motion listener so that it no longer receives mouse motion 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 listenerClass Component, void removeNotify()l isnullno exception is thrown and no action is performed. @param l the mouse motion listener.@see java.awt.event.MouseMotionEvent @see java.awt.event.MouseMotionListener @seejava.awt.Component#addMouseMotionListener @see #getMouseMotionListeners @since JDK1.1
Makes thisClass Component, void removePropertyChangeListener(PropertyChangeListener)Componentundisplayable by destroying it native screen resource. This method is called by the toolkit internally and should not be called directly by programs. @seejava.awt.Component#isDisplayable @seejava.awt.Component#addNotify @since JDK1.0
Class Component, void removePropertyChangeListener(String, PropertyChangeListener)RemoveRemoves a PropertyChangeListener from the listener list. ThisremovesmethodashouldPropertyChangeListenerbe used to remove PropertyChangeListeners thatwaswere registered for all bound properties of this class.If listener is null no exception is thrown and no action is performed. @param listener
Thethe PropertyChangeListener to be removed @see #addPropertyChangeListener @see #getPropertyChangeListeners @see #removePropertyChangeListener(java.lang.String java.beans.PropertyChangeListener)
Class Component, void repaint()RemoveRemoves a PropertyChangeListener from the listener list for a specific property. This method should be used to remove PropertyChangeListeners that were registered for a specific bound property.If listener is null no exception is thrown and no action is performed. @param propertyName
The name ofathevalid propertythat was listened on.name @param listenerThethe PropertyChangeListener to be removed @see #addPropertyChangeListener(java.lang.String) @see #getPropertyChangeListeners(java.lang.String) @see #removePropertyChangeListener(java.beans.PropertyChangeListener)
Repaints this component.Class Component, void repaint(int, int, int, int)This method causes a call to this component's
updatemethod as soon as possible. @seejava.awt.Component#update(java.awt.Graphics) @since JDK1.0
Repaints the specified rectangle of this component.Class Component, void repaint(long)This method causes a call to this component's
updatemethod as soon as possible. @param x the x coordinate.@param y the y coordinate.@param width the width.@param height the height.@seejava.awt.Component#update(java.awt.Graphics) @since JDK1.0
Repaints the component. This will result in a call toClass Component, void repaint(long, int, int, int, int)updatewithin tm milliseconds. @param tm maximum time in milliseconds before update @see #paint @seejava.awt.Component#update(java.awt.Graphics) @since JDK1.0
Repaints the specified rectangle of this component withinClass Component, void setBackground(Color)tmmilliseconds.This method causes a call to this component's
updatemethod. @param tm maximum time in milliseconds before update.@param x the x coordinate.@param y the y coordinate.@param width the width.@param height the height.@seejava.awt.Component#update(java.awt.Graphics) @since JDK1.0
Sets the background color of this component.Class Component, void setBounds(Rectangle)The background color affects each component differently and the parts of the component that are affected by the background color may differ between operating systems. @param c
Thethe color to become this component's color.;Ifif this parameter isnullthen this component will inherit the background color of its parent. background color.@see #getBackground @since JDK1.0 @beaninfo bound: true
Moves and resizes this component to conform to the new bounding rectangleClass Component, void setBounds(int, int, int, int)r. This component's new position is specified byr.xandr.yand its new size is specified byr.widthandr.height@param rThethe new bounding rectangle for this component.@seejava.awt.Component#getBounds @seejava.awt.Component#setLocation(int int) @seejava.awt.Component#setLocation(java.awt.Point) @seejava.awt.Component#setSize(int int) @seejava.awt.Component#setSize(java.awt.Dimension) @since JDK1.1
Moves and resizes this component. The new location of the top-left corner is specified byClass Component, void setComponentOrientation(ComponentOrientation)xandyand the new size is specified bywidthandheight. @param xThethe new x-coordinate of this component.@param yThethe new y-coordinate of this component.@param widthThethe newwidthof this component.@param heightThethe newheightof this component.@seejava.awt.Component#getBounds @seejava.awt.Component#setLocation(int int) @seejava.awt.Component#setLocation(java.awt.Point) @seejava.awt.Component#setSize(int int) @seejava.awt.Component#setSize(java.awt.Dimension) @since JDK1.1
Class Component, void setCursor(Cursor)SetSets the language-sensitive orientation that is to be used to order the elements or text within this component. Language-sensitiveLayoutManagerandComponentsubclasses will use this property to determine how to lay out and draw components.At construction time a component's orientation is set to
ComponentOrientation.UNKNOWNindicating that it has not been specified explicitly. The UNKNOWN orientation behaves the same asComponentOrientation.LEFT_TO_RIGHT.To set the orientation of a single component use this method. To
apply asetResourceBundle'sthe orientationtoof an entire component hierarchy usejava.awt.Window.applyResourceBundle.applyComponentOrientation @seejava.awt.ComponentOrientation @see java.awt.Window#applyResourceBundle(java.util.ResourceBundle) @author Laura Werner IBM @beaninfo bound: true
Sets the cursor image to the specified cursor. This cursor image is displayed when theClass Component, void setDropTarget(DropTarget)containsmethod for this component returns true for the current cursor location and this Component is visible displayable and enabled. Setting the cursor of aContainercauses that cursor to be displayed within all of the container's subcomponents except for those that have a non-nullcursor. @param cursor One of the constants defined by theCursorclass. If; if this parameter isnullthen this component will inherit the cursor of its parent.@see #isEnabled @see #isShowing @seejava.awt.Component#getCursor @seejava.awt.Component#contains @seejava.awt.Toolkit#createCustomCursor @seejava.awt.Cursor @since JDK1.1
Associate aClass Component, void setEnabled(boolean)DropTargetwith thisComponentcomponent. TheComponentwill receive drops only if it is enabled. @see #isEnabled @param dt The DropTarget
Enables or disables this component depending on the value of the parameterClass Component, void setFont(Font)b. An enabled component can respond to user input and generate events. Components are enabled initially by default.Note: Disabling a lightweight component does not prevent it from receiving MouseEvents. @param b If
truethis component is enabled; otherwise this component is disabled.@see #isEnabled @see #isLightweight @since JDK1.1
Sets the font of this component. @param fClass Component, void setForeground(Color)Thethe font to become this component's font.;Ifif this parameter isnullthen this component will inherit the font of its parent.@see #getFont @since JDK1.0 @beaninfo bound: true
Sets the foreground color of this component. @param cClass Component, void setLocale(Locale)Thethe color to become this component's foreground color.;Ifif this parameter isnullthen this component will inherit the foreground color of its parent.@see #getForeground @since JDK1.0
Sets the locale of this component. This is a bound property. @param lClass Component, void setLocation(Point)Thethe locale to become this component's locale.@see #getLocale @since JDK1.1
Moves this component to a new location. The top-left corner of the new location is specified by pointClass Component, void setLocation(int, int)p. Pointpis given in the parent's coordinate space. @param pThethe point defining the top-left corner of the new location given in the coordinate space of this component's parent.@see #getLocation @see #setBounds @since JDK1.1
Moves this component to a new location. The top-left corner of the new location is specified by theClass Component, void setName(String)xandyparameters in the coordinate space of this component's parent. @param xThethe x-coordinate of the new location's top-left corner in the parent's coordinate space.@param yThethe y-coordinate of the new location's top-left corner in the parent's coordinate space.@see #getLocation @see #setBounds @since JDK1.1
Sets the name of the component to the specified string. @param nameClass Component, void setSize(Dimension)Thethe string that is to be this component's name.@see #getName @since JDK1.1
Resizes this component so that it has widthClass Component, void setSize(int, int)d.widthand heightd.height. @param dThethe dimension specifying the new size of this component.@see #setSize @see #setBounds @since JDK1.1
Resizes this component so that it has widthClass Component, void setVisible(boolean)widthand heightheight. @param widthThethe new width of this component in pixels.@param heightThethe new height of this component in pixels.@see #getSize @see #setBounds @since JDK1.1
Shows or hides this component depending on the value of parameterClass Component, String toString()b. @param bIfiftrueshows this component; otherwise hides this component.@see #isVisible @since JDK1.1
Returns a string representation of this component and its values. @return a string representation of this componentClass Component, void transferFocus().@since JDK1.0
Transfers the focus to the next component as though this Component were the focus owner. @seeClass Component, void update(Graphics)java.awt.Component#requestFocus() @since JDK1.1s1
Updates this component.Class Component, void validate()The AWT calls the
updatemethod in response to a call torepaint. The appearance of the component on the screen has not changed since the last call toupdate orpaint. You can assume that the background is not cleared.The
updatemethod ofComponentdoescalls thisthecomponent'sfollowing:paintmethod toClearsredraw this component.byThis methodfilling it with the backgroundis commonly overridden by subclassescolor.whichSetsneedthe color of the graphics contextto do additional work in response tobeathecall toforegroundrepaint.colorSubclasses ofthisComponentcomponent.thatCallsoverride thiscomponent'smethodpaintshouldmethod toeither callcompletelysuper.update(g)redraw thisor callcomponent.paintdirectly.The origin of the graphics context its (
00) coordinate point is the top-left corner of this component. The clipping region of the graphics context is the bounding rectangle of this component. @param g the specified context to use for updating.@seejava.awt.Component#paint @seejava.awt.Component#repaint() @since JDK1.0
Ensures that this component has a valid layout. This method is primarily intended to operate on instances ofContainer. @seejava.awt.Component#invalidate @seejava.awt.Component#doLayout() @seejava.awt.LayoutManager @seejava.awt.Container#validate @since JDK1.0
Class ComponentOrientation, ComponentOrientation getOrientation(ResourceBundle)ReturnReturns the orientation that is appropriate for the given locale. @param localeused as a key to look uptheorientation in an internalspecifiedresource bundle.locale
ReturnReturns the orientation appropriate for the given ResourceBundle's localization. Three approaches are triedinnin the following order:@deprecated As of J2SE 1.4 use #getOrientation(java.util.Locale)
- Retrieve a ComponentOrientation object from the ResourceBundle using the string "Orientation" as the key.
- Use the ResourceBundle.getLocale to determine the bundle's locale then return the orientation for that locale.
- Return the default locale's orientation.
A generic Abstract Window Toolkit(AWT) container object is a component that can contain other AWT components.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.
181 04222 12/0603/0001 @author Arthur van Hoff @author Sami Shaio @seejava.awt.Container#add(java.awt.Component int) @seejava.awt.Container#getComponent(int) @seejava.awt.LayoutManager @since JDK1.0
FirePropertyChangelistener if one is registered when children are added/or removed.
Returns theClass Container.AccessibleAWTContainer, Accessible getAccessibleChild(int)Accessiblechild if one exists contained at the local coordinatePoint. @param pThethe point defining the top-left corner of theAccessiblegiven in the coordinate space of the object's parent.@return theAccessibleif it exists at the specified location; elsenull
Class Container.AccessibleAWTContainer, int getAccessibleChildrenCount()ReturnReturns the nthAccessiblechild of the object. @param i zero-based index of child @return the nthAccessiblechild of the object
Returns the number of accessible children in the object. If all of the children of this object implementAccessiblethanthen this method should return the number of children of this object. @return the number of accessible children in the object.
Class Container, void add(Component, Object)AddsAppends the specified component to the end of this container. This is a convenience method for #addImpl @param comp the component to be added.@see #addImpl @return the component argument.
Adds the specified component to the end of this container. Also notifies the layout manager to add the component to this container's layout using the specified constraints object. This is a convenience method for #addImpl @param comp the component to be added @param constraints an object expressing layout contraints for this component @seeClass Container, void add(Component, Object, int)java.awt.#addImpl @see LayoutManager @since JDK1.1
Adds the specified component to this container with the specified constraints at the specified index. Also notifies the layout manager to add the component to the this container's layout using the specified constraints object. This is a convenience method for #addImpl @param comp the component to be added @param constraints an object expressing layout contraints for this @param index the position in the container's list at which to insert the component. -1 means insert at the end. component @see #addImpl @see #remove @see LayoutManagerClass Container, Component add(Component, int)
Adds the specified component to this container at the given position. This is a convenience method for #addImpl @param comp the component to be addedClass Container, Component add(String, Component).@param index the position at which to insert the component or-1toinsertappend the componentatto the end.@return the componentcomp@see #addImpl @see #remove
Adds the specified component to this container.Class Container, void addContainerListener(ContainerListener)ItThis isstronglyaadvised to useconvenience method forthe#addImplThis method is obsolete as of 1.1. Please use the method
add(Component Object)inplace of this methodinstead.
Adds the specified container listener to receive container events from this container. If l is null no exception is thrown and no action is performed. @param l the container listener @see #removeContainerListener @see #getContainerListenersClass Container, void addImpl(Component, Object, int)
Adds the specified component to this container at the specified index. This method also notifies the layout manager to add the component to this container's layout using the specified constraints object via theClass Container, void doLayout()addLayoutComponentmethod. The constraints are defined by the particular layout manager being used. For example theBorderLayoutclass defines five constraints:BorderLayout.NORTHBorderLayout.SOUTHBorderLayout.EASTBorderLayout.WESTandBorderLayout.CENTER.Note that if the component already exists in this container or a child of this container it is removed from that container before being added to this container
.This is the method to override if a program needs to track every add request to a container as all other add methods defer to this one. An overriding method should usually include a call to the superclass's version of the method:
super.addImpl(comp constraints index)@param comp the component to be added
.@param constraints an object expressing layoutcontraintsconstraints for this component.@param index the position in the container's list at which to insert the component where-1meansinsert atappend to the end.@exception IllegalArgumentException ifindexis invalid @exception IllegalArgumentException if adding the container's parent to itself @exception IllegalArgumentException if adding a window to a container @seejava.awt.Container#add(java.awt.Component) @seejava.awt.Container#add(java.awt.Component int) @seejava.awt.Container#add(java.awt.Component java.lang.Object) @seejava.awt.LayoutManager @see LayoutManager2 @since JDK1.1
Causes this container to lay out its components. Most programs should not call this method directly but should invoke theClass Container, Component findComponentAt(Point)validatemethod instead. @seejava.awt.LayoutManager#layoutContainer @see #setLayout @see #validate @since JDK1.1
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 1.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(Point)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 1.2
Gets the component that contains the specified point. @param p the point. @return returns the component that contains the point orClass Container, int getComponentCount()nullif the component does not contain the point. @seejava.awt.Component#contains @since JDK1.1
Gets the number of components in this panel. @return the number of components in this panel. @seeClass Container, Insets getInsets()java.awt.Container#getComponent @since JDK1.1
Determines the insets of this container which indicate the size of the container's border.Class Container, EventListener[] getListeners(Class)A
Frameobject for example has a top inset that corresponds to the height of the frame's title bar. @return the insets of this container. @seejava.awt.Insets @seejava.awt.LayoutManager @since JDK1.1
Class Container, Dimension getMinimumSize()ReturnReturns an array of all thelistenersobjectsthat were addedcurrently registered astoFooListenersthe Containerupon thiswithContainer.addXXXListener()FooListenerswhere XXX isare registered using thenameaddFooListenerofmethod. You can specify thelistenerTypeargument.For example to get all ofwith a class literal such astheFooListener.class.ContainerListener(s)Forforexampletheyou cangivenquery aContainerconefor its container listeners withwouldthe followingwritecode:If no suchContainerListener[] cls = (ContainerListener[])(c.getListeners(ContainerListener.class));listenerlisteners existlist exists thenthis method returns an empty arrayis returned. @param listenerTypeTypethe type of listeners requested; this parameter should specify an interface that descends fromjava.util.EventListener@returnallan array oftheall objects registered asFooListeners on this container or an empty array if no such listenersof the specifiedhave been addedtype@exceptionsupported byClassCastException ifthislistenerTypecontainerdoesn't specify a class or interface that implementsjava.util.EventListener@see #getContainerListeners @since 1.3
Returns the minimum size of this container. @return an instance ofClass Container, Dimension getPreferredSize()Dimensionthat represents the minimum size of this container. @seejava.awt.Container#getPreferredSize @seejava.awt.Container#getLayout @seejava.awt.LayoutManager#minimumLayoutSize(java.awt.Container) @seejava.awt.Component#getMinimumSize @since JDK1.1
Returns the preferred size of this container. @return an instance ofClass Container, void list(PrintStream, int)Dimensionthat represents the preferred size of this container. @seejava.awt.Container#getMinimumSize @seejava.awt.Container#getLayout @seejava.awt.LayoutManager#preferredLayoutSize(java.awt.Container) @seejava.awt.Component#getPreferredSize
Prints a listing of this container to the specified output stream. The listing starts at the specified indentation. @param out a print stream. @param indent the number of spaces to indent. @seeClass Container, void paint(Graphics)java.awt.Component#list(java.io.PrintStream int) @sinceJDKJDK1.0
Paints the container. This forwards the paint to any lightweight components that are children of this container. If this method is reimplemented super.paint(g) should be called so that lightweight components are properly rendered. If a child component is entirely clipped by the current clipping setting in g paint() will not be forwarded to that child. @param g the specified Graphics window @seeClass Container, void paintComponents(Graphics)java.awt.Component#update(java.awt.Graphics)
Paints each of the components in this container. @param g the graphics context. @seeClass Container, String paramString()java.awt.Component#paint @seejava.awt.Component#paintAll
ReturnsClass Container, void print(Graphics)the parametera string representing the state of thiscontainerContainer. Thisstringmethod isusefulintended to be used only for debugging purposes and the content and format of the returned string may vary between implementations. The returned string may be empty but may not benull. @return the parameter string of this container.
Prints the container. This forwards the print to any lightweight components that are children of this container. If this method is reimplemented super.print(g) should be called so that lightweight components are properly rendered. If a child component is entirely clipped by the current clipping setting in g print() will not be forwarded to that child. @param g the specified Graphics window @seeClass Container, void printComponents(Graphics)java.awt.Component#update(java.awt.Graphics)
Prints each of the components in this container. @param g the graphics context. @seeClass Container, void processContainerEvent(ContainerEvent)java.awt.Component#print @seejava.awt.Component#printAll
Processes container events occurring on this container by dispatching them to any registered ContainerListener objects. NOTE: This method will not be called unless container events are enabled for this component; this happens when one of the following occurs:Class Container, void processEvent(AWTEvent)a)
- A ContainerListener object is registered via
addContainerListener()b)- Container events are enabled via
enableEvents()@seeComponent#enableEventsNote that if the event parameter is
nullthe behavior is unspecified and may result in an exception. @param e the container event @see Component#enableEvents
Processes events on this container. If the event is aClass Container, void removeContainerListener(ContainerListener)ContainerEventit invokes theprocessContainerEventmethod else it invokes its superclass'sprocessEvent.Note that if the event parameter is
nullthe behavior is unspecified and may result in an exception. @param e the event
Removes the specified container listener so it no longer receives container events from this container. If l is null no exception is thrown and no action is performed. @param l the container listener @see #addContainerListener @see #getContainerListenersClass Container, void update(Graphics)
Updates the container. This forwards the update to any lightweight components that are children of this container. If this method is reimplemented super.update(g) should be called so that lightweight components are properly rendered. If a child component is entirely clipped by the current clipping setting in g update() will not be forwarded to that child. @param g the specified Graphics window @seejava.awt.Component#update(java.awt.Graphics)
A class to encapsulate the bitmap representation of the mouse cursor. @see Component#setCursor @version 1.Class Cursor, constructor Cursor(int)30 0236 12/0203/0001 @author Amy Fowler
Creates a new cursor object with the specified type. @param type the type of cursor @throws IllegalArgumentException if the specified cursor type is invalidClass Cursor, Cursor getPredefinedCursor(int)
Returns a cursor object with the specified predefined type. @param type the type of predefined cursor @throws IllegalArgumentException if the specified cursor type is invalidClass Cursor, Cursor getSystemCustomCursor(String)
@return the system specific custom Cursor named Cursor names are for example: "Invalid.16x16" @exception HeadlessException if GraphicsEnvironment.isHeadless returns true
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)getInsetsmethod however since these dimensions are platform-dependent a valid insets value cannot be obtained until the dialog is made displayable by either callingpackorshow. 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 may have its native decorations (i.e. Frame & Titlebar) turned off with
. This can only be done while the dialog is not displayablesetUndecoratedA 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 orminimized the dialog will automatically be hidden from the user. When the owner window is subsequentlyre-opened thenrestored the dialog is made visible to the user again.In a multi-screen environment you can create a
Dialogon a different screen device than its owner. See java.awt.Frame for more information.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
appapplicationcontextexcept for any windows created with the dialog as their owner.Dialogs are capable of generating the following
window eventsWindowEvents:WindowOpenedWindowClosingWindowClosedWindowActivatedWindowDeactivatedWindowGainedFocusWindowLostFocus. @see WindowEvent @see Window#addWindowListener @version 1.69 0483 12/2103/01 @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)ownerisnull. This exception is always thrown when GraphicsEnvironment.isHeadless() returns true @see java.awt.GraphicsEnvironment#isHeadless @since 1.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)nullvalue will be accepted without causing a NullPointerException to be thrown. @exception java.lang.IllegalArgumentException ifownerisnull. This exception is always thrown when GraphicsEnvironment.isHeadless() returns true @see java.awt.GraphicsEnvironment#isHeadless @since 1.2
Constructs an initially invisibleClass Dialog, constructor Dialog(Frame)Dialogwith the specified owner dialog title and modality. @param owner the owner of the dialog @exception IllegalArgumentException if theowner'sGraphicsConfigurationis not from a screen device @param title the title of the dialog. A; anullvalue will be accepted without causing aNullPointerExceptionto be thrown.@param modal if true dialog blocks input to other app windows when shown @exception java.lang.IllegalArgumentException ifownerisnull; this exception is always thrown whenGraphicsEnvironment.isHeadlessreturnstrue@see java.awt.GraphicsEnvironment#isHeadless @since 1.2
Constructs an initially invisible non-modalClass Dialog, constructor Dialog(Frame, String)Dialogwith an empty title and the specified owner frame. @param owner the owner of the dialog @exception IllegalArgumentException if theowner'sGraphicsConfigurationis not from a screen device @exception java.lang.IllegalArgumentException ifownerisnull; this exception is always thrown whenGraphicsEnvironment.isHeadlessreturnstrue@see java.awt.GraphicsEnvironment#isHeadless @see Component#setSize @see Component#setVisible
Constructs an initially invisible non-modalClass Dialog, constructor Dialog(Frame, String, boolean)Dialogwith the specified owner frame and title. @param owner the owner of the dialog @param title the title of the dialog. A; anullvalue will be accepted without causing aNullPointerExceptionto be thrown.@exception IllegalArgumentException if theowner'sGraphicsConfigurationis not from a screen device @exception java.lang.IllegalArgumentException ifownerisnull; this exception is always thrown whenGraphicsEnvironment.isHeadlessreturnstrue@see java.awt.GraphicsEnvironment#isHeadless @see Component#setSize @see Component#setVisible
Constructs an initially invisibleClass Dialog, constructor Dialog(Frame, boolean)Dialogwith the specified owner frame title and modality. @param owner the owner of the dialog @param title the title of the dialog. A; anullvalue will be accepted without causing aNullPointerExceptionto be thrown.@param modal if true dialog blocks input to other app windows when shown @exception IllegalArgumentException if theowner'sGraphicsConfigurationis not from a screen device @exception java.lang.IllegalArgumentException ifownerisnull. This exception is always thrown whenGraphicsEnvironment.isHeadlessreturnstrue@see java.awt.GraphicsEnvironment#isHeadless @see Component#setSize @see Component#setVisible
Constructs an initially invisibleClass Dialog, boolean isModal()Dialogwith an empty title the specified owner frame and modality. @param owner the owner of the dialog @param modal iftruedialog blocks input to other app windows when shown @exception IllegalArgumentException if theowner'sGraphicsConfigurationis not from a screen device @exception java.lang.IllegalArgumentException ifownerisnull; this exception is always thrown whenGraphicsEnvironment.isHeadlessreturnstrue@see java.awt.GraphicsEnvironment#isHeadless
Indicates whether the dialog is modal. When a modal Dialog is made visible user input will be blocked to the other windows in theClass Dialog, String paramString()appapplicationcontextexcept for any windows created with this dialog as their owner. @returntrueif this dialog window is modal;falseotherwise. @see java.awt.Dialog#setModal
ReturnsClass Dialog, void setTitle(String)the parametera string representing the state of this dialogwindow. Thisstringmethod isusefulintended to be used only for debugging purposes and the content and format of the returned string may vary between implementations. The returned string may be empty but may not benull. @return the parameter string of this dialog window.
Sets the title of the Dialog. @param title the title displayed in the dialog's border; a null value results in an empty title @see #getTitle
TheClass Dimension, constructor Dimension(Dimension)Dimensionclass 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 theComponentclass and theLayoutManagerinterface return aDimensionobject.Normally the values of
widthandheightare 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 ofwidthorheightis negative the behavior of some methods defined by other objects is undefined. @version 1.26 0230 12/0203/0001 @author Sami Shaio @author Arthur van Hoff @see java.awt.Component @see java.awt.LayoutManager @since JDK1.0
Creates an instance ofClass Dimension, constructor Dimension(int, int)Dimensionwhose width and height are the same as for the specified dimension. @param d the specified dimension for thewidthandheightvalues.
Constructs aClass Dimension, double getHeight()Dimensionand initializes it to the specified width and specified height. @param width the specified widthdimension@param height the specified heightdimension
Returns the height of this dimension in double precision. @return the height of this dimension in double precisionClass Dimension, Dimension getSize()
Gets the size of thisClass Dimension, double getWidth()Dimensionobject. This method is included for completeness to parallel thegetSizemethod defined byComponent. @return the size of this dimension a new instance ofDimensionwith the same width and height.@see java.awt.Dimension#setSize @see java.awt.Component#getSize @since JDK1.1
Returns the width of this dimension in double precision. @return the width of this dimension in double precisionClass Dimension, int hashCode()
Returns the hash code for thisClass Dimension, void setSize(Dimension)Dimension. @return a hash code for thisDimension.
Class Dimension, void setSize(double, double)SetSets the size of thisDimensionobject to the specified size. This method is included for completeness to parallel thesetSizemethod defined byComponent. @param d the new size for thisDimensionobject.@see java.awt.Dimension#getSize @see java.awt.Component#setSize @since JDK1.1
Class Dimension, void setSize(int, int)SetSets the size of thisDimensionobject to the specified width and height in double precision. Note that ifwidthorheightare larger thanInteger.MAX_VALUEthey will be reset toInteger.MAX_VALUE. @param width the new width for theDimensionobject @param height the new height for theDimensionobject
Class Dimension, String toString()SetSets the size of thisDimensionobject to the specified width and height. This method is included for completeness to parallel thesetSizemethod defined byComponent. @param width the new width for thisDimensionobject.@param height the new height for thisDimensionobject.@see java.awt.Dimension#getSize @see java.awt.Component#setSize @since JDK1.1
Returns a string representation of the values of thisClass Dimension, int heightDimensionobject'sheightandwidthfields. This method is intended to be used only for debugging purposes and the content and format of the returned string may vary between implementations. The returned string may be empty but may not benull. @return a string representation of thisDimensionobject.
The height dimensionClass Dimension, int width. Negative; negative values can be used. @serial @see #getSize @see #setSize
The width dimension. Negative; negative values can be used. @serial @see #getSize @see #setSize
NOTE: TheClass Event, constructor Event(Object, int, Object)Eventclass is obsolete and is available only for backwards compatilibility. It has been replaced by theAWTEventclass and its subclasses.
Eventis 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 theEventclass 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
Eventvariables 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
keyis the unicode character code for the key. For KEY_ACTION and KEY_ACTION_RELEASE the value ofkeyis one of the defined action-key identifiers in theEventclass (PGUPPGDNF1F2etc). @version 1.68 0272 12/0203/0001 @author Sami Shaio @since JDK1.0
NOTE: TheClass Event, constructor Event(Object, long, int, int, int, int, int)Eventclass is obsolete and is available only for backwards compatilibility. It has been replaced by theAWTEventclass and its subclasses.Creates an instance of
Eventwith the specified target component event type and argument. @param target the target component. @param id the event type. @param arg the specified argument.
NOTE: TheClass Event, constructor Event(Object, long, int, int, int, int, int, Object)Eventclass is obsolete and is available only for backwards compatilibility. It has been replaced by theAWTEventclass and its subclasses.Creates an instance of
Eventwith the specified target component time stamp event type x and y coordinates keyboard key state of the modifier keys and an argument set tonull. @param target the target component. @param when the time stamp. @param id the event type. @param x the x coordinate. @param y the y coordinate. @param key the key pressed in a keyboard event. @param modifiers the state of the modifier keys.
NOTE: TheClass Event, boolean controlDown()Eventclass is obsolete and is available only for backwards compatilibility. It has been replaced by theAWTEventclass and its subclasses.Creates an instance of
Eventwith the specified target component time stamp event type x and y coordinates keyboard key state of the modifier keys and argument. @param target the target component. @param when the time stamp. @param id the event type. @param x the x coordinate. @param y the y coordinate. @param key the key pressed in a keyboard event. @param modifiers the state of the modifier keys. @param arg the specified argument.
NOTE: TheClass Event, boolean metaDown()Eventclass is obsolete and is available only for backwards compatilibility. It has been replaced by theAWTEventclass and its subclasses.Checks if the Control key is down. @return
trueif the key is down;falseotherwise. @see java.awt.Event#modifiers @see java.awt.Event#shiftDown @see java.awt.Event#metaDown
NOTE: TheClass Event, String paramString()Eventclass is obsolete and is available only for backwards compatilibility. It has been replaced by theAWTEventclass and its subclasses.Checks if the Meta key is down. @return
trueif the key is down;falseotherwise. @see java.awt.Event#modifiers @see java.awt.Event#shiftDown @see java.awt.Event#controlDown
Class Event, boolean shiftDown()ReturnsNOTE: TheEventclass is obsolete and is available only for backwards compatilibility. It has been replaced by theparameterAWTEventclass and its subclasses.Returns a string representing the state of this
eventEvent. Thisstringmethod isusefulintended to be used only for debugging purposes and the content and format of the returned string may vary between implementations. The returned string may be empty but may not benull. @return the parameter string of this event.
NOTE: TheClass Event, String toString()Eventclass is obsolete and is available only for backwards compatilibility. It has been replaced by theAWTEventclass and its subclasses.Checks if the Shift key is down. @return
trueif the key is down;falseotherwise. @see java.awt.Event#modifiers @see java.awt.Event#controlDown @see java.awt.Event#metaDown
NOTE: TheClass Event, void translate(int, int)Eventclass is obsolete and is available only for backwards compatilibility. It has been replaced by theAWTEventclass and its subclasses.Returns a representation of this event's values as a string. @return a string that represents the event and the values of its member fields. @see java.awt.Event#paramString @since JDK1.1
NOTE: TheClass Event, Object argEventclass is obsolete and is available only for backwards compatilibility. It has been replaced by theAWTEventclass and its subclasses.Translates this event so that its x and y coordinates are increased by dx and dy respectively.
This method translates an event relative to the given component. This involves at a minimum translating the coordinates into the local coordinate system of the given component. It may also involve translating a region in the case of an expose event. @param dx the distance to translate the x coordinate. @param dy the distance to translate the y coordinate.
An arbitrary argument of the event. The value of this field depends on the type of event.arghas been replacedbby event specific property. @serial
Class EventQueue, void dispatchEvent(AWTEvent)EventQueueis a platform-independent class that queues events both from the underlying peer classes and from trusted application classes.It encapsulates asynchronous event dispatch machinery which extracts events from the queue and dispatches them by calling dispatchEvent(AWTEvent) method on this
EventQueuewith the event to be dispatched as an argument. The particular behavior of this machinery is implementation-dependent. The only requirements are that events which were actually enqueued to this queue (note that events being posted to theEventQueuecan be coalesced) are dispatched:
- Sequentially.
- That is it is not permitted that several events from this queue are dispatched simultaneously.
- In the same order as they are enqueued.
- That is if
AWTEventA is enqueued to theEventQueuebeforeAWTEventB then event B will not be dispatched before event A.Some browsers partition applets in different code bases into separate contexts and establish walls between these contexts. In such a scenario there will be one
EventQueueper context. Other browsers place all applets into the same context implying that there will be only a single globalEventQueuefor all applets. This behavior is implementation-dependent. Consult your browser's documentation for more information. @author Thomas Ball @author Fred Ecks @author David Mendenhall @version 1.71 0282 12/0903/01 @since 1.1
Class EventQueue, AWTEvent getNextEvent()DispatchDispatches an event. The manner in which the event is dispatched depends upon the type of the event and the type of the event's source object:
Event Type Source Type Dispatched To ActiveEvent Any event.dispatch() Other Component source.dispatchEvent(AWTEvent) Other MenuComponent source.dispatchEvent(AWTEvent) Other Other No action (ignored) @param theEvent an instance of
java.awt.AWTEventor a subclass of it.
Class EventQueue, void invokeAndWait(Runnable)RemoveRemoves an event from theEventQueueandreturnreturns it. This method will block until an event has been posted by another thread. @return the nextAWTEvent@exception InterruptedException if another thread has interrupted this thread.
CausesClass EventQueue, void invokeLater(Runnable)runnableto have itsrunmethod 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 theRunnablewhoserunmethod should be executed synchronously on the()EventQueue@exception InterruptedException if another thread has interrupted this thread @exception InvocationTargetException if an exception is thrown when runningrunnable@see #invokeLater @since 1.2
CausesClass EventQueue, boolean isDispatchThread()runnableto have itsrunmethod called in the dispatch thread of the()EventQueue. This will happen after all pending events are processed. @param runnable theRunnablewhoserunmethod should be executed synchronously on the()EventQueue@see #invokeAndWait @since 1.2
Returns true if the calling thread is the current AWTClass EventQueue, AWTEvent peekEvent()EventQueue's dispatch thread. Use this call the ensure that a given task is being executed (or not being) on the current AWTEventDispatchThread. @return true if running on the current AWTEventQueue's dispatch thread.
Class EventQueue, AWTEvent peekEvent(int)ReturnReturns the first event on theEventQueuewithout removing it. @return the first event
Class EventQueue, void pop()ReturnReturns the first event with the specified id if any. @param id the id of the type of event desired.@return the first event of the specified id ornullif there is no such event
Class EventQueue, void postEvent(AWTEvent)StopStops dispatching events using thisEventQueue. Any pending events are transferred to the previousinstanceEventQueuefor processing.Warning: To avoid deadlock do not
bydeclareitthis method synchronized in a subclass. @exception EmptyStackException if no previous push was made on thisEventQueue@see java.awt.EventQueue#push.
Class EventQueue, void push(EventQueue)PostPosts a 1.1-style event to theEventQueue. If there is an existing event on the queue with the same ID and event source the sourceComponent'scoalesceEventsmethod will be called. @param theEvent an instance ofjava.awt.AWTEventor a subclass of it.
ReplaceReplaces the existingEventQueuewith the specified one. Any pending events are transferred to the newEventQueuefor processing by it. @param newEventQueue anEventQueue(or subclass thereof) instance to beused.use @see java.awt.EventQueue#pop
TheClass FileDialog, constructor FileDialog(Frame)FileDialogclass displays a dialog window from which the user can select a file.Since it is a modal dialog when the application calls its
showmethod to display the dialog it blocks the rest of the application until the user has chosen a file. @see Window#show @version 1.43 0249 12/0203/0001 @author Sami Shaio @author Arthur van Hoff @since JDK1.0
Creates a file dialog for loading a file. The title of the file dialog is initially empty. This is a convenience method for FileDialog(parent "" LOAD). @param parent the owner of the dialog @since JDK1.1
Class FileDialog, constructor FileDialog(Frame, String)Creates a file dialog window with the specified title for loading a file. The files shown are those in the current directory. This is a convenience method forClass FileDialog, constructor FileDialog(Frame, String, int)FileDialog(parent title LOAD). @param parent the owner of the dialog.@param title the title of the dialog.
Creates a file dialog window with the specified title for loading or saving a file.Class FileDialog, String getDirectory()If the value of
modeisLOADthen the file dialog is finding a file to read and the files shown are those in the current directory. If the value ofmodeisSAVEthe file dialog is finding a place to write a file. @param parent the owner of the dialog.@param title the title of the dialog.@param mode the mode of the dialog; eitherFileDialog.LOADorFileDialog.SAVE @exception IllegalArgumentException if an illegal file dialog mode is supplied @see java.awt.FileDialog#LOAD @see java.awt.FileDialog#SAVE
Gets the directory of this file dialog. @return the (potentiallyClass FileDialog, String getFile()nullor invalid) directory of thisFileDialog@see java.awt.FileDialog#setDirectory.
Gets the selected file of this file dialog. If the user selectedClass FileDialog, FilenameFilter getFilenameFilter()CANCELthe returned file isnull. @return the currently selected file of this file dialog window ornullif none is selected.@see java.awt.FileDialog#setFile
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 filterClass FileDialog, int getMode().@see java.io.FilenameFilter @see java.awt.FileDialog#setFilenameFilter
Indicates whether this file dialog box is for loading from a file or for saving to a file. @return the mode of this file dialog window eitherClass FileDialog, String paramString()FileDialog.LOADorFileDialog.SAVE.@see java.awt.FileDialog#LOAD @see java.awt.FileDialog#SAVE @see java.awt.FileDialog#setMode
ReturnsClass FileDialog, void setDirectory(String)the parametera string representing the state of thisfile dialogFileDialogwindow. Thisstringmethod isusefulintended to be used only for debugging purposes and the content and format of the returned string may vary between implementations. The returned string may be empty but may not benull. @return the parameter string of this file dialog window.
Sets the directory of this file dialog window to be the specified directory. Specifying aClass FileDialog, void setFile(String)nullor an invalid directory implies an implementation-defined default. This default will not be realized however until the user has selected a file. Until this pointgetDirectory()will return the value passed into this method.Specifying "" as the directory is exactly equivalent to specifying
nullas the directory. @param dir thespecificspecified directory.@see java.awt.FileDialog#getDirectory
Sets the selected file for this file dialog window to be the specified file. This file becomes the default file if it is set before the file dialog window is first shown.Class FileDialog, void setFilenameFilter(FilenameFilter)Specifying "" as the file is exactly equivalent to specifying
nullas the file. @param file the file being set.@see java.awt.FileDialog#getFile
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 filterClass FileDialog, void setMode(int).@see java.io.FilenameFilter @see java.awt.FileDialog#getFilenameFilter
Sets the mode of the file dialog. Ifmodeis not a legal value an exception will be thrown andmodewill not be set. @param mode the mode for this file dialog eitherFileDialog.LOADorFileDialog.SAVE.@see java.awt.FileDialog#LOAD @see java.awt.FileDialog#SAVE @see java.awt.FileDialog#getMode @exception IllegalArgumentException if an illegal file dialog mode isused.supplied @since JDK1.1
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, constructor FlowLayout()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.
39 0243 12/0203/0001 @author Arthur van Hoff @author Sami Shaio @since JDK1.0
Constructs a newClass FlowLayout, constructor FlowLayout(int)FlowFlowLayoutLayoutwith a centered alignment and a default 5-unit horizontal and vertical gap.
Constructs a newClass FlowLayout, constructor FlowLayout(int, int, int)Flow LayoutFlowLayoutwith the specified alignment and a default 5-unit horizontal and vertical gap. The value of the alignment argument must be one ofFlowLayout.LEFTFlowLayout.RIGHTorFlowLayout.CENTER. @param align the alignment value
Creates a new flow layout manager with the indicated alignment and the indicated horizontal and vertical gaps.Class FlowLayout, int getAlignment()The value of the alignment argument must be one of
FlowLayout.LEFTFlowLayout.RIGHTorFlowLayout.CENTER. @param align the alignment value.@param hgap the horizontal gap between components.@param vgap the vertical gap between components.
Gets the alignment for this layout. Possible values areClass FlowLayout, int getHgap()FlowLayout.LEFTFlowLayout.RIGHTFlowLayout.CENTERFlowLayout.LEADINGorFlowLayout.. @return the alignment value for this layoutCENTERTRAILING.@see java.awt.FlowLayout#setAlignment @since JDK1.1
Gets the horizontal gap between components. @return the horizontal gap between componentsClass FlowLayout, int getVgap().@see java.awt.FlowLayout#setHgap @since JDK1.1
Gets the vertical gap between components. @return the vertical gap between componentsClass FlowLayout, void layoutContainer(Container).@see java.awt.FlowLayout#setVgap @since JDK1.1
Lays out the container. This method lets each component take its preferred size by reshaping the components in the target container in order to satisfy the constraints of thisClass FlowLayout, Dimension minimumLayoutSize(Container)FlowLayoutobject. @param target the specified component being laid out.@see Container @see java.awt.Container#doLayout
Returns the minimum dimensions needed to layout the visible components contained in the specified target container. @param target the component which needs to be laid out @return the minimum dimensions to lay out the subcomponents of the specified containerClass FlowLayout, Dimension preferredLayoutSize(Container).@see #preferredLayoutSize @see java.awt.Container @see java.awt.Container#doLayout
Returns the preferred dimensions for this layout given the visible components in the specified target container. @param target the component which needs to be laid out @return the preferred dimensions to lay out the subcomponents of the specified containerClass FlowLayout, void setAlignment(int).@see Container @see #minimumLayoutSize @see java.awt.Container#getPreferredSize
Sets the alignment for this layout. Possible values areClass FlowLayout, String toString()@param align one of the alignment
FlowLayout.LEFTFlowLayout.RIGHTandFlowLayout.CENTERFlowLayout.LEADING- .TRAILING
FlowLayoutvalue.values shown above @see #getAlignment() @since JDK1.1
Returns a string representation of thisClass FlowLayout, int LEADINGFlowLayoutobject and its values. @return a string representation of this layout.
This value indicates that each row of components should be justified to the leading edge of the container's orientationClass FlowLayout, int TRAILINGe.g.for example to the left in left-to-right orientations. @see java.awt.Component#getComponentOrientation @see java.awt.ComponentOrientation @since 1.2 Package-private pending API change approval
This value indicates that each row of components should be justified to theleadingtrailing edge of the container's orientatione.g.for example to the right in left-to-right orientations. @see java.awt.Component#getComponentOrientation @see java.awt.ComponentOrientation @since 1.2 Package-private pending API change approval
TheClass Font, constructor Font(String, int, int)Fontclass represents fonts. Thecapabilities of this class have been extended over thewhich are used to render text in a visiblejava.awtway.Font classinAJDK(tm)font1.1providesand earlier releasesthe information needed toprovide formapdevelopers thesequences ofabilitycharacters toutilize more sophisticated typographicsequencesfeatures.of glyphsIt is important to present the conceptsand to render sequences of glyphs onbehindGraphicsusingandtheComponentwordsobjects.characterCharacters and
A character is a symbol that representsglyph separately.Glyphsitems like letters and numbers inan item such as a letter aparticulardigitwritingorsystempunctuation in an abstract way. For examplelowercase-'g'LATIN SMALL LETTER G is a character.WhenA glyph is a
particularshapecharacterused tohasrenderbeena characterrenderedor ashapesequence of characters. In simple writing systems such as Latinnowtypically one glyph representsthisone character.ThisInshape is called ageneral however characters andglyphglyphs do not have one-to-one correspondence. For exampleChararcterthe characterencoding'á'isLATIN SMALL LETTER A WITH ACUTE can be represented by two glyphs: one for 'a'conversion table thatand one formaps'´'. On the other hand the two-charactercodesstringto"fi" can be represented by a single glyphcodesanin"fi" ligature. In complex writing systems such as Arabic or the South and South-East Asian writing systems the relationship between characters and glyphs can be more complicated and involve context-dependent selection of glyphs as well as glyph reordering. A font encapsulates the collection of glyphs needed to render a selected set of characters as well as the tables needed to map sequences of characters to corresponding sequences of glyphs.Physical and Logical Fonts
The Java 2 platform distinguishes between two kinds of fonts: physical fonts and logical fonts.Physical fonts are the actual font libraries containing glyph data and tables to map from
characterencoding usedsequences toinglyph sequences using a font technology such as TrueType or PostScript Type 1. All implementations of the Java2D(tm)2APIplatform must support TrueType fonts; support for other font technologies isUnicodeimplementation dependent.For more information on Unicode you can visit the sitePhysical fonts may use names such as Helvetica Palatino HonMinchohttp://wwwor any number of other font names.unicodeTypically each physical font supports only a limited set of writing systems for example only Latin characters or only Japanese and Basic Latin.orgThe set of available physical fonts varies between configurations. ApplicationsCharactersthat require specific fonts can bundle them andglyphs do not haveinstantiate them using theone-to-onecreateFontcorrespondencemethod.For
exampleLogicallowercase-afontsacutearecanthe five font families defined by the Java platform which must berepresentedsupported bytwoanyglyphsJava runtime environment:lowercase-aSerif SansSerif Monospaced Dialog andacuteDialogInput.Another example is ligatures such asThese logical fonts are not actualligaturefont-filibraries.whichInstead the logical font names are mapped to physical fonts by the Java runtime environment. The mapping isa single glyph representing twoimplementation and usually locale dependentcharactersso theflook andithe metrics provided by them vary. Typically each logical font name maps to several physical fonts in order to cover a large range of characters.
APeeredFontAWTiscomponents such as Label and TextField can only use logical fonts.For
acollectiondiscussion ofglyphsthe relative advantages and disadvantages of using physical or logical fonts see the Internationalization FAQ document.Font Faces and Names
AFontcan 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
Fontobject. The logical font name isthe same assimply the name thatused by java.awt.Font inwasJDKused1.1toand earlier releasesconstruct the font. 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
Fontclass 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 severalFontobjects associated with a font face each differing in size style transform and font features. The getAllFonts method of theGraphicsEnvironmentclass returns an array of all font faces available in the system. These font faces are returned asFontobjects with a size of 1 identity transform and default font features. These base fonts can then be used to derive newFontobjects with varying sizes styles transforms and font features via thederiveFontmethods in this class. @see GraphicsEnvironment#getAllFonts @version 1.143 02171 12/1303/01
Creates a newClass Font, int canDisplayUpTo(CharacterIterator, int, int)Fontfrom 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 SerifSansSeriforSymbolSansSerif. Ifnameisnullthenameof the newFontis set to the name "Default". @param style the style constant for theFontThe 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
Indicates whether or not thisClass Font, int canDisplayUpTo(char[], int, int)Fontcan 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 theStringstrwhich is the first character thisFontcannot display without using the missing glyph code . If thisFontcan display all characters-1is returned. @paramtextiter 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 theStringobject that can be displayed by thisFont. @since 1.2
Indicates whether or not thisClass Font, Font createFont(int, InputStream)Fontcan display the characters in the specifiedtextstarting atstartand 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 @return an offset intotextthat points to the first character intextthat thisFontcannot display; or-1if thisFontcan display all characters intext. @since 1.2
Returns a newClass Font, GlyphVector createGlyphVector(FontRenderContext, CharacterIterator)Fontwith the specified font type and input data. The newFontis created with a point size of 1 and style PLAIN This base font can then be used with thederiveFontmethods in this class to derive newFontobjects with varying sizes styles transforms and font features. This method does not close the InputStream @paramfontTypefontFormat the type of theFontwhich is TRUETYPE_FONT if a TrueType is desired. Other types might be provided in the future. @param fontStream anInputStreamobject representing the input data for the font. @return a newFontcreated with the specified font type. @throws IllegalArgumentException iffontTypeis notTRUETYPE_FONT@throws FontFormatException if thefontStreamdata does not contain the required Truetype font tables. @throws IOException if thefontStreamcannot be completely read. @since 1.3
Class Font, GlyphVector createGlyphVector(FontRenderContext, String)ReturnsCreates anewGlyphVectorobjectbycreated withmapping the specifiedCharacterIteratorcharactersandto glyphs one-to-one based on thespecifiedUnicode cmap in this. This method does no other processing besides the mapping of glyphs to characters. This means that this method is not useful for some scripts such as Arabic Hebrew Thai and Indic that require reordering shaping or ligature substitution. @param frc the specifiedFontRenderContextFontFontRenderContext@param ci the specifiedCharacterIterator@return a newGlyphVectorcreated with the specifiedCharacterIteratorand the specifiedFontRenderContext.
Class Font, GlyphVector createGlyphVector(FontRenderContext, char[])ReturnsCreates anewGlyphVectorobject createdby mappingwithcharacters to glyphs one-to-one based on thespecifiedUnicode cmap in this.StringFontandThis method does no other processing besides thespecifiedmappingFontRenderContextof glyphs to characters. This means that this method is not useful for some scripts such as Arabic Hebrew Thai and Indic that require reordering shaping or ligature substitution. @param frc the specifiedFontRenderContext@param str the specifiedString@return a newGlyphVectorcreated with the specifiedStringand the specifiedFontRenderContext.
Class Font, GlyphVector createGlyphVector(FontRenderContext, int[])ReturnsCreates anewGlyphVector by mapping characters to glyphs one-to-one based on the Unicode cmap in this.GlyphVectorFontobject created with the specifiedThis method does no otherarrayprocessing besides the mapping of glyphs to characters. This means that this method is not useful for some scripts such as Arabic Hebrew Thai andthe specifiedIndic thatFontRenderContextrequire reordering shaping or ligature substitution. @param frc the specifiedFontRenderContext@param chars the specified array of characters @return a newGlyphVectorcreated with the specified array of characters and the specifiedFontRenderContext.
Class Font, Font decode(String)ReturnsCreates anewGlyphVector by mapping characters to glyphs one-to-one based on the Unicode cmap in this.GlyphVectorFontobject createdThis methodwithdoes no other processing besides thespecified integermapping ofarrayglyphs to characters. This means that this method is not useful for some scripts such as Arabic Hebrew Thai andthe specifiedIndic thatFontRenderContextrequire reordering shaping or ligature substitution. @param frc the specifiedFontRenderContext@paramglyphcodesglyphCodes the specified integer array @return a newGlyphVectorcreated with the specified integer array and the specifiedFontRenderContext.
Returns theClass Font, String getFamily()Fontthat thestrargument describes. To ensure that this method returns the desired Font format thestrparameter in one of two ways:"fontfamilyname-style-pointsize" or
"fontfamilyname style pointsize"in which style is one of the three case-insensitive strings:
"BOLD""BOLDITALIC"or"ITALIC"and pointsize is a decimal representation of the point size. For example if you want a font that is Arial bold and a point size of 18 you would call this method with: "Arial-BOLD-18".The default size is 12 and the default style is PLAIN. If you don't specify a valid size the returned
Fonthas a size of 12. If you don't specify a valid style the returned Font has a style of PLAIN. If you do not provide a valid font family name in thestrargument this method still returns a valid font with a family name of "dialog". To determine what font family names are available on your system use the GraphicsEnvironment#getAvailableFontFamilyNames() method. Ifstrisnulla newFontis returned with the family name "dialog" a size of 12 and a PLAIN style. Ifstrisnulla newFontis returned with the name "dialog" a size of 12 and a PLAIN style. @param str the name of the font ornull@return theFontobject thatstrdescribes or a new defaultFontifstrisnull. @see #getFamily @since JDK1.1
Returns the family name of thisClass Font, String getFamily(Locale)Font.ForThe
examplefamilyHelveticaname ofcouldabefont is font specific. Tworeturnedfonts such asaHelvetica Italic and Helvetica Bold have the same family nameforHelvetica whereasthetheir font facenamenamesofare Helvetica Bold and Helvetica Italic. The list of available family names may be obtained by using the GraphicsEnvironment#getAvailableFontFamilyNames() method.Use
getNameto get the logical name of the font. UsegetFontNameto get the font face name of the font. @return aStringthat is the family name of thisFont. @see #getName @see #getFontName @since JDK1.1
Returns the family name of thisClass Font, Font getFont(Map)Fontlocalized for the specified locale.ForThe
examplefamilyHelveticaname ofcouldabefont is font specific. Two fontsreturnedsuch asaHelvetica Italic and Helvetica Bold have the same family nameforHelveticathewhereas their font facename ofnames are Helvetica Bold and Helvetica Italic. The list of available family names may be obtained by using the GraphicsEnvironment#getAvailableFontFamilyNames() method.Use
getFontNameto get the font face name of the font. @param l locale for which to get the family name @return aStringrepresenting the family name of the font localized for the specified locale. @see #getFontName @see java.util.Locale @since 1.2
Returns aClass Font, Rectangle2D getStringBounds(CharacterIterator, int, int, FontRenderContext)Fontappropriate to this attribute set. @param attributes the attributes to assign to the newFont@return a newFontcreated with the specified attributes.@since 1.2 @see java.awt.font.TextAttribute
Returns the logical bounds of the characters indexed in the specified CharacterIterator in the specifiedClass Font, Rectangle2D getStringBounds(String, FontRenderContext)FontRenderContext. The logical boundsiscontains the origin ascent advance and height which includes the leading. The logical bounds does not always enclose all the text. For example in some languages and in some fonts accent marks can be positioned above the ascent or below the descent.used toTo obtainlayouta visual bounding box which encloses all the text use the getBounds method of. @param ci the specifiedStringTextLayoutCharacterIterator@param beginIndex the initial offset inci@param limit the end offset inci@param frc the specifiedFontRenderContext@return aRectangle2Dthat is the bounding box of the characters indexed in the specifiedCharacterIteratorin the specifiedFontRenderContext. @see FontRenderContext @see Font#createGlyphVector @since 1.2 @throws IndexOutOfBoundsException ifbeginIndexis less than the start index ofciorlimitis greater than the end index ofciorbeginIndexis greater thanlimit
Returns the logical bounds of the specifiedClass Font, Rectangle2D getStringBounds(String, int, int, FontRenderContext)Stringin the specifiedFontRenderContext. The logical boundsiscontains the origin ascent advance and height which includes the leading. The logical bounds does not always enclose all the text. For example in some languages and in some fonts accent marks can be positioned above the ascent or below the descent. Tousedobtaintoa visual bounding box which encloses alllayoutthe text use the getBounds method of. @param str the specifiedStringTextLayoutString@param frc the specifiedFontRenderContext@return a Rectangle2D that is the bounding box of the specifiedStringin the specifiedFontRenderContext. @see FontRenderContext @see Font#createGlyphVector @since 1.2
Returns the logical bounds of the specifiedClass Font, Rectangle2D getStringBounds(char[], int, int, FontRenderContext)Stringin the specifiedFontRenderContext. The logical boundsiscontains the origin ascent advance and height which includes the leading. The logical bounds does not always enclose all the text. For example in some languages and in some fonts accent marks can be positioned above the ascent or below the descent.used toTo obtainlayouta visual bounding box which encloses all the text use the getBounds method of. @param str the specifiedStringTextLayoutString@param beginIndex the initial offset ofstr@param limit the end offset ofstr@param frc the specifiedFontRenderContext@return aRectangle2Dthat is the bounding box of the specifiedStringin the specifiedFontRenderContext. @throws IndexOutOfBoundsException ifbeginIndexis less than zero orlimitis greater than the length ofstrorbeginIndexis greater thanlimit. @see FontRenderContext @see Font#createGlyphVector @since 1.2
Returns the logical bounds of the specified array of characters in the specifiedClass Font, AffineTransform getTransform()FontRenderContext. The logical boundsiscontains the origin ascent advance andused to layoutheight which includes theStringleading. The logical bounds doescreated withnot always enclose all thespecifiedtext.array of charactersFor example inbeginIndexsome languages and in some fonts accent marks can be positioned above the ascent or below the descent. To obtain a visual bounding box which encloses all the text use the getBounds method of. @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 specifiedlimitTextLayoutFontRenderContext@return aRectangle2Dthat is the bounding box of the specified array of characters in the specifiedFontRenderContext. @throws IndexOutOfBoundsException ifbeginIndexis less than zero orlimitis greater than the length ofcharsorbeginIndexis greater thanlimit. @see FontRenderContext @see Font#createGlyphVector @since 1.2
Returns a copy of the transform associated with thisClass Font, int CENTER_BASELINEFont. @paramreturn an AffineTransform object representing the transform attribute of thisFontobject.
The baseline used in ideographic scripts like Chinese Japanese and Korean when laying out text.Class Font, int HANGING_BASELINE
The baseline used in Devanigiri and similar scripts when laying out text.Class Font, int ROMAN_BASELINE
The baseline used in most Roman scripts when laying out text.
Thrown by method createFont in theClass FontFormatException, constructor FontFormatException(String)Fontclass to indicate that the specified font is bad. @author Parry Kejriwal @version 1.4 026 12/0203/0001 @see java.awt.Font @since 1.3
Report a FontFormatException for the reason specified. @param reason a String message indicating why the font is not accepted.
TheClass FontMetrics, int charWidth(char)FontMetricsclass defines a font metrics object which encapsulates information about the rendering of a particular font on a particular screen.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.
An array of characters or a string can also have an ascent a descent and an advance width. The ascent of the array is the maximum ascent of any character in the array. The descent is the maximum descent of any character in the array. The advance width is the sum of the advance widths of each of the characters in the character array. The advance of a
Stringis the distance along the baseline of theString. This distance is the width that should be used for centering or right-aligning theString. Note that the advance of aStringis not necessarily the sum of the advances of its characters measured in isolation because the width of a character can vary depending on its context. For example in Arabic text the shape of a character can change in order to connect to other characters. Also in some scripts certain character sequences can be represented by a single shape called a ligature. Measuring characters individually does not account for these transformations. @version 1.21 0347 12/1803/9801 @author Jim Graham @see java.awt.Font @since JDK1.0
Returns the advance width of the specified character in thisClass FontMetrics, int getHeight()Font. The advance is the distance from the leftmost point to the rightmost point on the character's baseline. Note that the advance of aStringis not necessarily the sum of the advances of its characters. @param ch the character to be measured @return the advance width of the specifiedcharin theFontdescribed by thisFontMetricsobject. @see #charsWidth(char[] int int) @see #stringWidth(String)
Gets the standard height of a line of text in this font. This is the distance between the baseline of adjacent lines of text. It is the sum of the leading + ascent + descent. Due to rounding this may not be the same as getAscent() + getDescent() + getLeading(). There is no guarantee that lines of text spaced at this distance are disjoint; such lines may overlap if some characters overshoot either the standard ascent or the standard descent metric. @return the standard height of the font. @see #getLeading() @see #getAscent() @see #getDescent()Class FontMetrics, int getMaxDecent()
For backward compatibility only. @return the maximum descent of any character in theFont. @see #getMaxDescent() @deprecated As of JDK version 1.1.1 replaced bygetMaxDescent().
AClass Frame, constructor Frame()Frameis a top-level window with a title and a border.The size of the frame includes any area designated for the border. The dimensions of the border area
canmay be obtained using thegetInsetsmethod however since these dimensions are platform-dependent a valid insets value cannot be obtained until the frame is made displayable by either callingpackorshow. 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.A frame may have its native decorations (i.e.
. This can only be done while the frame is not displayableFrameandTitlebar) turned off withsetUndecoratedIn a multi-screen environment you can create a
Frameon a different screen device by constructing theFramewith #Frame(GraphicsConfiguration) or titl GraphicsConfiguration)}. TheGraphicsConfigurationobject is one of theGraphicsConfigurationobjects 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
setLocationyou must pass a virtual coordinate to this method. Similarly callinggetLocationOnScreenon aFramereturns virtual device coordinates. Call thegetBoundsmethod of aGraphicsConfigurationto find its origin in the virtual coordinate system.The following code sets the location of the
Frameat (10 10) relative to the origin of the physical screen of the correspondingGraphicsConfiguration. If the bounds of theGraphicsConfigurationis not taken into account theFramelocation 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 eventsWindowEvents:WindowOpened@version 1.
WINDOW_OPENEDWINDOW_CLOSINGWINDOW_CLOSEDWINDOW_ICONIFIEDWINDOW_DEICONIFIEDWindowClosingWINDOW_ACTIVATEDWindowClosedWINDOW_DEACTIVATEDWindowIconifiedWINDOW_GAINED_FOCUSWindowDeiconifiedWINDOW_LOST_FOCUSWindowActivatedWINDOW_STATE_CHANGEDWindowDeactivated.108 04131 12/0603/0001 @author Sami Shaio @see WindowEvent @see Window#addWindowListener @since JDK1.0
Constructs a new instance ofClass Frame, constructor Frame(GraphicsConfiguration)Framethat is initially invisible. The title of theFrameis empty. @exception HeadlessException when GraphicsEnvironment.isHeadless() returns true @see java.awt.GraphicsEnvironment#isHeadless() @see Component#setSize @see Component#setVisible(boolean)
Create aClass Frame, constructor Frame(String)Framewith the specifiedGraphicsConfigurationof a screen device. @param gc theGraphicsConfigurationof the target screen device. Ifgcisnullthe system defaultGraphicsConfigurationis assumed. @exception IllegalArgumentException ifgcis not from a screen device. This exception is always thrown when GraphicsEnvironment.isHeadless() returns true @see java.awt.GraphicsEnvironment#isHeadless() @since 1.3
Constructs a new initially invisibleClass Frame, constructor Frame(String, GraphicsConfiguration)Frameobject with the specified title. @param title the title to be displayed in the frame's border. Anullvalue is treated as an empty string "". @exceptionIllegalArgumentException ifHeadlessException whengc is notGraphicsEnvironment.isHeadless()from areturns truescreen@seedevicejava.awt.GraphicsEnvironment#isHeadless() @see java.awt.Component#setSize @see java.awt.Component#setVisible(boolean) @see java.awt.GraphicsConfiguration#getBounds
Constructs a new initially invisibleClass Frame, Image getIconImage()Frameobject with the specified title and aGraphicsConfiguration. @param title the title to be displayed in the frame's border. Anullvalue is treated as an empty string "". @param gc theGraphicsConfigurationof the target screen device. Ifgcisnullthe system defaultGraphicsConfigurationis assumed. @exception IllegalArgumentException ifgcis not from a screen device. This exception is always thrown when GraphicsEnvironment.isHeadless() returns true @see java.awt.GraphicsEnvironment#isHeadless() @see java.awt.Component#setSize @see java.awt.Component#setVisible(boolean) @see java.awt.GraphicsConfiguration#getBounds
Gets the image to be displayed in the minimized icon for this frame. @return the icon image for this frame orClass Frame, MenuBar getMenuBar()nullif this frame doesn't have an icon image. @seejava.awt.Frame#setIconImage(Icon)
Gets the menu bar for this frame. @return the menu bar for this frame orClass Frame, int getState()nullif this frame doesn't have a menu bar. @seejava.awt.Frame#setMenuBar(MenuBar)
Gets the state of this frame (obsolete).Class Frame, String getTitle()@return
Frame.In older versions of JDK a frame state could only be NORMAL or ICONIFIED. Since JDK 1.4 set ofifsupported frameinstatesiconicis expanded and frame state;is represented as a bitwise mask.For compatibility with old programs this method still
returnsFrame.NORMALifandFrame.ICONIFIEDbut it only reports the iconic state of the frameisother aspectsin normalof frame state are not reported by this method. @seereturnjava.awtFrame.NORMALorFrame.ICONIFIED. @see #setState(int) @see #getExtendedState
Gets the title of the frame. The title is displayed in the frame's border. @return the title of this frame or an empty string ("") if this frame doesn't have a title. @seeClass Frame, boolean isResizable()java.awt.Frame#setTitle(String)
Indicates whether this frame is resizable by the user. By default all frames are initially resizable. @returnClass Frame, String paramString()trueif the user can resize this frame;falseotherwise. @see java.awt.Frame#setResizable(boolean)
ReturnsClass Frame, void remove(MenuComponent)theaparameterstring representing theStringstate of thisFrame. This method is intended to be used only for debugging purposes and the content and format of the returned string may vary between implementations. The returned string may be empty but may not benull. @return the parameter string of this frame
Removes the specified menu bar from this frame. @param m the menu component to remove. IfClass Frame, void setIconImage(Image)this parametermisnullthena NullPointerException is thrown andno action is taken.
Sets the image to be displayed in the minimized icon for this frame. Not all platforms support the concept of minimizing a window. @param image the icon image to be displayed. If this parameter isClass Frame, void setMenuBar(MenuBar)nullthen the icon image is set to the default image which may vary with platform. @seejava.awt.Frame#getIconImage
Sets the menu bar for this frame to the specified menu bar. @param mb the menu bar being set. If this parameter isClass Frame, void setState(int)nullthen any existing menu bar on this frame is removed. @seejava.awt.Frame#getMenuBar
Sets the state of this frame (obsolete).Class Frame, void setTitle(String)@paramIn older versions of JDK a frame state
Frame.could only be NORMAL or ICONIFIEDif. SincethisJDK 1.4 set of supported frame states isin iconicexpanded and frame state;is represented as a bitwise mask.For compatibility with old programs this method still accepts
Frame.NORMALifandthisFrame.ICONIFIEDbut it only changes the iconic state of the frameisother aspectsin normalof frame state are not affected by this method. @seeparamjava.awtstate eitherFrame.NORMAL orFrame.ICONIFIED. @see #getState @see #setExtendedState(int)
Sets the title for this frame to the specified string. @param title the title to be displayed in the frame's border @param title the title to be displayed in the frame's border. Anullvalue is treated as an empty string "". @seejava.awt.Frame#getTitle
Constructs a simple acyclicClass GradientPaint, constructor GradientPaint(Point2D, Color, Point2D, Color, boolean)GradientPaintobject. @param pt1 the first specifiedPointin user space @param color1Colorat the first specifiedPoint@param pt2 the second specifiedPointin user space @param color2Colorat the second specifiedPoint@throws NullPointerException if either one of colors or points is null
Constructs either a cyclic or acyclicClass GradientPaint, constructor GradientPaint(float, float, Color, float, float, Color)GradientPaintobject depending on thebooleanparameter. @param pt1 the first specifiedPointin user space @param color1Colorat the first specifiedPoint@param pt2 the second specifiedPointin user space @param color2Colorat the second specifiedPoint@param cyclictrueif the gradient pattern should cycle repeatedly between the two colors;falseotherwise @throws NullPointerException if either one of colors or points is null
Constructs a simple acyclicGradientPaintobject. @param x1 y1 coordinates of the first specifiedPointin user space @param color1Colorat the first specifiedPoint@param x2 y2 coordinates of the second specifiedPointin user space @param color2Colorat the second specifiedPoint@throws NullPointerException if either one of colors is null
TheClass Graphics, boolean drawImage(Image, int, int, Color, ImageObserver)Graphicsclass 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
Graphicsobject encapsulates state information needed for the basic rendering operations that Java supports. This state information includes the following properties:
- The
Componentobject 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
Graphicsobject are considered relative to the translation origin of thisGraphicsobject 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
Graphicsobject. 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 thesetCliporclipRectmethods. All drawing or writing is done in the current color using the current paint mode and in the current font. @version 1.63 0564 12/2403/01 @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 as much of the specified image as is currently available. The image is drawn with its top-left corner at (x y) in this graphics context's coordinate space. Transparent pixels are drawn in the specified background color.Class Graphics, boolean drawImage(Image, int, int, ImageObserver)This operation is equivalent to filling a rectangle of the width and height of the specified image with the given color and then drawing the image on top of it but possibly more efficient.
This method returns immediately in all cases even if the complete image has not yet been loaded and it has not been dithered and converted for the current output device.
If the image has not yet been completely loaded then
drawImagereturnsfalse. As more of the image becomes available the process that draws the image notifies the specified image observer. @param img the specified image to be drawn. @param x the x coordinate. @param y the y coordinate. @param bgcolor the background color to paint under the non-opaque portions of the image. @param observer object to be notified as more of the image is converted. @returntrueif the image is completely loaded;falseotherwise. @see java.awt.Image @see java.awt.image.ImageObserver @see java.awt.image.ImageObserver#imageUpdate(java.awt.Image int int int int int)
Draws as much of the specified image as is currently available. The image is drawn with its top-left corner at (x y) in this graphics context's coordinate space. Transparent pixels in the image do not affect whatever pixels are already there.Class Graphics, boolean drawImage(Image, int, int, int, int, Color, ImageObserver)This method returns immediately in all cases even if the complete image has not yet been loaded and it has not been dithered and converted for the current output device.
If the image has not yet been completely loaded then
drawImagereturnsfalse. As more of the image becomes available the process that draws the image notifies the specified image observer. @param img the specified image to be drawn. @param x the x coordinate. @param y the y coordinate. @param observer object to be notified as more of the image is converted. @returntrueif the image is completely loaded;falseotherwise. @see java.awt.Image @see java.awt.image.ImageObserver @see java.awt.image.ImageObserver#imageUpdate(java.awt.Image int int int int int)
Draws as much of the specified image as has already been scaled to fit inside the specified rectangle.Class Graphics, boolean drawImage(Image, int, int, int, int, ImageObserver)The image is drawn inside the specified rectangle of this graphics context's coordinate space and is scaled if necessary. Transparent pixels are drawn in the specified background color. This operation is equivalent to filling a rectangle of the width and height of the specified image with the given color and then drawing the image on top of it but possibly more efficient.
This method returns immediately in all cases even if the entire image has not yet been scaled dithered and converted for the current output device. If the current output representation is not yet complete then
drawImagereturnsfalse. As more of the image becomes available the process that draws the image notifies the specified image observer.A scaled version of an image will not necessarily be available immediately just because an unscaled version of the image has been constructed for this output device. Each size of the image may be cached separately and generated from the original data in a separate image production sequence. @param img the specified image to be drawn. @param x the x coordinate. @param y the y coordinate. @param width the width of the rectangle. @param height the height of the rectangle. @param bgcolor the background color to paint under the non-opaque portions of the image. @param observer object to be notified as more of the image is converted. @return
trueif the current output representation is complete;falseotherwise. @see java.awt.Image @see java.awt.image.ImageObserver @see java.awt.image.ImageObserver#imageUpdate(java.awt.Image int int int int int)
Draws as much of the specified image as has already been scaled to fit inside the specified rectangle.Class Graphics, boolean drawImage(Image, int, int, int, int, int, int, int, int, Color, ImageObserver)The image is drawn inside the specified rectangle of this graphics context's coordinate space and is scaled if necessary. Transparent pixels do not affect whatever pixels are already there.
This method returns immediately in all cases even if the entire image has not yet been scaled dithered and converted for the current output device. If the current output representation is not yet complete then
drawImagereturnsfalse. As more of the image becomes available the process that draws the image notifies the image observer by calling itsimageUpdatemethod.A scaled version of an image will not necessarily be available immediately just because an unscaled version of the image has been constructed for this output device. Each size of the image may be cached separately and generated from the original data in a separate image production sequence. @param img the specified image to be drawn. @param x the x coordinate. @param y the y coordinate. @param width the width of the rectangle. @param height the height of the rectangle. @param observer object to be notified as more of the image is converted. @return
trueif the current output representation is complete;falseotherwise. @see java.awt.Image @see java.awt.image.ImageObserver @see java.awt.image.ImageObserver#imageUpdate(java.awt.Image int int int int int)
Draws as much of the specified area of the specified image as is currently available scaling it on the fly to fit inside the specified area of the destination drawable surface.Class Graphics, boolean drawImage(Image, int, int, int, int, int, int, int, int, ImageObserver)Transparent pixels are drawn in the specified background color. This operation is equivalent to filling a rectangle of the width and height of the specified image with the given color and then drawing the image on top of it but possibly more efficient.
This method returns immediately in all cases even if the image area to be drawn has not yet been scaled dithered and converted for the current output device. If the current output representation is not yet complete then
drawImagereturnsfalse. As more of the image becomes available the process that draws the image notifies the specified image observer.This method always uses the unscaled version of the image to render the scaled rectangle and performs the required scaling on the fly. It does not use a cached scaled version of the image for this operation. Scaling of the image from source to destination is performed such that the first coordinate of the source rectangle is mapped to the first coordinate of the destination rectangle and the second source coordinate is mapped to the second destination coordinate. The subimage is scaled and flipped as needed to preserve those mappings. @param img the specified image to be drawn @param dx1 the x coordinate of the first corner of the destination rectangle. @param dy1 the y coordinate of the first corner of the destination rectangle. @param dx2 the x coordinate of the second corner of the destination rectangle. @param dy2 the y coordinate of the second corner of the destination rectangle. @param sx1 the x coordinate of the first corner of the source rectangle. @param sy1 the y coordinate of the first corner of the source rectangle. @param sx2 the x coordinate of the second corner of the source rectangle. @param sy2 the y coordinate of the second corner of the source rectangle. @param bgcolor the background color to paint under the non-opaque portions of the image. @param observer object to be notified as more of the image is scaled and converted. @return
trueif the current output representation is complete;falseotherwise. @see java.awt.Image @see java.awt.image.ImageObserver @see java.awt.image.ImageObserver#imageUpdate(java.awt.Image int int int int int) @since JDK1.1
Draws as much of the specified area of the specified image as is currently available scaling it on the fly to fit inside the specified area of the destination drawable surface. Transparent pixels do not affect whatever pixels are already there.Class Graphics, Rectangle getClipRect()This method returns immediately in all cases even if the image area to be drawn has not yet been scaled dithered and converted for the current output device. If the current output representation is not yet complete then
drawImagereturnsfalse. As more of the image becomes available the process that draws the image notifies the specified image observer.This method always uses the unscaled version of the image to render the scaled rectangle and performs the required scaling on the fly. It does not use a cached scaled version of the image for this operation. Scaling of the image from source to destination is performed such that the first coordinate of the source rectangle is mapped to the first coordinate of the destination rectangle and the second source coordinate is mapped to the second destination coordinate. The subimage is scaled and flipped as needed to preserve those mappings. @param img the specified image to be drawn @param dx1 the x coordinate of the first corner of the destination rectangle. @param dy1 the y coordinate of the first corner of the destination rectangle. @param dx2 the x coordinate of the second corner of the destination rectangle. @param dy2 the y coordinate of the second corner of the destination rectangle. @param sx1 the x coordinate of the first corner of the source rectangle. @param sy1 the y coordinate of the first corner of the source rectangle. @param sx2 the x coordinate of the second corner of the source rectangle. @param sy2 the y coordinate of the second corner of the source rectangle. @param observer object to be notified as more of the image is scaled and converted. @return
trueif the current output representation is complete;falseotherwise. @see java.awt.Image @see java.awt.image.ImageObserver @see java.awt.image.ImageObserver#imageUpdate(java.awt.Image int int int int int) @since JDK1.1
Returns the bounding rectangle of the current clipping area. @return the bounding rectangle of the current clipping area orClass Graphics, Color getColor()nullif no clip is set. @deprecated As of JDK version 1.1 replaced bygetClipBounds().
Gets this graphics context's current color. @return this graphics context's current color. @see java.awt.Color @see java.awt.Graphics#setColor(Color)Class Graphics, Font getFont()
Gets the current font. @return this graphics context's current font. @see java.awt.Font @see java.awt.Graphics#setFont(Font)Class Graphics, boolean hitClip(int, int, int, int)
Returns true if the specified rectangular areaClass Graphics, void setClip(int, int, int, int)intersects the boundingmightrectangle ofintersect the current clipping area. The coordinates of the specified rectangular area are in therectangleuser coordinate space and are relative to the coordinate system origin of this graphics context. This method may use an algorithm that calculates a result quickly but which sometimes might return true even if the specified rectangular area does not intersect the clipping area. The specific algorithm employed may thus trade off accuracy for speed but it will never return false unless it can guarantee that the specified rectangular area does not intersect the current clipping area. The clipping area used by this method can represent the intersection of the user clip as specified through the clip methods of this graphics context as well as the clipping associated with the device or image bounds and window visibility. @param x the x coordinate of the rectangle to test against the clip @param y the y coordinate of the rectangle to test against the clip @param width the width of the rectangle to test against the clip @param height the height of the rectangle to test against the clip @returntrueif the specified rectangle intersects the bounds of the current clip;falseotherwise.
Sets the current clip to the rectangle specified by the given coordinates. This method sets the user clip which is independent of the clipping associated with device bounds and window visibility. Rendering operations have no effect outside of the clipping area. @param x the x coordinate of the new clip rectangle. @param y the y coordinate of the new clip rectangle. @param width the width of the new clip rectangle. @param height the height of the new clip rectangle. @see java.awt.Graphics#clipRect @see java.awt.Graphics#setClip(Shape) @see java.awt.Graphics#getClip @since JDK1.1
ThisClass Graphics2D, void drawGlyphVector(GlyphVector, float, float)Graphics2Dclass 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 aGraphics2Dobject are specified in a device-independent coordinate system called User Space which is used by applications. TheGraphics2Dobject 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
Graphics2Dobjects 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 theGraphics2DTransformis 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
Graphics2Dmethods take user space coordinates.Every
Graphics2Dobject 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 aGraphics2Dobject.When creating a
Graphics2Dobject theGraphicsConfigurationspecifies 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 theIdentitytransform.Rendering Process
The Rendering Process can be broken down into four phases that are controlled by theGraphics2Drendering 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. TheClipis specified by a Shape in user space and is controlled by the program using the various clip manipulation methods ofGraphicsandGraphics2D. This user clip is transformed into device space by the currentTransformand 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
Graphics2Dcontext.
The three types of rendering operations along with details of each of their particular rendering processes are:
Shapeoperations
- If the operation is a
draw(Shape)operation then the createStrokedShape method on the current Stroke attribute in theGraphics2Dcontext is used to construct a newShapeobject that contains the outline of the specifiedShape.- The
Shapeis transformed from user space to device space using the currentTransformin theGraphics2Dcontext.- The outline of the
Shapeis extracted using the getPathIterator method ofShapewhich returns a PathIterator object that iterates along the boundary of theShape.- If the
Graphics2Dobject cannot handle the curved segments that thePathIteratorobject returns then it can call the alternate double getPathIterator} method ofShapewhich flattens theShape.- The current Paint in the
Graphics2Dcontext 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
Stringthen the currentFontin theGraphics2Dcontext is asked to convert the Unicode characters in theStringinto 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
TextLayoutimplements 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
GlyphVectorobject already contains the appropriate font-specific glyph codes with explicit coordinates for the position of each glyph.- The current
Fontis 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
Shapeoperations.- The current
Paintis queried for aPaintContextwhich specifies the colors to render in device space.ImageOperations
- The region of interest is defined by the bounding box of the source
Image. This bounding box is specified in Image Space which is theImageobject's local coordinate system.- If an
AffineTransformis passed to java.awt.geom.AffineTransfor java.awt.image.ImageObserver) drawImage(Image AffineTransform ImageObserver)} theAffineTransformis used to transform the bounding box from image space to user space. If noAffineTransformis supplied the bounding box is treated as if it is already in user space.- The bounding box of the source
Imageis 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
Imageobject determines what colors to render sampled according to the source to destination coordinate mapping specified by the currentTransformand the optional image transform.Default Rendering Attributes
The default values for theGraphics2Drendering attributes are:
Paint- The color of the
Component.Font- The
Fontof theComponent.Stroke- A square pen with a linewidth of 1 no dashing miter segment joins and square end caps.
Transform- The getDefaultTransform for the
GraphicsConfigurationof theComponent.Composite- The AlphaComposite#SRC_OVER rule.
Clip- No rendering
Clipthe 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) (Java(tm) 2 platform) API supports antialiasing renderers. A pen with a width of one pixel does not need to fall completely on pixel N as opposed to pixel N+1. The pen can fall partially on both pixels. It is not necessary to choose a bias direction for a wide pen since the blending that occurs along the pen traversal edges makes the sub-pixel position of the pen visible to the user. On the other hand when antialiasing is turned off by setting the 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 the KEY_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
drawandfillmethods are defined which clearly indicates howGraphics2DextendsGraphicsbased on settings ofStrokeandTransformattributes and rendering hints. The definition performs identically under default attribute settings. For example the defaultStrokeis aBasicStrokewith 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.
- Lines and paths stroked using the
BasicStrokeobject may be "normalized" to provide consistent rendering of the outlines when positioned at various points on the drawable and whether drawn with aliased or antialiased rendering. This normalization process is controlled by the KEY_STROKE_CONTROL hint. The exact normalization algorithm is not specified but the goals of this normalization are to ensure that lines are rendered with consistent visual appearance regardless of how they fall on the pixel grid and to promote more solid horizontal and vertical lines in antialiased mode so that they resemble their non-antialiased counterparts more closely. A typical normalization step might promote antialiased line endpoints to pixel centers to reduce the amount of blending or adjust the subpixel positioning of non-antialiased lines so that the floating point line widths round to even or odd pixel counts with equal likelihood. This process can move endpoints by up to half a pixel (usually towards positive infinity along both axes) to promote these consistent results.The following definitions of general legacy methods perform identically to previously specified behavior under default attribute settings:
The
- For
filloperations includingfillRectfillRoundRectfillOvalfillArcfillPolygonandclearRectfill 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
drawLinedrawRectdrawRoundRectdrawOvaldrawArcdrawPolylineanddrawPolygondraw can now be called with the desiredShape. For example when drawing a rectangle:draw(new Rectangle(x y w h));is called.
- The
draw3DRectandfill3DRectmethods were implemented in terms of thedrawLineandfillRectmethods in theGraphicsclass which would predicate their behavior upon the currentStrokeandPaintobjects in aGraphics2Dcontext. This class overrides those implementations with versions that use the currentColorexclusively overriding the currentPaintand which usesfillRectto describe the exact same behavior as the preexisting methods regardless of the setting of the currentStroke.Graphicsclass defines only thesetColormethod to control the color to be painted. Since the Java 2D API extends theColorobject to implement the newPaintinterface the existingsetColormethod is now a convenience method for setting the currentPaintattribute to aColorobject.setColor(c)is equivalent tosetPaint(c).The
Graphicsclass defines two methods for controlling how colors are applied to the destination.@version 1.
- The
setPaintModemethod is implemented as a convenience method to set the defaultCompositeequivalent tosetComposite(new AlphaComposite.SrcOver).- The
setXORMode(Color xorcolor)method is implemented as a convenience method to set a specialCompositeobject that ignores theAlphacomponents of source colors and sets the destination color to the value:dstpixel = (PixelOf(srccolor) ^ PixelOf(xorcolor) ^ dstpixel);70 0276 12/0203/0001 @author Jim Graham @see java.awt.RenderingHints
Renders the text of the specified GlyphVector using theClass Graphics2D, void drawString(String, float, float)Graphics2Dcontext's rendering attributes. The rendering attributes applied include theClipTransformPaintandCompositeattributes. TheGlyphVectorspecifies individual glyphs from a Font TheGlyphVectorcan also contain the glyph positions. This is the fastest way to render a set of characters to the screen. @param g theGlyphVectorto be rendered @param x y the position in User Space where the glyphs should be rendered @see java.awt.fontFont#createGlyphVector @see java.awt.font.GlyphVector @see #setPaint @see java.awt.Graphics#setColor @see #setTransform @see #setComposite @see #setClip
Renders the text specified by the specifiedClass Graphics2D, void drawString(String, int, int)Stringusing the currentFont andtextPaintattributeattributesstate in theGraphics2Dcontext. The baseline of the first character is at position (x y) in the User Space. The rendering attributes applied include theClipTransformPaintFontandCompositeattributes. 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 theStringto be rendered @param x y the coordinates where theStringshould be rendered @throws NullPointerException ifstrisnull@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, GraphicsConfiguration getDeviceConfiguration()Stringusing the currentFont andtextPaintattributeattributesstate in theGraphics2Dcontext. The baseline of the first character is at position (x y) in the User Space. The rendering attributes applied include theClipTransformPaintFontandCompositeattributes. 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 theStringshould be rendered @throws NullPointerException ifstrisnull@see java.awt.Graphics#drawBytes @see java.awt.Graphics#drawChars @since JDK1.0
Returns the device configuration associated with thisClass Graphics2D, Object getRenderingHint(Key)Graphics2D. @return the device configuration of thisGraphics2D.
Returns the value of a single preference for the rendering algorithms. Hint categories include controls for rendering quality and overall time/quality trade-off in the rendering process. Refer to theClass Graphics2D, RenderingHints getRenderingHints()RenderingHintsclass for definitions of some common keys and values. @param hintKey the key corresponding to the hint to get. @return an object representing the value for the specified hint key. Some of the keys and their associated values are defined in theRenderingHintsclass. @see RenderingHints @see #setRenderingHint(RenderingHints.Key Object)
Gets the preferences for the rendering algorithms. Hint categories include controls for rendering quality and overall time/quality trade-off in the rendering process. Returns all of the hint key/value pairs that were ever specified in one operation. Refer to theClass Graphics2D, void setComposite(Composite)RenderingHintsclass for definitions of some common keys and values. @return a reference to an instance ofRenderingHintsthat contains the current preferences. @see RenderingHints @see #setRenderingHints(Map)
Sets theClass Graphics2D, void setPaint(Paint)Compositefor theGraphics2Dcontext. TheCompositeis used in all drawing methods such asdrawImagedrawStringdrawandfill. It specifies how new pixels are to be combined with the existing pixels on the graphics device during the rendering process.If this
Graphics2Dcontext is drawing to aComponenton the display screen and theCompositeis a custom object rather than an instance of theAlphaCompositeclass and if there is a security manager itscheckPermissionmethod is called with anAWTPermission("readDisplayPixels")permission. @throws SecurityException if a customCompositeobject is being used to render to the screen and a security manager is set and itscheckPermissionmethod does not allow the operation. @param comp theCompositeobject to be used for rendering @see java.awt.Graphics#setXORMode @see java.awt.Graphics#setPaintMode @see #getComposite @see AlphaComposite @see SecurityManager#checkPermission @see java.awt.AWTPermission
Sets theClass Graphics2D, void setRenderingHint(Key, Object)Paintattribute for theGraphics2Dcontext. Calling this method with anullPaintobject does not have any effect on the currentPaintattribute of thisGraphics2D. @param paint thePaintobject to be used to generate color during the rendering process ornull@see java.awt.Graphics#setColor @see #getPaint @see GradientPaint @see TexturePaint
Sets the value of a single preference for the rendering algorithms. Hint categories include controls for rendering quality and overall time/quality trade-off in the rendering process. Refer to the RenderingHints class for definitions of some common keys and values. @param hintKey the key of the hint to be set. @param hintValue the value indicating preferences for the specified hint category. @see #getRenderingHint(RenderingHints.Key) @see RenderingHints
Class Graphics2D, void setRenderingHints(Map)Replaces the values of all preferences for the rendering algorithms with the specifiedClass Graphics2D, void setStroke(Stroke)hints. The existing values for all rendering hints are discarded and the new set of known hints and values are initialized from the specified Map object. Hint categories include controls for rendering quality and overall time/quality trade-off in the rendering process. Refer to theRenderingHintsclass for definitions of some common keys and values. @param hints the rendering hints to be set @see #getRenderingHints @see RenderingHints
Sets theClass Graphics2D, void setTransform(AffineTransform)Strokefor theGraphics2Dcontext. @param s theStrokeobject to be used to stroke aShapeduring the rendering process @see BasicStroke @see #getStroke
SetsOverwrites the Transform in theGraphics2Dcontext. WARNING: This method should never be used to apply a new coordinate transform on top of an existing transform because theGraphics2Dmight already have a transform that is needed for other purposes such as rendering Swing components or applying a scaling transformation to adjust for the resolution of a printer.To add a coordinate transform use the
transformrotatescaleorshearmethods. ThesetTransformmethod is intended only for restoring the originalGraphics2Dtransform after rendering as shown in this example:@param Tx the// Get the current transform AffineTransform saveAT = g2.getTransform(); // Perform transformation g2d.transform(...); // Render g2d.draw(...); // Restore original transform g2d.setTransform(saveAT);AffineTransformobject tothatbe used inwas retrieved from therenderinggetTransformprocessmethod @see #transform @see #getTransform @see AffineTransform
TheGraphicsConfigTemplateclass 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 validGraphicsConfigurationis returned that meets or exceeds what was requested in theGraphicsConfigTemplate. @see GraphicsDevice @see GraphicsConfiguration @version 1.13 0214 12/0203/0001 @since 1.2
TheGraphicsDeviceclass 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 theGraphicsDevicecan be used.In a multi-screen environment the
GraphicsConfigurationobjects can be used to render components on multiple screens. The following code sample demonstrates how to create aJFrameobject for eachGraphicsConfigurationon each screen device in theGraphicsEnvironment:GraphicsEnvironment ge = GraphicsEnvironment. getLocalGraphicsEnvironment(); GraphicsDevice[] gs = ge.getScreenDevices(); for (int j = 0; j@see GraphicsEnvironment @see GraphicsConfiguration @version 1. 21 0225 12/0903/01
TheClass GraphicsEnvironment, String[] getAvailableFontFamilyNames()GraphicsEnvironmentclass describes the collection of GraphicsDevice objects and java.awt.Font objects available to a Java(tm) application on a particular platform. The resources in thisGraphicsEnvironmentmight be local or on a remote machine.GraphicsDeviceobjects can be screens printers or image buffers and are the destination of Graphics2D drawing methods. EachGraphicsDevicehas a number of GraphicsConfiguration objects associated with it. These objects specify the different configurations in which theGraphicsDevicecan be used. @see GraphicsDevice @see GraphicsConfiguration @version 1.42 0251 12/0203/0001
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
Fontinstance is used to render text but allows theFontobject more flexibility in choosing its own best match among multiple fonts in the same font family. @return an array ofStringcontaining names of font families.@see #getAllFonts @see java.awt.Font @see java.awt.Font#getFamily @since 1.2
Returns an array containing the localized names of all font families available in thisClass GraphicsEnvironment, GraphicsDevice getDefaultScreenDevice()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
Fontinstance used to render text but allows theFontobject more flexibility in choosing its own best match among multiple fonts in the same font family. Iflisnullthis 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 ofStringobjects containing names of font families specific to the specifiedLocale.@see #getAllFonts @see java.awt.Font @see java.awt.Font#getFamily @since 1.2
Returns the default screenClass GraphicsEnvironment, GraphicsDevice[] getScreenDevices()GraphicsDevice. @return theGraphicsDevicethat represents the default screen device. @exception HeadlessException if isHeadless() returns true @see isHeadless
Returns an array of all of the screenGraphicsDeviceobjects. @return an array containing all theGraphicsDeviceobjects that represent screen devices. @exception HeadlessException if isHeadless() returns true @see isHeadless
TheClass GridBagConstraints, int RELATIVEGridBagConstraintsclass specifies constraints for components that are laid out using theGridBagLayoutclass. @version 1.26 0229 12/0203/0001 @author Doug Stein @see java.awt.GridBagLayout @since JDK1.0
Class GridBagConstraints, int REMAINDERSpecifySpecifies that this component is the next-to-last component in its column or row (gridwidthgridheight) or that this component be placed next to the previously added component (gridxgridy). @see java.awt.GridBagConstraints#gridwidth @see java.awt.GridBagConstraints#gridheight @see java.awt.GridBagConstraints#gridx @see java.awt.GridBagConstraints#gridy
Class GridBagConstraints, int anchorSpecifySpecifies that this component is the last component in its column or row.
This field is used when the component is smaller than its display area. It determines where within the display area to place the component.Class GridBagConstraints, int gridheightPossibleThere are two kinds of possible values: relative and absolute. Relative values are interpreted relative to the container's component orientation property while absolute values are not. The absolute values are:
CENTERNORTHNORTHEASTEASTSOUTHEASTSOUTHSOUTHWESTWESTandNORTHWEST. The relative values are:PAGE_STARTPAGE_ENDLINE_STARTLINE_ENDFIRST_LINE_STARTFIRST_LINE_ENDLAST_LINE_STARTandLAST_LINE_END. The default value isCENTER. @serial @see #clone() @see java.awt.ComponentOrientation
Specifies the number of cells in a column for the component's display area.Class GridBagConstraints, int gridwidthUse
REMAINDERto specify that the component be the last one in its column. UseRELATIVEto specify that the component be the next-to-last one in its column.
gridheightshould 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
REMAINDERto specify that the component be the last one in its row. UseRELATIVEto specify that the component be the next-to-last one in its row.
gridwidthshould be non-negative and the default value is 1. @serial @see #clone() @see java.awt.GridBagConstraints#gridheight
Specifies the cellClass GridBagConstraints, int gridyatcontaining theleftleading edge of the component's display area where theleftmostfirst cell in a row hasgridx=0. The leading edge of a component's display area is its left edge for a horizontal left-to-right container and its right edge for a horizontal right-to-left container. The valueRELATIVEspecifies that the component be placedjust to the rightimmediatelyoffollowing the component that was added to the container just before this component was added.The default value is
RELATIVE.gridxshould be a non-negative value. @serial @see #clone() @see java.awt.GridBagConstraints#gridy @see java.awt.ComponentOrientation
Specifies the cell at the top of the component's display area where the topmost cell hasClass GridBagConstraints, double weightxgridy=0. The valueRELATIVEspecifies 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.gridyshould be a non-negative value. @serial @see #clone() @see java.awt.GridBagConstraints#gridx
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
weightxof all the components in a column. 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.weightxshould 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
weightyof 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.If 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.weightyshould be a non-negative value. @serial @see #clone() @see java.awt.GridBagConstraints#weightx
TheClass GridBagLayout, GridBagLayoutInfo GetLayoutInfo(Container, int)GridBagLayoutclass is a flexible layout manager that aligns components vertically and horizontally without requiring that the components be of the same size. EachGridBagLayoutobject maintains a dynamic rectangular grid of cells with each component occupying one or more cells called its display area.Each component managed by a
grid bag layoutGridBagLayoutis associated with an instance of GridBagConstraintsthatThe constraints object specifies where a component's display area should be located on the grid and how the componentis laid outshould be positioned within its display area. InHowadditionato its constraints object theGridBagLayoutobjectalso considers each component's minimum and preferred sizes in order toplacesdetermine asetcomponent's size.The overall
orientation ofcomponentsthe grid depends on theGridBagConstraintscontainer'sobjectComponentOrientationassociatedproperty.with eachFor horizontalcomponentleft-to-rightand onorientations grid coordinate (0 0) is in theminimum sizeupper left corner of the container with x increasing to the right and y increasing downward. For horizontal right-to-left orientations grid coordinate (0 0) is in thepreferreduppersizeright corner of thecomponents'container with x increasing to the left andcontainersy increasing downward.To use a grid bag layout effectively you must customize one or more of the
GridBagConstraintsobjects that are associated with its components. You customize aGridBagConstraintsobject by setting one or more of its instance variables:
- {@link GridBagConstraints#gridx} GridBagConstraints#gridy
- Specifies the cell
atcontaining theupperleadingleftcorner of the component's display area where theupper-left-mostcell at the origin of the grid has addressgridx = 0gridy = 0. For horizontal left-to-right layout a component's leading corner is its upper left. For horizontal right-to-left layout a component's leading corner is its upper right. UseGridBagConstraints.RELATIVE(the default value) to specify that the component bejustplacedjustimmediatelytofollowing (along theright ofx axis(forgridx)orjust belowthe y(axis forgridy) the component that was added to the container just before this component was added.- {@link GridBagConstraints#gridwidth} GridBagConstraints#gridheight
- Specifies the number of cells in a row (for
gridwidth) or column (forgridheight) in the component's display area. The default value is 1. UseGridBagConstraints.REMAINDERto specify that the component be the last one in its row (forgridwidth) or column (forgridheight). UseGridBagConstraints.RELATIVEto specify that the component be the next to last one in its row (forgridwidth) or column (forgridheight).- {@link GridBagConstraints#fill}
- Used when the component's display area is larger than the component's requested size to determine whether (and how) to resize the component. Possible values are
GridBagConstraints.NONE(the default)GridBagConstraints.HORIZONTAL(make the component wide enough to fill its display area horizontally but don't change its height)GridBagConstraints.VERTICAL(make the component tall enough to fill its display area vertically but don't change its width) andGridBagConstraints.BOTH(make the component fill its display area entirely).- {@link GridBagConstraints#ipadx} GridBagConstraints#ipady
- Specifies the component's internal padding within the layout how much to add to the minimum size of the component. The width of the component will be at least its minimum width plus
(ipadx * 2)pixels (since the padding applies to both sides of the component). Similarly the height of the component will be at least the minimum height plus(ipady * 2)pixels.- {@link GridBagConstraints#insets}
- Specifies the component's external padding the minimum amount of space between the component and the edges of its display area.
- {@link GridBagConstraints#anchor}
- Used when the component is smaller than its display area to determine where (within the display area) to place the component. There are two kinds of possible values: relative and absolute. Relative values are interpreted relative to the container's
ComponentOrientationproperty while absolute values are not. Valid values are:
Absolute Values Relative Values GridBagConstraints.NORTHGridBagConstraints.SOUTHGridBagConstraints.WESTGridBagConstraints.EASTGridBagConstraints.NORTHWESTGridBagConstraints.NORTHEASTGridBagConstraints.SOUTHWESTGridBagConstraints.SOUTHEASTGridBagConstraints.CENTER(the default)GridBagConstraints.NORTHPAGE_STARTGridBagConstraints.NORTHEASTPAGE_ENDGridBagConstraints.EASTLINE_STARTGridBagConstraints.SOUTHEASTLINE_ENDGridBagConstraints.SOUTHFIRST_LINE_STARTGridBagConstraints.SOUTHWESTFIRST_LINE_ENDGridBagConstraints.WESTLAST_LINE_STARTandGridBagConstraints.NORTHWESTLAST_LINE_END.
- {@link GridBagConstraints#weightx} GridBagConstraints#weighty
- Used to determine how to distribute space which is important for specifying resizing behavior. Unless you specify a weight for at least one component in a row (
weightx) and column (weighty) all the components clump together in the center of their container. This is because when the weight is zero (the default) theGridBagLayoutobject puts any extra space between its grid of cells and the edges of the container.The following
figure showsfigures show ten components (all buttons) managed by a grid bag layout:. Figure 1 shows the layout for a horizontal left-to-right container and Figure 2 shows the layout for a horizontal right-to-left container.
![]()
![]()
Figure 1: Horizontal Left-to-Right Figure 2: Horizontal Right-to-Left Each of the ten components has the
fillfield of its associatedGridBagConstraintsobject set toGridBagConstraints.BOTH. In addition the components have the following non-default constraints:
- Button1 Button2 Button3:
weightx = 1.0- Button4:
weightx = 1.0gridwidth = GridBagConstraints.REMAINDER- Button5:
gridwidth = GridBagConstraints.REMAINDER- Button6:
gridwidth = GridBagConstraints.RELATIVE- Button7:
gridwidth = GridBagConstraints.REMAINDER- Button8:
gridheight = 2weighty = 1.0- Button9 Button 10:
gridwidth = GridBagConstraints.REMAINDERHere is the code that implements the example shown above:
import java.awt.*; import java.util.*; import java.applet.Applet; public class GridBagEx1 extends Applet { protected void makebutton(String name GridBagLayout gridbag GridBagConstraints c) { Button button = new Button(name); gridbag.setConstraints(button c); add(button); } public void init() { GridBagLayout gridbag = new GridBagLayout(); GridBagConstraints c = new GridBagConstraints(); setFont(new Font("Helvetica" Font.PLAIN 14)); setLayout(gridbag); c.fill = GridBagConstraints.BOTH; c.weightx = 1.0; makebutton("Button1" gridbag c); makebutton("Button2" gridbag c); makebutton("Button3" gridbag c); c.gridwidth = GridBagConstraints.REMAINDER; //end row makebutton("Button4" gridbag c); c.weightx = 0.0; //reset to the default makebutton("Button5" gridbag c); //another row c.gridwidth = GridBagConstraints.RELATIVE; //next-to-last in row makebutton("Button6" gridbag c); c.gridwidth = GridBagConstraints.REMAINDER; //end row makebutton("Button7" gridbag c); c.gridwidth = 1; //reset to the default c.gridheight = 2; c.weighty = 1.0; makebutton("Button8" gridbag c); c.weighty = 0.0; //reset to the default c.gridwidth = GridBagConstraints.REMAINDER; //end row c.gridheight = 1; //reset to the default makebutton("Button9" gridbag c); makebutton("Button10" gridbag c); setSize(300 100); } public static void main(String args[]) { Frame f = new Frame("GridBag Layout Example"); GridBagEx1 ex1 = new GridBagEx1(); ex1.init(); f.add("Center" ex1); f.pack(); f.setSize(f.getPreferredSize()); f.show(); } }
@version 1.5 16 Nov 1995 @author Doug Stein @see java.awt.GridBagConstraints @see java.awt.ComponentOrientation @since JDK1.0
Class GridBagLayout, void addLayoutComponent(Component, Object)Print the layoutThis method isconstraints. Usefulsupplied fordebuggingbackwards compatability only; new code should call getLayoutInfo() instead. @see getLayoutInfo
Adds the specified component to the layout using the specifiedClass GridBagLayout, void addLayoutComponent(String, Component)constraintconstraintsobject. Note that constraints are mutable and are therefore cloned when cached. @param comp the component to be added.@param constraints an object that determines how the component is added to the layout.@exception IllegalArgumentException ifconstraintsis not aGridBagConstraint
Adds the specified component with the specified name to the layout. @param name the name of the componentClass GridBagLayout, GridBagConstraints getConstraints(Component).@param comp the component to be added.
Gets the constraints for the specified component. A copy of the actualClass GridBagLayout, int[][] getLayoutDimensions()GridBagConstraintsobject is returned. @param comp the component to be queried.@return the constraint for the specified component in this grid bag layout; a copy of the actual constraint object is returned.
Determines column widths and row heights for the layout grid.Class GridBagLayout, Point getLayoutOrigin()Most applications do not call this method directly. @return an array of two arrays containing the widths of the layout columns and the heights of the layout rows
.@since JDK1.1
Determines the origin of the layout area in the graphics coordinate space of the target container. This value represents the pixel coordinates of the top-left corner of the layout area regardless of the ComponentOrientation value of the container. This is distinct from the grid origin given by the cell coordinates (0 0). Most applications do not call this method directly. @return the graphics origin of the cell in the top-left corner of the layout grid @see java.awt.ComponentOrientation @since JDK1.1
Class GridBagLayout, double[][] getLayoutWeights()Determines the weights of the layout grid's columns and rows. Weights are used to calculate how much a given column or row stretches beyond its preferred size if the layout has extra room to fill.Class GridBagLayout, Point location(int, int)Most applications do not call this method directly. @return an array of two arrays representing the horizontal weights of the layout columns and the vertical weights of the layout rows
.@since JDK1.1
Determines which cell in the layout grid contains the point specified byClass GridBagLayout, GridBagConstraints lookupConstraints(Component)(x y). Each cell is identified by its column index (ranging from 0 to the number of columns minus 1) and its row index (ranging from 0 to the number of rows minus 1).If the
(x y)point lies outside the grid the following rules are used. The column index is returned as zero ifxlies to the left of the layoutandfor a left-to-right container or to the right of the layout for a right-to-left container. The column index is returned as the number of columns ifxlies to the right of the layout in a left-to-right container or to the left in a right-to-left container. The row index is returned as zero ifylies above the layout and as the number of rows ifylies below the layout. The orientation of a container is determined by itsComponentOrientationproperty. @param x the x coordinate of a point.@param y the y coordinate of a point.@return an ordered pair of indexes that indicate which cell in the layout grid contains the point (x y). @see java.awt.ComponentOrientation @since JDK1.1
Retrieves the constraints for the specified component. The return value is not a copy but is the actualClass GridBagLayout, void setConstraints(Component, GridBagConstraints)GridBagConstraintsobject used by the layout mechanism. @param comp the component to be queried @return the contraints for the specifiedcomponentcomponen.
Sets the constraints for the specified component in this layout. @param comp the component to be modifiedClass GridBagLayout, double[] columnWeights.@param constraints the constraints to be applied.
This field holds the overrides to the column weights. If this field is non-Class GridBagLayout, int[] columnWidthsnullthe values are applied to the gridbag after all of the columns weights have been calculated. IfcolumnWeights[i]> weight for column i then column i is assigned the weight incolumnWeights[i]. IfcolumnWeightshas more elements than the number of columns the excess elements are ignored - they do not cause more columns to be created. @serial
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, Hashtable comptableThis hashtable maintains the association between a component and its gridbag constraints. The Keys in comptable are the components and the values are the instances of GridBagConstraints. @serial @see java.awt.GridBagConstraints
Class GridBagLayout, GridBagLayoutInfo layoutInfoThis field holdsClass GridBagLayout, int[] rowHeightsthathe layout information for the gridbag. The information in this field is based on the most recent validation of the gridbag. IflayoutInfoisnullthis indicates that there are no components in the gridbag or if there are components they have not yet been validated. @serial @see #GetLayoutInfogetLayoutInfo(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. IfClass GridBagLayrowHeightshas more elements than the number of rows rowa are added to the gridbag to match the number of elements inrowHeights. @serial @see #getLayoutDimensions()