AWT Quick Guide

Advertisements


Graphical User Interface

Graphical User Interface (GUI) offers user interaction via some graphical components. For example our underlying Operating System also offers GUI via window,frame,Panel, Button, Textfield, TextArea, Listbox, Combobox, Label, Checkbox etc. These all are known as components. Using these components we can create an interactive user interface for an application.

GUI provides result to end user in response to raised events.GUI is entirely based events. For example clicking over a button, closing a window, opening a window, typing something in a textarea etc. These activities are known as events.GUI makes it easier for the end user to use an application. It also makes them interesting.

Basic Terminologies

TermDescription
ComponentComponent is an object having a graphical representation that can be displayed on the screen and that can interact with the user. For examples buttons, checkboxes, list and scrollbars of a graphical user interface.
ContainerContainer object is a component that can contain other 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.
PanelPanel provides space in which an application can attach any other components, including other panels.
WindowWindow is a rectangular area which is displayed on the screen. In different window we can execute different program and display different data. Window provide us with multitasking environment. A window must have either a frame, dialog, or another window defined as its owner when it's constructed.
FrameA Frame is a top-level window with a title and a border. The size of the frame includes any area designated for the border. Frame encapsulates window. It and has a title bar, menu bar, borders, and resizing corners.
CanvasCanvas component represents a blank rectangular area of the screen onto which the application can draw. Application can also trap input events from the use from that blank area of Canvas component.

Examples of GUI based Applications

Following are some of the examples for GUI based applications.

  • Automated Teller Machine (ATM)

  • Airline Ticketing System

  • Information Kiosks at railway stations

  • Mobile Applications

  • Navigation Systems

Advantages of GUI over CUI

  • GUI provides graphical icons to interact while the CUI (Character User Interface) offers the simple text-based interfaces.

  • GUI makes the application more entertaining and interesting on the other hand CUI does not.

  • GUI offers click and execute environment while in CUI every time we have to enter the command for a task.

  • New user can easily interact with graphical user interface by the visual indicators but it is difficult in Character user interface.

  • GUI offers a lot of controls of file system and the operating system while in CUI you have to use commands which is difficult to remember.

  • Windows concept in GUI allow the user to view, manipulate and control the multiple applications at once while in CUI user can control one task at a time.

  • GUI provides multitasking environment so as the CUI also does but CUI does not provide same ease as the GUI do.

  • Using GUI it is easier to control and navigate the operating system which becomes very slow in command user interface. GUI can be easily customized.

Environment Setup

This section guides you on how to download and set up Java on your machine. Please follow the following steps to set up the environment.

Java SE is freely available from the link Download Java. So you download a version based on your operating system.

Follow the instructions to download java and run the .exe to install Java on your machine. Once you installed Java on your machine, you would need to set environment variables to point to correct installation directories:

Setting up the path for windows 2000/XP:

Assuming you have installed Java in c:\Program Files\java\jdk directory:

  • Right-click on 'My Computer' and select 'Properties'.

  • Click on the 'Environment variables' button under the 'Advanced' tab.

  • Now alter the 'Path' variable so that it also contains the path to the Java executable. Example, if the path is currently set to 'C:\WINDOWS\SYSTEM32', then change your path to read 'C:\WINDOWS\SYSTEM32;c:\Program Files\java\jdk\bin'.

Setting up the path for windows 95/98/ME:

Assuming you have installed Java in c:\Program Files\java\jdk directory:

  • Edit the 'C:\autoexec.bat' file and add the following line at the end:
    'SET PATH=%PATH%;C:\Program Files\java\jdk\bin'

Setting up the path for Linux, UNIX, Solaris, FreeBSD:

Environment variable PATH should be set to point to where the java binaries have been installed. Refer to your shell documentation if you have trouble doing this.

Example, if you use bash as your shell, then you would add the following line to the end of your '.bashrc: export PATH=/path/to/java:$PATH'

Popular Java Editors:

To write your java programs you will need a text editor. There are even more sophisticated IDE available in the market. But for now, you can consider one of the following:

  • Notepad : On Windows machine you can use any simple text editor like Notepad (Recommended for this tutorial), TextPad.

  • Netbeans :is a Java IDE that is open source and free which can be downloaded from http://www.netbeans.org/index.html.

  • Eclipse : is also a java IDE developed by the eclipse open source community and can be downloaded from http://www.eclipse.org/.

AWT Controls

Every user interface considers the following three main aspects:

  • UI elements : Thes are the core visual elements the user eventually sees and interacts with. GWT provides a huge list of widely used and common elements varying from basic to complex which we will cover in this tutorial.

  • Layouts: They define how UI elements should be organized on the screen and provide a final look and feel to the GUI (Graphical User Interface). This part will be covered in Layout chapter.

  • Behavior: These are events which occur when the user interacts with UI elements. This part will be covered in Event Handling chapter.

UI classes

Every AWT controls inherits properties from Component class.

AWT Component Class

Introduction

The class Component is the abstract base class for the non menu user-interface controls of AWT. Component represents an object with graphical representation.

Class declaration

Following is the declaration for java.awt.Component class:

public abstract class Component
   extends Object
      implements ImageObserver, MenuContainer, Serializable

Field

Following are the fields for java.awt.Component class:

  • static float BOTTOM_ALIGNMENT -- Ease-of-use constant for getAlignmentY.

  • static float CENTER_ALIGNMENT -- Ease-of-use constant for getAlignmentY and getAlignmentX.

  • static float LEFT_ALIGNMENT -- Ease-of-use constant for getAlignmentX.

  • static float RIGHT_ALIGNMENT -- Ease-of-use constant for getAlignmentX.

  • static float TOP_ALIGNMENT -- Ease-of-use constant for getAlignmentY().

Class constructors

S.N.Constructor & Description
1protected Component()
This creates a new Component.

Class methods

S.N.Method & Description
1boolean action(Event evt, Object what)
Deprecated. As of JDK version 1.1, should register this component as ActionListener on component which fires action events.
2void add(PopupMenu popup)
Adds the specified popup menu to the component.
3void addComponentListener(ComponentListener l)
Adds the specified component listener to receive component events from this component.
4void addFocusListener(FocusListener l)
Adds the specified focus listener to receive focus events from this component when this component gains input focus.
5void addHierarchyBoundsListener(HierarchyBoundsListener l)
Adds the specified hierarchy bounds listener to receive hierarchy bounds events from this component when the hierarchy to which this container belongs changes.
6void addHierarchyListener(HierarchyListener l)
Adds the specified hierarchy listener to receive hierarchy changed events from this component when the hierarchy to which this container belongs changes.
7void addInputMethodListener(InputMethodListener l)
Adds the specified input method listener to receive input method events from this component.
8void addKeyListener(KeyListener l)
Adds the specified key listener to receive key events from this component.
9void addMouseListener(MouseListener l)
Adds the specified mouse listener to receive mouse events from this component.
10void addMouseMotionListener(MouseMotionListener l)
Adds the specified mouse motion listener to receive mouse motion events from this component.
11void addMouseWheelListener(MouseWheelListener l)
Adds the specified mouse wheel listener to receive mouse wheel events from this component.
12void addNotify()
Makes this Component displayable by connecting it to a native screen resource.
13void addPropertyChangeListener(PropertyChangeListener listener)
Adds a PropertyChangeListener to the listener list.
14void addPropertyChangeListener(String propertyName, PropertyChangeListener listener)
Adds a PropertyChangeListener to the listener list for a specific property.
15void applyComponentOrientation(ComponentOrientation orientation)
Sets the ComponentOrientation property of this component and all components contained within it.
16boolean areFocusTraversalKeysSet(int id)
Returns whether the Set of focus traversal keys for the given focus traversal operation has been explicitly defined for this Component.
17int checkImage(Image image, ImageObserver observer)
Returns the status of the construction of a screen representation of the specified image.
18int checkImage(Image image,int width,int height, ImageObserver observer)
Returns the status of the construction of a screen representation of the specified image.
19boolean contains(int x,int y)
Checks whether this component "contains" the specified point, where x and y are defined to be relative to the coordinate system of this component.
20boolean contains(Point p)
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.
21Image createImage(ImageProducer producer)
Creates an image from the specified image producer.
22Image createImage(int width,int height)
Creates an off-screen drawable image to be used for double buffering.
23VolatileImage createVolatileImage(int width,int height)
Creates a volatile off-screen drawable image to be used for double buffering.
24VolatileImage createVolatileImage(int width,int height, ImageCapabilities caps)
Creates a volatile off-screen drawable image, with the given capabilities.
25void deliverEvent(Event e)
Deprecated. As of JDK version 1.1, replaced by dispatchEvent(AWTEvent e).
26void disable()
Deprecated. As of JDK version 1.1, replaced by setEnabled(boolean).
27protected void disableEvents(long eventsToDisable)
Disables the events defined by the specified event mask parameter from being delivered to this component.
28void dispatchEvent(AWTEvent e)
Dispatches an event to this component or one of its sub components.
29void doLayout()
Prompts the layout manager to lay out this component.
30void enable()
Deprecated. As of JDK version 1.1, replaced by setEnabled(boolean).
31void enable(boolean b)
Deprecated. As of JDK version 1.1, replaced by setEnabled(boolean).
32protected void enableEvents(long eventsToEnable)
Enables the events defined by the specified event mask parameter to be delivered to this component.
33void enableInputMethods(boolean enable)
Enables or disables input method support for this component.
34protected void firePropertyChange(String propertyName, boolean oldValue, boolean newValue)
Support for reporting bound property changes for boolean properties.
35void firePropertyChange(String propertyName, byte oldValue, byte newValue)
Reports a bound property change.
36void firePropertyChange(String propertyName, char oldValue, char newValue)
Reports a bound property change.
37void firePropertyChange(String propertyName, double oldValue, double newValue)
Reports a bound property change.
38void firePropertyChange(String propertyName, float oldValue, float newValue)
Reports a bound property change.
39void firePropertyChange(String propertyName, long oldValue, long newValue)
Reports a bound property change.
40protected void firePropertyChange(String propertyName, Object oldValue, Object newValue)
Support for reporting bound property changes for Object properties.
41void firePropertyChange(String propertyName, short oldValue, short newValue)
Reports a bound property change.
42AccessibleContext getAccessibleContext()
Gets the AccessibleContext associated with this Component.
43float getAlignmentX()
Returns the alignment along the x axis.
44float getAlignmentY()
Returns the alignment along the y axis.
45Color getBackground()
Gets the background color of this component.
46int getBaseline(int width,int height)
Returns the baseline.
47Component.BaselineResizeBehavior getBaselineResizeBehavior()
Returns an enum indicating how the baseline of the component changes as the size changes.
48Rectangle getBounds()
Gets the bounds of this component in the form of a Rectangle object.
49Rectangle getBounds(Rectangle rv)
Stores the bounds of this component into return value rv and return rv.
50ColorModel getColorModel()
Gets the instance of ColorModel used to display the component on the output device.
51Component getComponentAt(int x,int y)
Determines if this component or one of its immediate subcomponents contains the (x, y) location, and if so, returns the containing component.
52Component getComponentAt(Point p)
Returns the component or subcomponent that contains the specified point.
53ComponentListener[] getComponentListeners()
Returns an array of all the component listeners registered on this component.
54ComponentOrientation getComponentOrientation()
Retrieves the language-sensitive orientation that is to be used to order the elements or text within this component.
55Cursor getCursor()
Gets the cursor set in the component.
56DropTarget getDropTarget()
Gets the DropTarget associated with this Component.
57Container getFocusCycleRootAncestor()
Returns the Container which is the focus cycle root of this Component's focus traversal cycle.
58FocusListener[] getFocusListeners()
Returns an array of all the focus listeners registered on this component.
59Set<AWTKeyStroke> getFocusTraversalKeys(int id)
Returns the Set of focus traversal keys for a given traversal operation for this Component.
60boolean getFocusTraversalKeysEnabled()
Returns whether focus traversal keys are enabled for this Component.
61Font getFont()
Gets the font of this component.
62FontMetrics getFontMetrics(Font font)
Gets the font metrics for the specified font.
63Color getForeground()
Gets the foreground color of this component.
64Graphics getGraphics()
Creates a graphics context for this component.
65GraphicsConfiguration getGraphicsConfiguration()
Gets the GraphicsConfiguration associated with this Component.
66int getHeight()
Returns the current height of this component.
67HierarchyBoundsListener[] getHierarchyBoundsListeners()
Returns an array of all the hierarchy bounds listeners registered on this component.
68HierarchyListener[] getHierarchyListeners()
Returns an array of all the hierarchy listeners registered on this component.
69boolean getIgnoreRepaint()
70InputContext getInputContext()
Gets the input context used by this component for handling the communication with input methods when text is entered in this component.
71InputMethodListener[] getInputMethodListeners()
Returns an array of all the input method listeners registered on this component.
72InputMethodRequests getInputMethodRequests()
Gets the input method request handler which supports requests from input methods for this component.
73KeyListener[] getKeyListeners()
Returns an array of all the key listeners registered on this component.
74<T extends EventListener> T[] getListeners(Class<T> listenerType)
Returns an array of all the objects currently registered as FooListeners upon this Component.
75Locale getLocale()
Gets the locale of this component.
76Point getLocation()
Gets the location of this component in the form of a point specifying the component's top-left corner.
77Point getLocation(Point rv)
Stores the x,y origin of this component into return value rv and return rv.
78Point getLocationOnScreen()
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.
79Dimension getMaximumSize()
Gets the maximum size of this component.
80Dimension getMinimumSize()
Gets the mininimum size of this component.
81MouseListener[] getMouseListeners()
Returns an array of all the mouse listeners registered on this component.
82MouseMotionListener[] getMouseMotionListeners()
Returns an array of all the mouse motion listeners registered on this component.
83Point getMousePosition()
Returns the position of the mouse pointer in this Component's coordinate space if the Component is directly under the mouse pointer, otherwise returns null.
84MouseWheelListener[] getMouseWheelListeners()
Returns an array of all the mouse wheel listeners registered on this component.
85String getName()
Gets the name of the component.
86Container getParent()
Gets the parent of this component.
87java.awt.peer.ComponentPeer getPeer() Deprecated. As of JDK version 1.1, programs should not directly manipulate peers; replaced by boolean isDisplayable().
88Dimension getPreferredSize()
Gets the preferred size of this component.
89PropertyChangeListener[] getPropertyChangeListeners()
Returns an array of all the property change listeners registered on this component.
90PropertyChangeListener[] getPropertyChangeListeners(String propertyName)
Returns an array of all the listeners which have been associated with the named property.
91Dimension getSize()
Returns the size of this component in the form of a Dimension object.
92Dimension getSize(Dimension rv)Stores the width/height of this component into return value rv and return rv.
93Toolkit getToolkit()
Gets the toolkit of this component.
94Object getTreeLock()
Gets this component's locking object (the object that owns the thread sychronization monitor)
for AWT component-tree and layout operations.
95int getWidth()
Returns the current width of this component.
96int getX()
Returns the current x coordinate of the components origin.
97int getY()
Returns the current y coordinate of the components origin.
98boolean gotFocus(Event evt, Object what)
Deprecated. As of JDK version 1.1, replaced by processFocusEvent(FocusEvent)
.
99boolean handleEvent(Event evt)
Deprecated. As of JDK version 1.1 replaced by processEvent(AWTEvent).
100boolean hasFocus()
Returns true if this Component is the focus owner.
101void hide()
Deprecated. As of JDK version 1.1, replaced by setVisible(boolean).
102boolean imageUpdate(Image img,int infoflags,int x,int y,int w,int h)
Repaints the component when the image has changed.
103boolean inside(int x,int y)
Deprecated. As of JDK version 1.1, replaced by contains(int, int).
104void invalidate()
Invalidates this component.
105boolean isBackgroundSet()
Returns whether the background color has been explicitly set for this Component.
106boolean isCursorSet()
Returns whether the cursor has been explicitly set for this Component.
107boolean isDisplayable()
Determines whether this component is displayable.
108boolean isDoubleBuffered()
Returns true if this component is painted to an offscreen image (buffer)
that's copied to the screen later.
109boolean isEnabled()
Determines whether this component is enabled.
110boolean isFocusable()
Returns whether this Component can be focused.
111boolean isFocusCycleRoot(Container container)
Returns whether the specified Container is the focus cycle root of this Component's focus traversal cycle.
112boolean isFocusOwner()
Returns true if this Component is the focus owner.
113boolean isFocusTraversable()
Deprecated. As of 1.4, replaced by isFocusable().
114boolean isFontSet()
Returns whether the font has been explicitly set for this Component.
115boolean isForegroundSet()
Returns whether the foreground color has been explicitly set for this Component.
116boolean isLightweight()
A lightweight component doesn't have a native toolkit peer.
117boolean isMaximumSizeSet()
Returns true if the maximum size has been set to a non-null value otherwise returns false.
118boolean isMinimumSizeSet()
Returns whether or not setMinimumSize has been invoked with a non-null value.
119boolean isOpaque()
Returns true if this component is completely opaque, returns false by default.
120boolean isPreferredSizeSet()
Returns true if the preferred size has been set to a non-null value otherwise returns false.
121boolean isShowing()
Determines whether this component is showing on screen.
122boolean isValid()
Determines whether this component is valid.
123boolean isVisible()
Determines whether this component should be visible when its parent is visible.
124boolean keyDown(Event evt,int key)
Deprecated. As of JDK version 1.1, replaced by processKeyEvent(KeyEvent).
125boolean keyUp(Event evt,int key)
Deprecated. As of JDK version 1.1, replaced by processKeyEvent(KeyEvent).
126void layout()
Deprecated. As of JDK version 1.1, replaced by doLayout().
127void list()
Prints a listing of this component to the standard system output stream System.out.
128void list(PrintStream out)
Prints a listing of this component to the specified output stream.
129void list(PrintStream out,int indent)
Prints out a list, starting at the specified indentation, to the specified print stream.
130void list(PrintWriter out)
Prints a listing to the specified print writer.
131void list(PrintWriter out,int indent)
Prints out a list, starting at the specified indentation, to the specified print writer.
132Component locate(int x,int y)
Deprecated. As of JDK version 1.1, replaced by getComponentAt(int, int).
133Point location()
Deprecated. As of JDK version 1.1, replaced by getLocation().
134boolean lostFocus(Event evt, Object what)
Deprecated. As of JDK version 1.1, replaced by processFocusEvent(FocusEvent).
135boolean mouseDown(Event evt,int x,int y)
Deprecated. As of JDK version 1.1, replaced by processMouseEvent(MouseEvent).
136boolean mouseDrag(Event evt,int x,int y)
Deprecated. As of JDK version 1.1, replaced by processMouseMotionEvent(MouseEvent).
137boolean mouseEnter(Event evt,int x,int y)
Deprecated. As of JDK version 1.1, replaced by processMouseEvent(MouseEvent).
138boolean mouseExit(Event evt,int x,int y)
Deprecated. As of JDK version 1.1, replaced by processMouseEvent(MouseEvent)..
139boolean mouseMove(Event evt,int x,int y)
Deprecated. As of JDK version 1.1, replaced by processMouseMotionEvent(MouseEvent)..
140boolean mouseUp(Event evt,int x,int y)
Deprecated. As of JDK version 1.1, replaced by processMouseEvent(MouseEvent).
141void move(int x,int y)
Deprecated. As of JDK version 1.1, replaced by setLocation(int, int).
142void nextFocus()
Deprecated. As of JDK version 1.1, replaced by transferFocus().
143void paint(Graphics g)
Paints this component.
144void paintAll(Graphics g)
Paints this component and all of its subcomponents.
145boolean postEvent(Event e)
Deprecated. As of JDK version 1.1, replaced by dispatchEvent(AWTEvent).
146boolean prepareImage(Image image,int width,int height, ImageObserver observer)
Prepares an image for rendering on this component at the specified width and height.
147void print(Graphics g)
Prints this component.
148void printAll(Graphics g)
Prints this component and all of its subcomponents.
149protectedvoid processComponentEvent(ComponentEvent e)
Processes component events occurring on this component by dispatching them to any registered ComponentListener objects.
150protected void processEvent(AWTEvent e)
Processes events occurring on this component.
151protected void processFocusEvent(FocusEvent e)
Processes focus events occurring on this component by dispatching them to any registered FocusListener objects.
152protected void processHierarchyBoundsEvent(HierarchyEvent e)
Processes hierarchy bounds events occurring on this component by dispatching them to any registered HierarchyBoundsListener objects.
153protected void processHierarchyEvent(HierarchyEvent e)
Processes hierarchy events occurring on this component by dispatching them to any registered HierarchyListener objects.
154protectedvoid processInputMethodEvent(InputMethodEvent e)
Processes input method events occurring on this component by dispatching them to any registered InputMethodListener objects.
155protected void processKeyEvent(KeyEvent e)
Processes key events occurring on this component by dispatching them to any registered KeyListener objects.
156protected void processMouseEvent(MouseEvent e)
Processes mouse events occurring on this component by dispatching them to any registered MouseListener objects.
157protected void processMouseMotionEvent(MouseEvent e)
Processes mouse motion events occurring on this component by dispatching them to any registered MouseMotionListener objects.
158protected void processMouseWheelEvent(MouseWheelEvent e)
Processes mouse wheel events occurring on this component by dispatching them to any registered MouseWheelListener objects.
159void remove(MenuComponent popup)
Removes the specified popup menu from the component.
160void removeComponentListener(ComponentListener l)
Removes the specified component listener so that it no longer receives component events from this component.
161void removeFocusListener(FocusListener l)
Removes the specified focus listener so that it no longer receives focus events from this component.
162void removeHierarchyBoundsListener(HierarchyBoundsListener l)
Removes the specified hierarchy bounds listener so that it no longer receives hierarchy bounds events from this component.
163void removeHierarchyListener(HierarchyListener l)
Removes the specified hierarchy listener so that it no longer receives hierarchy changed events from this component.
164void removeInputMethodListener(InputMethodListener l)
Removes the specified input method listener so that it no longer receives input method events from this component.
165void removeKeyListener(KeyListener l)
Removes the specified key listener so that it no longer receives key events from this component.
166void removeMouseListener(MouseListener l)
Removes the specified mouse listener so that it no longer receives mouse events from this component.
167void removeMouseMotionListener(MouseMotionListener l)
Removes the specified mouse motion listener so that it no longer receives mouse motion events from this component.
168void removeMouseWheelListener(MouseWheelListener l)
Removes the specified mouse wheel listener so that it no longer receives mouse wheel events from this component.
169void removeNotify()
Makes this Component undisplayable by destroying it native screen resource.
170void removePropertyChangeListener(PropertyChangeListener listener)
Removes a PropertyChangeListener from the listener list.
171void removePropertyChangeListener(String propertyName, PropertyChangeListener listener)
Removes a PropertyChangeListener from the listener list for a specific property.
172void repaint()
Repaints this component.
173void repaint(int x,int y,int width,int height)
Repaints the specified rectangle of this component.
174void repaint(long tm)
Repaints the component.
175void repaint(long tm,int x,int y,int width,int height)
Repaints the specified rectangle of this component within tm milliseconds.
176void requestFocus()
Requests that this Component get the input focus, and that this Component's top-level ancestor become the focused Window.
177protected boolean requestFocus(boolean temporary)
Requests that this Component get the input focus, and that this Component's top-level ancestor become the focused Window.
178boolean requestFocusInWindow()
Requests that this Component get the input focus, if this Component's top-level ancestor is already the focused Window.
179protected boolean requestFocusInWindow(boolean temporary)
Requests that this Component get the input focus, if this Component's top-level ancestor is already the focused Window.
180void reshape(int x,int y,int width,int height)
Deprecated. As of JDK version 1.1, replaced by setBounds(int, int, int, int).
181void resize(Dimension d)
Deprecated. As of JDK version 1.1, replaced by setSize(Dimension).
182void resize(int width,int height)
Deprecated. As of JDK version 1.1, replaced by setSize(int, int).
183void setBackground(Color c)
Sets the background color of this component.
184void setBounds(int x,int y,int width,int height)
Moves and resizes this component.
185void setBounds(Rectangle r)
Moves and resizes this component to conform to the new bounding rectangle r.
186void setComponentOrientation(ComponentOrientation o)
Sets the language-sensitive orientation that is to be used to order the elements or text within this component.
187void setCursor(Cursor cursor)
Sets the cursor image to the specified cursor.
188void setDropTarget(DropTarget dt)
Associate a DropTarget with this component.
189void setEnabled(boolean b)
Enables or disables this component, depending on the value of the parameter b.
190void setFocusable(boolean focusable)
Sets the focusable state of this Component to the specified value.
191void setFocusTraversalKeys(int id, Set<? extends AWTKeyStroke> keystrokes)
Sets the focus traversal keys for a given traversal operation for this Component.
192void setFocusTraversalKeysEnabled(boolean focusTraversalKeysEnabled)
Sets whether focus traversal keys are enabled for this Component.
193void setFont(Font f)
Sets the font of this component.
194void setForeground(Color c)
Sets the foreground color of this component.
195void setIgnoreRepaint(boolean ignoreRepaint)
Sets whether or not paint messages received from the operating system should be ignored.
196void setLocale(Locale l)
Sets the locale of this component.
197void setLocation(int x,int y)
Moves this component to a new location.
198void setLocation(Point p)
Moves this component to a new location.
199void setMaximumSize(Dimension maximumSize)
Sets the maximum size of this component to a constant value.
200void setMinimumSize(Dimension minimumSize)
Sets the minimum size of this component to a constant value.
201void setName(String name)
Sets the name of the component to the specified string.
202void setPreferredSize(Dimension preferredSize)
Sets the preferred size of this component to a constant value.
203void setSize(Dimension d)
Resizes this component so that it has width d.width and height d.height.
204void setSize(int width,int height)
Resizes this component so that it has width width and height height.
205void setVisible(boolean b)
Shows or hides this component depending on the value of parameter b.
206void show()
Deprecated. As of JDK version 1.1, replaced by setVisible(boolean).
207void show(boolean b)
Deprecated. As of JDK version 1.1, replaced by setVisible(boolean).
208Dimension size()
Deprecated. As of JDK version 1.1, replaced by getSize().
209String toString()
Returns a string representation of this component and its values.
210void transferFocus()
Transfers the focus to the next component, as though this Component were the focus owner.
211void transferFocusBackward()
Transfers the focus to the previous component, as though this Component were the focus owner.
212void transferFocusUpCycle()
Transfers the focus up one focus traversal cycle.
213void update(Graphics g)
Updates this component.
214void validate()
Ensures that this component has a valid layout.
215Rectangle bounds()
Deprecated. As of JDK version 1.1, replaced by getBounds().
216protected AWTEvent coalesceEvents(AWTEvent existingEvent, AWTEvent newEvent)
Potentially coalesce an event being posted with an existing event.
217protected String paramString()
Returns a string representing the state of this component.
218protected void firePropertyChange(String propertyName,int oldValue,int newValue)
Support for reporting bound property changes for integer properties.
219Dimension preferredSize()
Deprecated. As of JDK version 1.1, replaced by getPreferredSize().
220boolean prepareImage(Image image, ImageObserver observer)
Prepares an image for rendering on this component.
221Dimension minimumSize()
Deprecated. As of JDK version 1.1, replaced by getMinimumSize().

Methods inherited

This class inherits methods from the following classes:

  • java.lang.Object

AWT Label Class

Introduction

Label is a passive control because it does not create any event when accessed by the user. The label control is an object of Label. A label displays a single line of read-only text. However the text can be changed by the application programmer but cannot be changed by the end user in any way.

Class declaration

Following is the declaration for java.awt.Label class:

public class Label
   extends Component
      implements Accessible

Field

Following are the fields for java.awt.Component class:

  • static int CENTER -- Indicates that the label should be centered.

  • static int LEFT -- Indicates that the label should be left justified.

  • static int RIGHT -- Indicates that the label should be right justified.

Class constructors

S.N.Constructor & Description
1Label()
Constructs an empty label.
2Label(String text)
Constructs a new label with the specified string of text, left justified.
3Label(String text, int alignment)
Constructs a new label that presents the specified string of text with the specified alignment.

Class methods

S.N.Method & Description
1void addNotify()
Creates the peer for this label.
2AccessibleContext getAccessibleContext()
Gets the AccessibleContext associated with this Label.
3int getAlignment()
Gets the current alignment of this label.
4String getText()
Gets the text of this label.
5protected String paramString()
Returns a string representing the state of this Label.
6void setAlignment(int alignment)
Sets the alignment for this label to the specified alignment.
7void setText(String text)
Sets the text for this label to the specified text.

Methods inherited

This class inherits methods from the following classes:

  • java.awt.Component

  • java.lang.Object

Label Example

Create the following java program using any editor of your choice in say D:/ > AWT > com > tutorialspoint > gui >

AwtControlDemo.java
package com.tutorialspoint.gui;

import java.awt.*;
import java.awt.event.*;

public class AwtControlDemo {

   private Frame mainFrame;
   private Label headerLabel;
   private Label statusLabel;
   private Panel controlPanel;

   public AwtControlDemo(){
      prepareGUI();
   }

   public static void main(String[] args){
      AwtControlDemo  awtControlDemo = new AwtControlDemo();
      awtControlDemo.showLabelDemo();
   }

   private void prepareGUI(){
      mainFrame = new Frame("Java AWT Examples");
      mainFrame.setSize(400,400);
      mainFrame.setLayout(new GridLayout(3, 1));
      mainFrame.addWindowListener(new WindowAdapter() {
         public void windowClosing(WindowEvent windowEvent){
            System.exit(0);
         }        
      });    
      headerLabel = new Label();
      headerLabel.setAlignment(Label.CENTER);
      statusLabel = new Label();        
      statusLabel.setAlignment(Label.CENTER);
      statusLabel.setSize(350,100);

      controlPanel = new Panel();
      controlPanel.setLayout(new FlowLayout());

      mainFrame.add(headerLabel);
      mainFrame.add(controlPanel);
      mainFrame.add(statusLabel);
      mainFrame.setVisible(true);  
   }

   private void showLabelDemo(){
      headerLabel.setText("Control in action: Label");      

      Label label = new Label();
      label.setText("Welcome to TutorialsPoint AWT Tutorial.");
      label.setAlignment(Label.CENTER);
      label.setBackground(Color.GRAY);
      label.setForeground(Color.WHITE);
      controlPanel.add(label);
   
      mainFrame.setVisible(true);  
   }
}

Compile the program using command prompt. Go to D:/ > AWT and type the following command.

D:\AWT>javac com\tutorialspoint\gui\AwtControlDemo.java

If no error comes that means compilation is successful. Run the program using following command.

D:\AWT>java com.tutorialspoint.gui.AwtControlDemo

Verify the following output

AWT Label

AWT Button Class

Introduction

Button is a control component that has a label and generates an event when pressed. When a button is pressed and released, AWT sends an instance of ActionEvent to the button, by calling processEvent on the button. The button's processEvent method receives all events for the button; it passes an action event along by calling its own processActionEvent method. The latter method passes the action event on to any action listeners that have registered an interest in action events generated by this button.

If an application wants to perform some action based on a button being pressed and released, it should implement ActionListener and register the new listener to receive events from this button, by calling the button's addActionListener method. The application can make use of the button's action command as a messaging protocol.

Class declaration

Following is the declaration for java.awt.Button class:

public class Button
   extends Component
      implements Accessible

Class constructors

S.N.Constructor & Description
1Button()
Constructs a button with an empty string for its label.
2Button(String text)
Constructs a new button with specified label.

Class methods

S.N.Method & Description
1void addActionListener(ActionListener l)
Adds the specified action listener to receive action events from this button.
2void addNotify()
Creates the peer of the button.
3AccessibleContext getAccessibleContext()
Gets the AccessibleContext associated with this Button.
4String getActionCommand()
Returns the command name of the action event fired by this button.
5ActionListener[] getActionListeners()
Returns an array of all the action listeners registered on this button.
6String getLabel()
Gets the label of this button.
7<T extends EventListener> T[] getListeners(Class<T> listenerType)
Returns an array of all the objects currently registered as FooListeners upon this Button.
8protected String paramString()
Returns a string representing the state of this Button.
9protected void processActionEvent(ActionEvent e)
Processes action events occurring on this button by dispatching them to any registered ActionListener objects.
10protected void processEvent(AWTEvent e)
Processes events on this button.
11void removeActionListener(ActionListener l)
Removes the specified action listener so that it no longer receives action events from this button.
12void setActionCommand(String command)
Sets the command name for the action event fired by this button.
13void setLabel(String label)
Sets the button's label to be the specified string.

Methods inherited

This class inherits methods from the following classes:

  • java.awt.Component

  • java.lang.Object

Button Example

Create the following java program using any editor of your choice in say D:/ > AWT > com > tutorialspoint > gui >

AwtControlDemo.java
package com.tutorialspoint.gui;

import java.awt.*;
import java.awt.event.*;

public class AwtControlDemo {

   private Frame mainFrame;
   private Label headerLabel;
   private Label statusLabel;
   private Panel controlPanel;

   public AwtControlDemo(){
      prepareGUI();
   }

   public static void main(String[] args){
      AwtControlDemo  awtControlDemo = new AwtControlDemo();
      awtControlDemo.showButtonDemo();
   }

   private void prepareGUI(){
      mainFrame = new Frame("Java AWT Examples");
      mainFrame.setSize(400,400);
      mainFrame.setLayout(new GridLayout(3, 1));
      mainFrame.addWindowListener(new WindowAdapter() {
         public void windowClosing(WindowEvent windowEvent){
            System.exit(0);
         }        
      });    
      headerLabel = new Label();
      headerLabel.setAlignment(Label.CENTER);
      statusLabel = new Label();        
      statusLabel.setAlignment(Label.CENTER);
      statusLabel.setSize(350,100);

      controlPanel = new Panel();
      controlPanel.setLayout(new FlowLayout());

      mainFrame.add(headerLabel);
      mainFrame.add(controlPanel);
      mainFrame.add(statusLabel);
      mainFrame.setVisible(true);  
   }

   private void showButtonDemo(){
      headerLabel.setText("Control in action: Button"); 

      Button okButton = new Button("OK");
      Button submitButton = new Button("Submit");
      Button cancelButton = new Button("Cancel");

      okButton.addActionListener(new ActionListener() {
         public void actionPerformed(ActionEvent e) {
            statusLabel.setText("Ok Button clicked.");
         }
      });

      submitButton.addActionListener(new ActionListener() {
         public void actionPerformed(ActionEvent e) {
            statusLabel.setText("Submit Button clicked.");
         }
      });

      cancelButton.addActionListener(new ActionListener() {
         public void actionPerformed(ActionEvent e) {
            statusLabel.setText("Cancel Button clicked.");
         }
      });

      controlPanel.add(okButton);
      controlPanel.add(submitButton);
      controlPanel.add(cancelButton);       

      mainFrame.setVisible(true);  
   }
}

Compile the program using command prompt. Go to D:/ > AWT and type the following command.

D:\AWT>javac com\tutorialspoint\gui\AwtControlDemo.java

If no error comes that means compilation is successful. Run the program using following command.

D:\AWT>java com.tutorialspoint.gui.AwtControlDemo

Verify the following output

AWT Button

AWT CheckBox Class

Introduction

Checkbox control is used to turn an option on(true) or off(false). There is label for each checkbox representing what the checkbox does.The state of a checkbox can be changed by clicking on it.

Class declaration

Following is the declaration for java.awt.Checkbox class:

public class Checkbox
   extends Component
      implements ItemSelectable,Accessible

Class constructors

S.N.Constructor & Description
1Checkbox()
Creates a check box with an empty string for its label.
2Checkbox(String label)
Creates a check box with the specified label.
3Checkbox(String label, boolean state)
Creates a check box with the specified label and sets the specified state.
4Checkbox(String label, boolean state, CheckboxGroup group)
Constructs a Checkbox with the specified label, set to the specified state, and in the specified check box group.
5Checkbox(String label, CheckboxGroup group, boolean state)
Creates a check box with the specified label, in the specified check box group, and set to the specified state.

Class methods

S.N.Method & Description
1void addItemListener(ItemListener l)
Adds the specified item listener to receive item events from this check box.
2void addNotify()
Creates the peer of the Checkbox.
3AccessibleContext getAccessibleContext()
Gets the AccessibleContext associated with this Checkbox.
4CheckboxGroup getCheckboxGroup()
Determines this check box's group.
5ItemListener[] getItemListeners()
Returns an array of all the item listeners registered on this checkbox.
6String getLabel()
Gets the label of this check box.
7<T extends EventListener>T[] getListeners(Class<T> listenerType)
Returns an array of all the objects currently registered as FooListeners upon this Checkbox.
8Object[] getSelectedObjects()
Returns an array (length 1) containing the checkbox label or null if the checkbox is not selected.
9boolean getState()
Determines whether this check box is in the on or off state.
10protected String paramString()
Returns a string representing the state of this Checkbox.
11protected void processEvent(AWTEvent e)
Processes events on this check box.
12protected void processItemEvent(ItemEvent e)
Processes item events occurring on this check box by dispatching them to any registered ItemListener objects.
13void removeItemListener(ItemListener l)
Removes the specified item listener so that the item listener no longer receives item events from this check box.
14void setCheckboxGroup(CheckboxGroup g)
Sets this check box's group to the specified check box group.
15void setLabel(String label)
Sets this check box's label to be the string argument.
16void setState(boolean state)
Sets the state of this check box to the specified state.

Methods inherited

This class inherits methods from the following classes:

  • java.awt.Component

  • java.lang.Object

CheckBox Example

Create the following java program using any editor of your choice in say D:/ > AWT > com > tutorialspoint > gui >

AwtControlDemo.java
package com.tutorialspoint.gui;

import java.awt.*;
import java.awt.event.*;

public class AwtControlDemo {

   private Frame mainFrame;
   private Label headerLabel;
   private Label statusLabel;
   private Panel controlPanel;

   public AwtControlDemo(){
      prepareGUI();
   }

   public static void main(String[] args){
      AwtControlDemo  awtControlDemo = new AwtControlDemo();
      awtControlDemo.showCheckBoxDemo();
   }

   private void prepareGUI(){
      mainFrame = new Frame("Java AWT Examples");
      mainFrame.setSize(400,400);
      mainFrame.setLayout(new GridLayout(3, 1));
      mainFrame.addWindowListener(new WindowAdapter() {
         public void windowClosing(WindowEvent windowEvent){
            System.exit(0);
         }        
      });    
      headerLabel = new Label();
      headerLabel.setAlignment(Label.CENTER);
      statusLabel = new Label();        
      statusLabel.setAlignment(Label.CENTER);
      statusLabel.setSize(350,100);

      controlPanel = new Panel();
      controlPanel.setLayout(new FlowLayout());

      mainFrame.add(headerLabel);
      mainFrame.add(controlPanel);
      mainFrame.add(statusLabel);
      mainFrame.setVisible(true);  
   }

   private void showCheckBoxDemo(){

      headerLabel.setText("Control in action: CheckBox"); 

      Checkbox chkApple = new Checkbox("Apple");
      Checkbox chkMango = new Checkbox("Mango");
      Checkbox chkPeer = new Checkbox("Peer");


      chkApple.addItemListener(new ItemListener() {
         public void itemStateChanged(ItemEvent e) {             
            statusLabel.setText("Apple Checkbox: " 
            + (e.getStateChange()==1?"checked":"unchecked"));
         }
      });

      chkMango.addItemListener(new ItemListener() {
         public void itemStateChanged(ItemEvent e) {
            statusLabel.setText("Mango Checkbox: " 
            + (e.getStateChange()==1?"checked":"unchecked"));
         }
      });

      chkPeer.addItemListener(new ItemListener() {
         public void itemStateChanged(ItemEvent e) {
            statusLabel.setText("Peer Checkbox: " 
            + (e.getStateChange()==1?"checked":"unchecked"));
         }
      });

      controlPanel.add(chkApple);
      controlPanel.add(chkMango);
      controlPanel.add(chkPeer);       

      mainFrame.setVisible(true);  
   }
}

Compile the program using command prompt. Go to D:/ > AWT and type the following command.

D:\AWT>javac com\tutorialspoint\gui\AwtControlDemo.java

If no error comes that means compilation is successful. Run the program using following command.

D:\AWT>java com.tutorialspoint.gui.AwtControlDemo

Verify the following output

AWT CheckBox

AWT CheckBoxGroup Class

Introduction

The CheckboxGroup class is used to group the set of checkbox.

Class declaration

Following is the declaration for java.awt.CheckboxGroup class:

public class CheckboxGroup
   extends Object
      implements Serializable

Class constructors

S.N.Constructor & Description
1CheckboxGroup() ()
Creates a new instance of CheckboxGroup.

Class methods

S.N.Method & Description
1Checkbox getCurrent()
Deprecated. As of JDK version 1.1, replaced by getSelectedCheckbox().
2Checkbox getSelectedCheckbox()
Gets the current choice from this check box group.
3void setCurrent(Checkbox box)
Deprecated. As of JDK version 1.1, replaced by setSelectedCheckbox(Checkbox).
4void setSelectedCheckbox(Checkbox box)
Sets the currently selected check box in this group to be the specified check box.
5String toString()
Returns a string representation of this check box group, including the value of its current selection.

Methods inherited

This class inherits methods from the following classes:

  • java.lang.Object

CheckBoxGroup Example

Create the following java program using any editor of your choice in say D:/ > AWT > com > tutorialspoint > gui >

AwtControlDemo.java
package com.tutorialspoint.gui;

import java.awt.*;
import java.awt.event.*;

public class AwtControlDemo {

   private Frame mainFrame;
   private Label headerLabel;
   private Label statusLabel;
   private Panel controlPanel;

   public AwtControlDemo(){
      prepareGUI();
   }

   public static void main(String[] args){
      AwtControlDemo  awtControlDemo = new AwtControlDemo();
      awtControlDemo.showCheckBoxGroupDemo();
   }

   private void prepareGUI(){
      mainFrame = new Frame("Java AWT Examples");
      mainFrame.setSize(400,400);
      mainFrame.setLayout(new GridLayout(3, 1));
      mainFrame.addWindowListener(new WindowAdapter() {
         public void windowClosing(WindowEvent windowEvent){
            System.exit(0);
         }        
      });    
      headerLabel = new Label();
      headerLabel.setAlignment(Label.CENTER);
      statusLabel = new Label();        
      statusLabel.setAlignment(Label.CENTER);
      statusLabel.setSize(350,100);

      controlPanel = new Panel();
      controlPanel.setLayout(new FlowLayout());

      mainFrame.add(headerLabel);
      mainFrame.add(controlPanel);
      mainFrame.add(statusLabel);
      mainFrame.setVisible(true);  
   }

   private void showCheckBoxGroupDemo(){
    
      headerLabel.setText("Control in action: CheckBoxGroup"); 

      CheckboxGroup fruitGroup = new CheckboxGroup();

      Checkbox chkApple = new Checkbox("Apple",fruitGroup,true);
      Checkbox chkMango = new Checkbox("Mango",fruitGroup,false);
      Checkbox chkPeer = new Checkbox("Peer",fruitGroup,false);

      statusLabel.setText("Apple Checkbox: checked");
      chkApple.addItemListener(new ItemListener() {
         public void itemStateChanged(ItemEvent e) {             
            statusLabel.setText("Apple Checkbox: checked");
         }
      });

      chkMango.addItemListener(new ItemListener() {
         public void itemStateChanged(ItemEvent e) {
            statusLabel.setText("Mango Checkbox: checked");
         }
      });

      chkPeer.addItemListener(new ItemListener() {
         public void itemStateChanged(ItemEvent e) {
            statusLabel.setText("Peer Checkbox: checked");
         }
      });

      controlPanel.add(chkApple);
      controlPanel.add(chkMango);   
      controlPanel.add(chkPeer);       

      mainFrame.setVisible(true);  
   }
}

Compile the program using command prompt. Go to D:/ > AWT and type the following command.

D:\AWT>javac com\tutorialspoint\gui\AwtControlDemo.java

If no error comes that means compilation is successful. Run the program using following command.

D:\AWT>java com.tutorialspoint.gui.AwtControlDemo

Verify the following output

AWT CheckBoxGroup

AWT List Class

Introduction

The List represents a list of text items. The list can be configured to that user can choose either one item or multiple items.

Class declaration

Following is the declaration for java.awt.List class:

public class List
   extends Component
      implements ItemSelectable, Accessible

Class constructors

S.N.Constructor & Description
1List()
Creates a new scrolling list.
2List(int rows)
Creates a new scrolling list initialized with the specified number of visible lines.
3List(int rows, boolean multipleMode)
Creates a new scrolling list initialized to display the specified number of rows.

Class methods

<T extends EventListener> T[] getListeners(Class<T> listenerType)
Returns an array of all the objects currently registered as FooListeners upon this List.
S.N.Method & Description
1void add(String item)
Adds the specified item to the end of scrolling list.
2void add(String item, int index)
Adds the specified item to the the scrolling list at the position indicated by the index.
3void addActionListener(ActionListener l)
Adds the specified action listener to receive action events from this list.
4void addItem(String item)
Deprecated. replaced by add(String).
5void addItem(String item, int index)
Deprecated. replaced by add(String, int).
6void addItemListener(ItemListener l)
Adds the specified item listener to receive item events from this list.
7void addNotify()
Creates the peer for the list.
8boolean allowsMultipleSelections()
Deprecated. As of JDK version 1.1, replaced by isMultipleMode().
9void clear()
Deprecated. As of JDK version 1.1, replaced by removeAll().
10int countItems()
Deprecated. As of JDK version 1.1, replaced by getItemCount().
11void delItem(int position)
Deprecated. replaced by remove(String) and remove(int).
12void delItems(int start, int end)
Deprecated. As of JDK version 1.1, Not for public use in the future. This method is expected to be retained only as a package private method.
13void deselect(int index)
Deselects the item at the specified index.
14AccessibleContext getAccessibleContext()
Gets the AccessibleContext associated with this List.
15ActionListener[] getActionListeners()
Returns an array of all the action listeners registered on this list.
16String getItem(int index)
Gets the item associated with the specified index.
17int getItemCount()
Gets the number of items in the list.
18ItemListener[] getItemListeners()
Returns an array of all the item listeners registered on this list.
19String[] getItems()
Gets the items in the list.
20Dimension getMinimumSize()
Determines the minimum size of this scrolling list.
21Dimension getMinimumSize(int rows)
Gets the minumum dimensions for a list with the specified number of rows.
22Dimension getPreferredSize()
Gets the preferred size of this scrolling list.
23Dimension getPreferredSize(int rows)
Gets the preferred dimensions for a list with the specified number of rows.
24int getRows()
Gets the number of visible lines in this list.
25int getSelectedIndex()
Gets the index of the selected item on the list,
26int[] getSelectedIndexes()
Gets the selected indexes on the list.
27String getSelectedItem()
Gets the selected item on this scrolling list.
28String[] getSelectedItems()
Gets the selected items on this scrolling list.
29Object[] getSelectedObjects()
Gets the selected items on this scrolling list in an array of Objects.
30int getVisibleIndex()
Gets the index of the item that was last made visible by the method makeVisible.
31boolean isIndexSelected(int index)
Determines if the specified item in this scrolling list is selected.
32boolean isMultipleMode()
Determines whether this list allows multiple selections.
33boolean isSelected(int index)
Deprecated. As of JDK version 1.1, replaced by isIndexSelected(int).
34void makeVisible(int index)
Makes the item at the specified index visible.
35Dimension minimumSize()
Deprecated. As of JDK version 1.1, replaced by getMinimumSize().
36 Dimension minimumSize(int rows)
Deprecated. As of JDK version 1.1, replaced by getMinimumSize(int).
37protected String paramString()
Returns the parameter string representing the state of this scrolling list.
38Dimension preferredSize()
Deprecated. As of JDK version 1.1, replaced by getPreferredSize().
39Dimension preferredSize(int rows)
Deprecated. As of JDK version 1.1, replaced by getPreferredSize(int).
40protected void processActionEvent(ActionEvent e)
Processes action events occurring on this component by dispatching them to any registered ActionListener objects.
41protected void processEvent(AWTEvent e)
Processes events on this scrolling list.
42protected void processItemEvent(ItemEvent e)
Processes item events occurring on this list by dispatching them to any registered ItemListener objects.
43void remove(int position)
Removes the item at the specified position from this scrolling list.
44void remove(String item)
Removes the first occurrence of an item from the list.
45void removeActionListener(ActionListener l)
Removes the specified action listener so that it no longer receives action events from this list.
46void removeAll()
Removes all items from this list.
47void removeItemListener(ItemListener l)
Removes the specified item listener so that it no longer receives item events from this list.
48void removeNotify()
Removes the peer for this list.
49void replaceItem(String newValue, int index)
Replaces the item at the specified index in the scrolling list with the new string.
50void select(int index)
Selects the item at the specified index in the scrolling list.
51void setMultipleMode(boolean b)
Sets the flag that determines whether this list allows multiple selections.
52void setMultipleSelections(boolean b)
Deprecated. As of JDK version 1.1, replaced by setMultipleMode(boolean).

Methods inherited

This class inherits methods from the following classes:

  • java.awt.Component

  • java.lang.Object

List Example

Create the following java program using any editor of your choice in say D:/ > AWT > com > tutorialspoint > gui >

AwtControlDemo.java
package com.tutorialspoint.gui;

import java.awt.*;
import java.awt.event.*;

public class AwtControlDemo {

   private Frame mainFrame;
   private Label headerLabel;
   private Label statusLabel;
   private Panel controlPanel;

   public AwtControlDemo(){
      prepareGUI();
   }

   public static void main(String[] args){
      AwtControlDemo  awtControlDemo = new AwtControlDemo();
      awtControlDemo.showListDemo();
   }

   private void prepareGUI(){
      mainFrame = new Frame("Java AWT Examples");
      mainFrame.setSize(400,400);
      mainFrame.setLayout(new GridLayout(3, 1));
      mainFrame.addWindowListener(new WindowAdapter() {
         public void windowClosing(WindowEvent windowEvent){
            System.exit(0);
         }        
      });    
      headerLabel = new Label();
      headerLabel.setAlignment(Label.CENTER);
      statusLabel = new Label();        
      statusLabel.setAlignment(Label.CENTER);
      statusLabel.setSize(350,100);

      controlPanel = new Panel();
      controlPanel.setLayout(new FlowLayout());

      mainFrame.add(headerLabel);
      mainFrame.add(controlPanel);
      mainFrame.add(statusLabel);
      mainFrame.setVisible(true);  
   }

   private void showListDemo(){                                       

      headerLabel.setText("Control in action: List"); 
      final List fruitList = new List(4,false);

      fruitList.add("Apple");
      fruitList.add("Grapes");
      fruitList.add("Mango");
      fruitList.add("Peer");

      final List vegetableList = new List(4,true);
   
      vegetableList.add("Lady Finger");
      vegetableList.add("Onion");
      vegetableList.add("Potato");
      vegetableList.add("Tomato");

      Button showButton = new Button("Show");

      showButton.addActionListener(new ActionListener() {

         public void actionPerformed(ActionEvent e) {     
            String data = "Fruits Selected: " 
               + fruitList.getItem(fruitList.getSelectedIndex());
            data += ", Vegetables selected: ";
            for(String vegetable:vegetableList.getSelectedItems()){
               data += vegetable + " ";
            }
            statusLabel.setText(data);
         }
      }); 

      controlPanel.add(fruitList);
      controlPanel.add(vegetableList);
      controlPanel.add(showButton);

      mainFrame.setVisible(true);  
   }
}

Compile the program using command prompt. Go to D:/ > AWT and type the following command.

D:\AWT>javac com\tutorialspoint\gui\AwtControlDemo.java

If no error comes that means compilation is successful. Run the program using following command.

D:\AWT>java com.tutorialspoint.gui.AwtControlDemo

Verify the following output

AWT List

AWT TextField Class

Introduction

The textField component allows the user to edit single line of text.When the user types a key in the text field the event is sent to the TextField. The key event may be key pressed, Key released or key typed. The key event is passed to the registered KeyListener. It is also possible to for an ActionEvent if the ActionEvent is enabled on the textfield then ActionEvent may be fired by pressing the return key.

Class declaration

Following is the declaration for java.awt.TextField class:

public class TextField
   extends TextComponent

Class constructors

S.N.Constructor & Description
1TextField()
Constructs a new text field.
2TextField(int columns)
Constructs a new empty text field with the specified number of columns.
3TextField(String text)
Constructs a new text field initialized with the specified text.
4TextField(String text, int columns)
Constructs a new text field initialized with the specified text to be displayed, and wide enough to hold the specified number of columns.

Class methods

S.N.Method & Description
1void addActionListener(ActionListener l)
Adds the specified action listener to receive action events from this text field.
2void addNotify()
Creates the TextField's peer.
3boolean echoCharIsSet()
Indicates whether or not this text field has a character set for echoing.
4AccessibleContext getAccessibleContext()
Gets the AccessibleContext associated with this TextField.
5ActionListener[] getActionListeners()
Returns an array of all the action listeners registered on this textfield.
6int getColumns()
Gets the number of columns in this text field.
7char getEchoChar()
Gets the character that is to be used for echoing.
8<T extends EventListener> T[] getListeners(Class<T> listenerType)
Returns an array of all the objects currently registered as FooListeners upon this TextField.
9Dimension getMinimumSize()
Gets the minumum dimensions for this text field.
10Dimension getMinimumSize(int columns) Gets the minumum dimensions for a text field with the specified number of columns.
11Dimension getPreferredSize()
Gets the preferred size of this text field.
12Dimension getPreferredSize(int columns)
Gets the preferred size of this text field with the specified number of columns.
13Dimension minimumSize()
Deprecated. As of JDK version 1.1, replaced by getMinimumSize().
14Dimension minimumSize(int columns)
Deprecated. As of JDK version 1.1, replaced by getMinimumSize(int).
15protected String paramString()
Returns a string representing the state of this TextField.
16Dimension preferredSize()
Deprecated. As of JDK version 1.1, replaced by getPreferredSize().
17Dimension preferredSize(int columns)
Deprecated. As of JDK version 1.1, replaced by getPreferredSize(int).
18protected void processActionEvent(ActionEvent e)
Processes action events occurring on this text field by dispatching them to any registered ActionListener objects.
19protected void processEvent(AWTEvent e)
Processes events on this text field.
20void removeActionListener(ActionListener l)
Removes the specified action listener so that it no longer receives action events from this text field.
21void setColumns(int columns)
Sets the number of columns in this text field.
22void setEchoChar(char c)
Sets the echo character for this text field.
23void setEchoCharacter(char c)
Deprecated. As of JDK version 1.1, replaced by setEchoChar(char).
24void setText(String t)
Sets the text that is presented by this text component to be the specified text.

Methods inherited

This class inherits methods from the following classes:

  • java.awt.TextComponent

  • java.awt.Component

  • java.lang.Object

TextField Example

Create the following java program using any editor of your choice in say D:/ > AWT > com > tutorialspoint > gui >

AwtControlDemo.java
package com.tutorialspoint.gui;

import java.awt.*;
import java.awt.event.*;

public class AwtControlDemo {

   private Frame mainFrame;
   private Label headerLabel;
   private Label statusLabel;
   private Panel controlPanel;

   public AwtControlDemo(){
      prepareGUI();
   }

   public static void main(String[] args){
      AwtControlDemo  awtControlDemo = new AwtControlDemo();
      awtControlDemo.showTextFieldDemo();
   }

   private void prepareGUI(){
      mainFrame = new Frame("Java AWT Examples");
      mainFrame.setSize(400,400);
      mainFrame.setLayout(new GridLayout(3, 1));
      mainFrame.addWindowListener(new WindowAdapter() {
         public void windowClosing(WindowEvent windowEvent){
            System.exit(0);
         }        
      });    
      headerLabel = new Label();
      headerLabel.setAlignment(Label.CENTER);
      statusLabel = new Label();        
      statusLabel.setAlignment(Label.CENTER);
      statusLabel.setSize(350,100);

      controlPanel = new Panel();
      controlPanel.setLayout(new FlowLayout());

      mainFrame.add(headerLabel);
      mainFrame.add(controlPanel);
      mainFrame.add(statusLabel);
      mainFrame.setVisible(true);  
   }

   private void showTextFieldDemo(){
      headerLabel.setText("Control in action: TextField"); 

      Label  namelabel= new Label("User ID: ", Label.RIGHT);
      Label  passwordLabel = new Label("Password: ", Label.CENTER);
      final TextField userText = new TextField(6);
      final TextField passwordText = new TextField(6);
      passwordText.setEchoChar('*');

      Button loginButton = new Button("Login");
   
      loginButton.addActionListener(new ActionListener() {
         public void actionPerformed(ActionEvent e) {     
            String data = "Username: " + userText.getText();
            data += ", Password: " + passwordText.getText();
            statusLabel.setText(data);        
         }
      }); 

      controlPanel.add(namelabel);
      controlPanel.add(userText);
      controlPanel.add(passwordLabel);       
      controlPanel.add(passwordText);
      controlPanel.add(loginButton);
      mainFrame.setVisible(true);  
   }
}

Compile the program using command prompt. Go to D:/ > AWT and type the following command.

D:\AWT>javac com\tutorialspoint\gui\AwtControlDemo.java

If no error comes that means compilation is successful. Run the program using following command.

D:\AWT>java com.tutorialspoint.gui.AwtControlDemo

Verify the following output

AWT TextField

AWT TextArea Class

Introduction

The TextArea control in AWT provide us multiline editor area. The user can type here as much as he wants. When the text in the text area become larger than the viewable area the scroll bar is automatically appears which help us to scroll the text up & down and right & left.

Class declaration

Following is the declaration for java.awt.TextArea class:

public class TextArea
   extends TextComponent

Field

Following are the fields for java.awt.TextArea class:

  • static int SCROLLBARS_BOTH -- Create and display both vertical and horizontal scrollbars.

  • static int SCROLLBARS_HORIZONTAL_ONLY -- Create and display horizontal scrollbar only.

  • static int SCROLLBARS_NONE -- Do not create or display any scrollbars for the text area.

  • static int SCROLLBARS_VERTICAL_ONLY -- Create and display vertical scrollbar only.

Class constructors

S.N.Constructor & Description
1TextArea()
Constructs a new text area with the empty string as text.
2TextArea(int rows, int columns)
Constructs a new text area with the specified number of rows and columns and the empty string as text.
3TextArea(String text)
Constructs a new text area with the specified text.
4TextArea(String text, int rows, int columns)
Constructs a new text area with the specified text, and with the specified number of rows and columns.
5TextArea(String text, int rows, int columns, int scrollbars)
Constructs a new text area with the specified text, and with the rows, columns, and scroll bar visibility as specified.

Class methods

S.N.Method & Description
1void addNotify()
Creates the TextArea's peer.
2void append(String str)
Appends the given text to the text area's current text.
3void appendText(String str)
Deprecated. As of JDK version 1.1, replaced by append(String).
4AccessibleContext getAccessibleContext()
Returns the AccessibleContext associated with this TextArea.
5int getColumns()
Returns the number of columns in this text area.
6Dimension getMinimumSize()
Determines the minimum size of this text area.
7Dimension getMinimumSize(int rows, int columns)
Determines the minimum size of a text area with the specified number of rows and columns.
8Dimension getPreferredSize()
Determines the preferred size of this text area.
9Dimension getPreferredSize(int rows, int columns)
Determines the preferred size of a text area with the specified number of rows and columns.
10int getRows()
Returns the number of rows in the text area.
11int getScrollbarVisibility()
Returns an enumerated value that indicates which scroll bars the text area uses.
12void insert(String str, int pos)
Inserts the specified text at the specified position in this text area.
13void insertText(String str, int pos)
Deprecated. As of JDK version 1.1, replaced by insert(String, int).
14Dimension minimumSize()
Deprecated. As of JDK version 1.1, replaced by getMinimumSize().
15Dimension minimumSize(int rows, int columns)
Deprecated. As of JDK version 1.1, replaced by getMinimumSize(int, int).
16protected String paramString()
Returns a string representing the state of this TextArea.
17Dimension preferredSize()
Deprecated. As of JDK version 1.1, replaced by getPreferredSize().
18Dimension preferredSize(int rows, int columns)
Deprecated. As of JDK version 1.1, replaced by getPreferredSize(int, int).
19void replaceRange(String str, int start, int end)
Replaces text between the indicated start and end positions with the specified replacement text.
20void replaceText(String str, int start, int end)
Deprecated. As of JDK version 1.1, replaced by replaceRange(String, int, int).
21void setColumns(int columns)
Sets the number of columns for this text area.
22void setRows(int rows)
Sets the number of rows for this text area.

Methods inherited

This class inherits methods from the following classes:

  • java.awt.TextComponent

  • java.awt.Component

  • java.lang.Object

TextArea Example

Create the following java program using any editor of your choice in say D:/ > AWT > com > tutorialspoint > gui >

AwtControlDemo.java
package com.tutorialspoint.gui;

import java.awt.*;
import java.awt.event.*;

public class AwtControlDemo {

   private Frame mainFrame;
   private Label headerLabel;
   private Label statusLabel;
   private Panel controlPanel;

   public AwtControlDemo(){
      prepareGUI();
   }

   public static void main(String[] args){
      AwtControlDemo  awtControlDemo = new AwtControlDemo();
      awtControlDemo.showTextAreaDemo();
   }

   private void prepareGUI(){
      mainFrame = new Frame("Java AWT Examples");
      mainFrame.setSize(400,400);
      mainFrame.setLayout(new GridLayout(3, 1));
      mainFrame.addWindowListener(new WindowAdapter() {
         public void windowClosing(WindowEvent windowEvent){
            System.exit(0);
         }        
      });    
      headerLabel = new Label();
      headerLabel.setAlignment(Label.CENTER);
      statusLabel = new Label();        
      statusLabel.setAlignment(Label.CENTER);
      statusLabel.setSize(350,100);

      controlPanel = new Panel();
      controlPanel.setLayout(new FlowLayout());

      mainFrame.add(headerLabel);
      mainFrame.add(controlPanel);
      mainFrame.add(statusLabel);
      mainFrame.setVisible(true);  
   }

   private void showTextAreaDemo(){
      headerLabel.setText("Control in action: TextArea"); 

      Label  commentlabel= new Label("Comments: ", Label.RIGHT);

      final TextArea commentTextArea = new TextArea("This is a AWT tutorial "
      +"to make GUI application in Java.",5,30);

      Button showButton = new Button("Show");

      showButton.addActionListener(new ActionListener() {
         public void actionPerformed(ActionEvent e) {     
            statusLabel.setText( commentTextArea.getText());        
         }
      }); 

      controlPanel.add(commentlabel);
      controlPanel.add(commentTextArea);        
      controlPanel.add(showButton);
      mainFrame.setVisible(true);  
   }
}

Compile the program using command prompt. Go to D:/ > AWT and type the following command.

D:\AWT>javac com\tutorialspoint\gui\AwtControlDemo.java

If no error comes that means compilation is successful. Run the program using following command.

D:\AWT>java com.tutorialspoint.gui.AwtControlDemo

Verify the following output

AWT TextArea

AWT Choice Class

Introduction

Choice control is used to show pop up menu of choices. Selected choice is shown on the top of the menu.

Class declaration

Following is the declaration for java.awt.Choice class:

public class Choice
   extends Component
      implements ItemSelectable, Accessible

Class constructors

S.N.Constructor & Description
1Choice() ()
Creates a new choice menu.

Class methods

S.N.Method & Description
1void add(String item)
Adds an item to this Choice menu.
2void addItem(String item)
Obsolete as of Java 2 platform v1.1.
3void addItemListener(ItemListener l)
Adds the specified item listener to receive item events from this Choice menu.
4void addNotify()
Creates the Choice's peer.
5int countItems()
Deprecated. As of JDK version 1.1, replaced by getItemCount().
6AccessibleContext getAccessibleContext()
Gets the AccessibleContext associated with this Choice.
7String getItem(int index)
Gets the string at the specified index in this Choice menu.
8int getItemCount()
Returns the number of items in this Choice menu.
9ItemListener[] getItemListeners()
Returns an array of all the item listeners registered on this choice.
10<T extends EventListener> T[] getListeners(Class<T> listenerType)
Returns an array of all the objects currently registered as FooListeners upon this Choice.
11int getSelectedIndex()
Returns the index of the currently selected item.
12String getSelectedItem()
Gets a representation of the current choice as a string.
13Object[] getSelectedObjects()
Returns an array (length 1) containing the currently selected item.
14void insert(String item, int index)
Inserts the item into this choice at the specified position.
15protected String paramString()
Returns a string representing the state of this Choice menu.
16protected void processEvent(AWTEvent e)
Processes events on this choice.
17protected void processItemEvent(ItemEvent e)
Processes item events occurring on this Choice menu by dispatching them to any registered ItemListener objects.
18void remove(int position)
Removes an item from the choice menu at the specified position.
19void remove(String item)
Removes the first occurrence of item from the Choice menu.
20void removeAll()
Removes all items from the choice menu.
21void removeItemListener(ItemListener l)
Removes the specified item listener so that it no longer receives item events from this Choice menu.
22void select(int pos)
Sets the selected item in this Choice menu to be the item at the specified position.
23void select(String str)
Sets the selected item in this Choice menu to be the item whose name is equal to the specified string.

Methods inherited

This class inherits methods from the following classes:

  • java.awt.Component

  • java.lang.Object

Choice Example

Create the following java program using any editor of your choice in say D:/ > AWT > com > tutorialspoint > gui >

AwtControlDemo.java
package com.tutorialspoint.gui;

import java.awt.*;
import java.awt.event.*;

public class AwtControlDemo {

   private Frame mainFrame;
   private Label headerLabel;
   private Label statusLabel;
   private Panel controlPanel;

   public AwtControlDemo(){
      prepareGUI();
   }

   public static void main(String[] args){
      AwtControlDemo  awtControlDemo = new AwtControlDemo();
      awtControlDemo.showChoiceDemo();
   }

   private void prepareGUI(){
      mainFrame = new Frame("Java AWT Examples");
      mainFrame.setSize(400,400);
      mainFrame.setLayout(new GridLayout(3, 1));
      mainFrame.addWindowListener(new WindowAdapter() {
         public void windowClosing(WindowEvent windowEvent){
            System.exit(0);
         }        
      });    
      headerLabel = new Label();
      headerLabel.setAlignment(Label.CENTER);
      statusLabel = new Label();        
      statusLabel.setAlignment(Label.CENTER);
      statusLabel.setSize(350,100);

      controlPanel = new Panel();
      controlPanel.setLayout(new FlowLayout());

      mainFrame.add(headerLabel);
      mainFrame.add(controlPanel);
      mainFrame.add(statusLabel);
      mainFrame.setVisible(true);  
   }

   private void showChoiceDemo(){                                       

      headerLabel.setText("Control in action: Choice"); 
      final Choice fruitChoice = new Choice();

      fruitChoice.add("Apple");
      fruitChoice.add("Grapes");
      fruitChoice.add("Mango");
      fruitChoice.add("Peer");

      Button showButton = new Button("Show");

      showButton.addActionListener(new ActionListener() {
         public void actionPerformed(ActionEvent e) {     
            String data = "Fruit Selected: " 
            + fruitChoice.getItem(fruitChoice.getSelectedIndex());
            statusLabel.setText(data);
         }
      }); 

      controlPanel.add(fruitChoice);
      controlPanel.add(showButton);

      mainFrame.setVisible(true);  
   }
}

Compile the program using command prompt. Go to D:/ > AWT and type the following command.

D:\AWT>javac com\tutorialspoint\gui\AwtControlDemo.java

If no error comes that means compilation is successful. Run the program using following command.

D:\AWT>java com.tutorialspoint.gui.AwtControlDemo

Verify the following output

AWT Choice

AWT Canvas Class

Introduction

Canvas control represents a rectangular area where application can draw something or can receive inputs created by user.

Class declaration

Following is the declaration for java.awt.Canvas class:

public class Canvas
   extends Component
      implements Accessible

Class constructors

S.N.Constructor & Description
1Canvas()
Constructs a new Canvas.
2Canvas(GraphicsConfiguration config)
Constructs a new Canvas given a GraphicsConfiguration object.

Class methods

S.N.Method & Description
1void addNotify()
Creates the peer of the canvas.
2void createBufferStrategy(int numBuffers)
Creates a new strategy for multi-buffering on this component.
3void createBufferStrategy(int numBuffers, BufferCapabilities caps)
Creates a new strategy for multi-buffering on this component with the required buffer capabilities.
4AccessibleContext getAccessibleContext()
Gets the AccessibleContext associated with this Canvas.
5BufferStrategy getBufferStrategy()
Returns the BufferStrategy used by this component.
6void paint(Graphics g)
Paints this canvas.
7void pdate(Graphics g)
Updates this canvas.

Methods inherited

This class inherits methods from the following classes:

  • java.awt.Component

  • java.lang.Object

Canvas Example

Create the following java program using any editor of your choice in say D:/ > AWT > com > tutorialspoint > gui >

AwtControlDemo.java
package com.tutorialspoint.gui;

import java.awt.*;
import java.awt.event.*;

public class AwtControlDemo {

   private Frame mainFrame;
   private Label headerLabel;
   private Label statusLabel;
   private Panel controlPanel;

   public AwtControlDemo(){
      prepareGUI();
   }

   public static void main(String[] args){
      AwtControlDemo  awtControlDemo = new AwtControlDemo();
      awtControlDemo.showCanvasDemo();
   }

   private void prepareGUI(){
      mainFrame = new Frame("Java AWT Examples");
      mainFrame.setSize(400,400);
      mainFrame.setLayout(new GridLayout(3, 1));
      mainFrame.addWindowListener(new WindowAdapter() {
         public void windowClosing(WindowEvent windowEvent){
            System.exit(0);
         }        
      });    
      headerLabel = new Label();
      headerLabel.setAlignment(Label.CENTER);
      statusLabel = new Label();        
      statusLabel.setAlignment(Label.CENTER);
      statusLabel.setSize(350,100);

      controlPanel = new Panel();
      controlPanel.setLayout(new FlowLayout());

      mainFrame.add(headerLabel);
      mainFrame.add(controlPanel);
      mainFrame.add(statusLabel);
      mainFrame.setVisible(true);  
   }

   private void showCanvasDemo(){
      headerLabel.setText("Control in action: Canvas"); 

      controlPanel.add(new MyCanvas());
      mainFrame.setVisible(true);  
   } 

   class MyCanvas extends Canvas {

      public MyCanvas () {
         setBackground (Color.GRAY);
         setSize(300, 300);
      }

      public void paint (Graphics g) {
         Graphics2D g2;
         g2 = (Graphics2D) g;
         g2.drawString ("It is a custom canvas area", 70, 70);
      }
   }
}

Compile the program using command prompt. Go to D:/ > AWT and type the following command.

D:\AWT>javac com\tutorialspoint\gui\AwtControlDemo.java

If no error comes that means compilation is successful. Run the program using following command.

D:\AWT>java com.tutorialspoint.gui.AwtControlDemo

Verify the following output

AWT Canvas

AWT Image Class

Introduction

Image control is superclass for all image classes representing graphical images.

Class declaration

Following is the declaration for java.awt.Image class:

public abstract class Image
   extends Object

Field

Following are the fields for java.awt.Image class:

  • protected float accelerationPriority -- Priority for accelerating this image.

  • static int SCALE_AREA_AVERAGING -- Use the Area Averaging image scaling algorithm.

  • static int SCALE_DEFAULT -- Use the default image-scaling algorithm.

  • static int SCALE_FAST -- Choose an image-scaling algorithm that gives higher priority to scaling speed than smoothness of the scaled image.

  • static int SCALE_REPLICATE -- Use the image scaling algorithm embodied in the ReplicateScaleFilter class.

  • static int SCALE_SMOOTH -- Choose an image-scaling algorithm that gives higher priority to image smoothness than scaling speed.

  • static Object UndefinedProperty -- The UndefinedProperty object should be returned whenever a property which was not defined for a particular image is fetched.

Class constructors

S.N.Constructor & Description
1Image()

Class methods

S.N.Method & Description
1void flush()
Flushes all reconstructable resources being used by this Image object.
2float getAccelerationPriority()
Returns the current value of the acceleration priority hint.
3ImageCapabilities getCapabilities(GraphicsConfiguration gc)
Returns an ImageCapabilities object which can be inquired as to the capabilities of this Image on the specified GraphicsConfiguration.
4abstract Graphics getGraphics()
Creates a graphics context for drawing to an off-screen image.
5abstract int getHeight(ImageObserver observer)
Determines the height of the image.
6abstract Object getProperty(String name, ImageObserver observer)
Gets a property of this image by name.
7Image getScaledInstance(int width, int height, int hints)
Creates a scaled version of this image.
8abstract ImageProducer getSource()
Gets the object that produces the pixels for the image.
9abstract int getWidth(ImageObserver observer)
Determines the width of the image.
10void setAccelerationPriority(float priority)
Sets a hint for this image about how important acceleration is.

Methods inherited

This class inherits methods from the following classes:

  • java.lang.Object

Image Example

Create the following java program using any editor of your choice in say D:/ > AWT > com > tutorialspoint > gui >

AwtControlDemo.java
package com.tutorialspoint.gui;

import java.awt.*;
import java.awt.event.*;

public class AwtControlDemo {

   private Frame mainFrame;
   private Label headerLabel;
   private Label statusLabel;
   private Panel controlPanel;

   public AwtControlDemo(){
      prepareGUI();
   }

   public static void main(String[] args){
      AwtControlDemo  awtControlDemo = new AwtControlDemo();
      awtControlDemo.showImageDemo();
   }

   private void prepareGUI(){
      mainFrame = new Frame("Java AWT Examples");
      mainFrame.setSize(400,400);
      mainFrame.setLayout(new GridLayout(3, 1));
      mainFrame.addWindowListener(new WindowAdapter() {
         public void windowClosing(WindowEvent windowEvent){
            System.exit(0);
         }        
      });    
      headerLabel = new Label();
      headerLabel.setAlignment(Label.CENTER);
      statusLabel = new Label();        
      statusLabel.setAlignment(Label.CENTER);
      statusLabel.setSize(350,100);

      controlPanel = new Panel();
      controlPanel.setLayout(new FlowLayout());

      mainFrame.add(headerLabel);
      mainFrame.add(controlPanel);
      mainFrame.add(statusLabel);
      mainFrame.setVisible(true);  
   }

   private void showImageDemo(){
      headerLabel.setText("Control in action: Image"); 

      controlPanel.add(new ImageComponent("resources/java.jpg"));
      mainFrame.setVisible(true);  
   }
	
   class ImageComponent extends Component {

      BufferedImage img;

      public void paint(Graphics g) {
         g.drawImage(img, 0, 0, null);
      }

      public ImageComponent(String path) {
         try {
            img = ImageIO.read(new File(path));
         } catch (IOException e) {
            e.printStackTrace();
         }
      }

      public Dimension getPreferredSize() {
         if (img == null) {
            return new Dimension(100,100);
         } else {
            return new Dimension(img.getWidth(), img.getHeight());
         }
      }
   }
}

Compile the program using command prompt. Go to D:/ > AWT and type the following command.

D:\AWT>javac com\tutorialspoint\gui\AwtControlDemo.java

If no error comes that means compilation is successful. Run the program using following command.

D:\AWT>java com.tutorialspoint.gui.AwtControlDemo

Verify the following output

AWT Image

AWT Scrollbar Class

Introduction

Scrollbar control represents a scroll bar component in order to enable user to select from range of values.

Class declaration

Following is the declaration for java.awt.Scrollbar class:

public class Scrollbar
   extends Component
      implements Adjustable, Accessible

Field

Following are the fields for java.awt.Image class:

  • static int HORIZONTAL --A constant that indicates a horizontal scroll bar.

  • static int VERTICAL --A constant that indicates a vertical scroll bar.

Class constructors

S.N.Constructor & Description
1Scrollbar()
Constructs a new vertical scroll bar.
2Scrollbar(int orientation)
Constructs a new scroll bar with the specified orientation.
3Scrollbar(int orientation, int value, int visible, int minimum, int maximum)
Constructs a new scroll bar with the specified orientation, initial value, visible amount, and minimum and maximum values.

Class methods

AccessibleContext getAccessibleContext()
Gets the AccessibleContext associated with this Scrollbar. AdjustmentListener[] getAdjustmentListeners()
Returns an array of all the adjustment listeners registered on this scrollbar. <T extends EventListener>T[] getListeners(Class<T> listenerType)
Returns an array of all the objects currently registered as FooListeners upon this Scrollbar.
S.N.Method & Description
1void addAdjustmentListener(AdjustmentListener l)
Adds the specified adjustment listener to receive instances of AdjustmentEvent from this scroll bar.
2void addNotify()
Creates the Scrollbar's peer.
3int getBlockIncrement()
Gets the block increment of this scroll bar.
4int getLineIncrement()
Deprecated. As of JDK version 1.1, replaced by getUnitIncrement().
5int getMaximum()
Gets the maximum value of this scroll bar.
6int getMinimum()
Gets the minimum value of this scroll bar.
7int getOrientation()
Returns the orientation of this scroll bar.
8int getPageIncrement()
Deprecated. As of JDK version 1.1, replaced by getBlockIncrement().
9int getUnitIncrement()
Gets the unit increment for this scrollbar.
10int getValue()
Gets the current value of this scroll bar.
11boolean
getValueIsAdjusting()
Returns true if the value is in the process of changing as a result of actions being taken by the user.
12int getVisible()
Deprecated. As of JDK version 1.1, replaced by getVisibleAmount().
13int getVisibleAmount()
Gets the visible amount of this scroll bar.
14protected String paramString()
Returns a string representing the state of this Scrollbar.
15protected void processAdjustmentEvent(AdjustmentEvent e)
Processes adjustment events occurring on this scrollbar by dispatching them to any registered AdjustmentListener objects.
16protected
1void processEvent(AWTEvent e)
Processes events on this scroll bar.
17void removeAdjustmentListener(AdjustmentListener l)
Removes the specified adjustment listener so that it no longer receives instances of AdjustmentEvent from this scroll bar.
18void setBlockIncrement(int v)
Sets the block increment for this scroll bar.
19void setLineIncrement(int v)
Deprecated. As of JDK version 1.1, replaced by setUnitIncrement(int).
20void setMaximum(int newMaximum)
Sets the maximum value of this scroll bar.
21void setMinimum(int newMinimum)
Sets the minimum value of this scroll bar.
22void setOrientation(int orientation)
Sets the orientation for this scroll bar.
23void setPageIncrement(int v)
Deprecated. As of JDK version 1.1, replaced by setBlockIncrement().
24void setUnitIncrement(int v)
Sets the unit increment for this scroll bar.
25void setValue(int newValue)
Sets the value of this scroll bar to the specified value.
26void setValueIsAdjusting(boolean b)
Sets the valueIsAdjusting property.
27void setValues(int value, int visible, int minimum, int maximum)
Sets the values of four properties for this scroll bar: value, visibleAmount, minimum, and maximum.
28void setVisibleAmount(int newAmount)
Sets the visible amount of this scroll bar.

Methods inherited

This class inherits methods from the following classes:

  • java.awt.Component

  • java.lang.Object

Scrollbar Example

Create the following java program using any editor of your choice in say D:/ > AWT > com > tutorialspoint > gui >

AwtControlDemo.java
package com.tutorialspoint.gui;

import java.awt.*;
import java.awt.event.*;

public class AwtControlDemo {

   private Frame mainFrame;
   private Label headerLabel;
   private Label statusLabel;
   private Panel controlPanel;

   public AwtControlDemo(){
      prepareGUI();
   }

   public static void main(String[] args){
      AwtControlDemo  awtControlDemo = new AwtControlDemo();
      awtControlDemo.showScrollbarDemo();
   }

   private void prepareGUI(){
      mainFrame = new Frame("Java AWT Examples");
      mainFrame.setSize(400,400);
      mainFrame.setLayout(new GridLayout(3, 1));
      mainFrame.addWindowListener(new WindowAdapter() {
         public void windowClosing(WindowEvent windowEvent){
            System.exit(0);
         }        
      });    
      headerLabel = new Label();
      headerLabel.setAlignment(Label.CENTER);
      statusLabel = new Label();        
      statusLabel.setAlignment(Label.CENTER);
      statusLabel.setSize(350,100);

      controlPanel = new Panel();
      controlPanel.setLayout(new FlowLayout());

      mainFrame.add(headerLabel);
      mainFrame.add(controlPanel);
      mainFrame.add(statusLabel);
      mainFrame.setVisible(true);  
   }

   private void showScrollbarDemo(){                                       
      headerLabel.setText("Control in action: Scrollbar"); 

      final Scrollbar horizontalScroller = new Scrollbar(Scrollbar.HORIZONTAL);
      final Scrollbar verticalScroller = new Scrollbar();
      verticalScroller.setOrientation(Scrollbar.VERTICAL);
      horizontalScroller.setMaximum (100);
      horizontalScroller.setMinimum (1);
      verticalScroller.setMaximum (100);
      verticalScroller.setMinimum (1);

      horizontalScroller.addAdjustmentListener(new AdjustmentListener() {

         @Override
         public void adjustmentValueChanged(AdjustmentEvent e) {
            statusLabel.setText("Horozontal: "
               +horizontalScroller.getValue() 
               +" ,Vertical: "
               + verticalScroller.getValue());
            }
         });

      verticalScroller.addAdjustmentListener(new AdjustmentListener() {

            @Override
            public void adjustmentValueChanged(AdjustmentEvent e) {
               statusLabel.setText("Horozontal: "
               +horizontalScroller.getValue() 
               +" ,Vertical: "+ verticalScroller.getValue());
            }
         });

      controlPanel.add(horizontalScroller);
      controlPanel.add(verticalScroller);

      mainFrame.setVisible(true);  
   }
}

Compile the program using command prompt. Go to D:/ > AWT and type the following command.

D:\AWT>javac com\tutorialspoint\gui\AwtControlDemo.java

If no error comes that means compilation is successful. Run the program using following command.

D:\AWT>java com.tutorialspoint.gui.AwtControlDemo

Verify the following output

AWT Scrollbar

AWT Dialog Class

Introduction

Dialog control represents a top-level window with a title and a border used to take some form of input from the user.

Class declaration

Following is the declaration for java.awt.Dialog class:

public class Dialog
extends Window

Field

Following are the fields for java.awt.Image class:

  • static Dialog.ModalityType DEFAULT_MODALITY_TYPE -- Default modality type for modal dialogs.

Class constructors

S.N.Constructor & Description
1Dialog(Dialog owner)
Constructs an initially invisible, modeless Dialog with the specified owner Dialog and an empty title.
2Dialog(Dialog owner, String title)
Constructs an initially invisible, modeless Dialog with the specified owner Dialog and title.
3Dialog(Dialog owner, String title, boolean modal)
Constructs an initially invisible Dialog with the specified owner Dialog, title, and modality.
4Dialog(Dialog owner, String title, boolean modal, GraphicsConfiguration gc)
Constructs an initially invisible Dialog with the specified owner Dialog, title, modality and GraphicsConfiguration.
5Dialog(Frame owner)
Constructs an initially invisible, modeless Dialog with the specified owner Frame and an empty title.
6Dialog(Frame owner, boolean modal)
Constructs an initially invisible Dialog with the specified owner Frame and modality and an empty title.
7Dialog(Frame owner, String title)
Constructs an initially invisible, modeless Dialog with the specified owner Frame and title.
8Dialog(Frame owner, String title, boolean modal)
Constructs an initially invisible Dialog with the specified owner Frame, title and modality.
9Dialog(Frame owner, String title, boolean modal, GraphicsConfiguration gc)
Constructs an initially invisible Dialog with the specified owner Frame, title, modality, and GraphicsConfiguration.
10Dialog(Window owner)
Constructs an initially invisible, modeless Dialog with the specified owner Window and an empty title.
11Dialog(Window owner, Dialog.ModalityType modalityType)
Constructs an initially invisible Dialog with the specified owner Window and modality and an empty title.
12Dialog(Window owner, String title)
Constructs an initially invisible, modeless Dialog with the specified owner Window and title.
13Dialog(Window owner, String title, Dialog.ModalityType modalityType)
Constructs an initially invisible Dialog with the specified owner Window, title and modality.
14Dialog(Window owner, String title, Dialog.ModalityType modalityType, GraphicsConfiguration gc)
Constructs an initially invisible Dialog with the specified owner Window, title, modality and GraphicsConfiguration

Class methods

S.N.Method & Description
1void addNotify()
Makes this Dialog displayable by connecting it to a native screen resource.
2AccessibleContext getAccessibleContext()
Gets the AccessibleContext associated with this Dialog.
3Dialog.ModalityType getModalityType()
Returns the modality type of this dialog.
4String getTitle()
Gets the title of the dialog.
5void hide()
Deprecated. As of JDK version 1.5, replaced by setVisible(boolean).
6boolean isModal()
Indicates whether the dialog is modal.
7boolean isResizable()
Indicates whether this dialog is resizable by the user.
8boolean isUndecorated()
Indicates whether this dialog is undecorated.
9protected String paramString()
Returns a string representing the state of this dialog.
10void setModal(boolean modal)
Specifies whether this dialog should be modal.
11void setModalityType(Dialog.ModalityType type)
Sets the modality type for this dialog.
12void setResizable(boolean resizable)
Sets whether this dialog is resizable by the user.
13void setTitle(String title)
Sets the title of the Dialog.
14void setUndecorated(boolean undecorated)
Disables or enables decorations for this dialog.
15void setVisible(boolean b)
Shows or hides this Dialog depending on the value of parameter b.
16void show()
Deprecated. As of JDK version 1.5, replaced by setVisible(boolean).
17void toBack()
If this Window is visible, sends this Window to the back and may cause it to lose focus or activation if it is the focused or active Window.

Methods inherited

This class inherits methods from the following classes:

  • java.awt.Window

  • java.awt.Component

  • java.lang.Object

Dialog Example

Create the following java program using any editor of your choice in say D:/ > AWT > com > tutorialspoint > gui >

AwtControlDemo.java
package com.tutorialspoint.gui;

import java.awt.*;
import java.awt.event.*;

public class AwtControlDemo {

   private Frame mainFrame;
   private Label headerLabel;
   private Label statusLabel;
   private Panel controlPanel;

   public AwtControlDemo(){
      prepareGUI();
   }

   public static void main(String[] args){
      AwtControlDemo  awtControlDemo = new AwtControlDemo();
      awtControlDemo.showDialogDemo();
   }

   private void prepareGUI(){
      mainFrame = new Frame("Java AWT Examples");
      mainFrame.setSize(400,400);
      mainFrame.setLayout(new GridLayout(3, 1));
      mainFrame.addWindowListener(new WindowAdapter() {
         public void windowClosing(WindowEvent windowEvent){
            System.exit(0);
         }        
      });    
      headerLabel = new Label();
      headerLabel.setAlignment(Label.CENTER);
      statusLabel = new Label();        
      statusLabel.setAlignment(Label.CENTER);
      statusLabel.setSize(350,100);

      controlPanel = new Panel();
      controlPanel.setLayout(new FlowLayout());

      mainFrame.add(headerLabel);
      mainFrame.add(controlPanel);
      mainFrame.add(statusLabel);
      mainFrame.setVisible(true);  
   }

   private void showDialogDemo(){
      headerLabel.setText("Control in action: Dialog"); 
      Button showAboutDialogButton = new Button("Show About Dialog");
      showAboutDialogButton.addActionListener(new ActionListener() {
	     @Override
         public void actionPerformed(ActionEvent e) {
            AboutDialog aboutDialog = new AboutDialog(mainFrame);
            aboutDialog.setVisible(true);
         }
      });

      controlPanel.add(showAboutDialogButton);
      mainFrame.setVisible(true);  
   }

   class AboutDialog extends Dialog {
      public AboutDialog(Frame parent){
         super(parent, true);         
         setBackground(Color.gray);
         setLayout(new BorderLayout());
         Panel panel = new Panel();
         panel.add(new Button("Close"));
         add("South", panel);
         setSize(200,200);

         addWindowListener(new WindowAdapter() {
            public void windowClosing(WindowEvent windowEvent){
               dispose();
            }
         });
      }

      public boolean action(Event evt, Object arg){
         if(arg.equals("Close")){
            dispose();
            return true;
         }
         return false;
      }

      public void paint(Graphics g){
         g.setColor(Color.white);
         g.drawString("TutorialsPoint.Com", 25,70 );
         g.drawString("Version 1.0", 60, 90);      
      }
   }
}

Compile the program using command prompt. Go to D:/ > AWT and type the following command.

D:\AWT>javac com\tutorialspoint\gui\AwtControlDemo.java

If no error comes that means compilation is successful. Run the program using following command.

D:\AWT>java com.tutorialspoint.gui.AwtControlDemo

Verify the following output

AWT Dialog

AWT FileDialog Class

Introduction

FileDialog control represents a dialog window from which the user can select a file.

Class declaration

Following is the declaration for java.awt.FileDialog class:

public class FileDialog
   extends Dialog

Field

Following are the fields for java.awt.Image class:

  • static int LOAD -- This constant value indicates that the purpose of the file dialog window is to locate a file from which to read.

  • static int SAVE -- This constant value indicates that the purpose of the file dialog window is to locate a file to which to write.

Class constructors

S.N.Constructor & Description
1FileDialog(Dialog parent)
Creates a file dialog for loading a file.
2FileDialog(Dialog parent, String title)
Creates a file dialog window with the specified title for loading a file.
3FileDialog(Dialog parent, String title, int mode)
Creates a file dialog window with the specified title for loading or saving a file.
4FileDialog(Frame parent)
Creates a file dialog for loading a file.
5FileDialog(Frame parent, String title)
Creates a file dialog window with the specified title for loading a file.
6FileDialog(Frame parent, String title, int mode)
Creates a file dialog window with the specified title for loading or saving a file.

Class methods

S.N.Method & Description
1void addNotify()
Creates the file dialog's peer.
2String getDirectory()
Gets the directory of this file dialog.
3String getFile()
Gets the selected file of this file dialog.
4FilenameFilter getFilenameFilter()
Determines this file dialog's filename filter.
5int getMode()
Indicates whether this file dialog box is for loading from a file or for saving to a file.
6protected String paramString()
Returns a string representing the state of this FileDialog window.
7void setDirectory(String dir)
Sets the directory of this file dialog window to be the specified directory.
8void setFile(String file)
Sets the selected file for this file dialog window to be the specified file.
9void setFilenameFilter(FilenameFilter filter)
Sets the filename filter for this file dialog window to the specified filter.
10void setMode(int mode)
Sets the mode of the file dialog.

Methods inherited

This class inherits methods from the following classes:

  • java.awt.Dialog

  • java.awt.Window

  • java.awt.Component

  • java.lang.Object

FileDialog Example

Create the following java program using any editor of your choice in say D:/ > AWT > com > tutorialspoint > gui >

AwtControlDemo.java
package com.tutorialspoint.gui;

import java.awt.*;
import java.awt.event.*;

public class AwtControlDemo {

   private Frame mainFrame;
   private Label headerLabel;
   private Label statusLabel;
   private Panel controlPanel;

   public AwtControlDemo(){
      prepareGUI();
   }

   public static void main(String[] args){
      AwtControlDemo  awtControlDemo = new AwtControlDemo();
      awtControlDemo.showFileDialogDemo();
   }

   private void prepareGUI(){
      mainFrame = new Frame("Java AWT Examples");
      mainFrame.setSize(400,400);
      mainFrame.setLayout(new GridLayout(3, 1));
      mainFrame.addWindowListener(new WindowAdapter() {
         public void windowClosing(WindowEvent windowEvent){
            System.exit(0);
         }        
      });    
      headerLabel = new Label();
      headerLabel.setAlignment(Label.CENTER);
      statusLabel = new Label();        
      statusLabel.setAlignment(Label.CENTER);
      statusLabel.setSize(350,100);

      controlPanel = new Panel();
      controlPanel.setLayout(new FlowLayout());

      mainFrame.add(headerLabel);
      mainFrame.add(controlPanel);
      mainFrame.add(statusLabel);
      mainFrame.setVisible(true);  
   }

   private void showFileDialogDemo(){
      headerLabel.setText("Control in action: FileDialog"); 

      final FileDialog fileDialog = new FileDialog(mainFrame,"Select file");
      Button showFileDialogButton = new Button("Open File");
      showFileDialogButton.addActionListener(new ActionListener() {
         @Override
         public void actionPerformed(ActionEvent e) {
            fileDialog.setVisible(true);
            statusLabel.setText("File Selected :" 
            + fileDialog.getDirectory() + fileDialog.getFile());
         }
      });

      controlPanel.add(showFileDialogButton);
      mainFrame.setVisible(true);  
   }
}

Compile the program using command prompt. Go to D:/ > AWT and type the following command.

D:\AWT>javac com\tutorialspoint\gui\AwtControlDemo.java

If no error comes that means compilation is successful. Run the program using following command.

D:\AWT>java com.tutorialspoint.gui.AwtControlDemo

Verify the following output

AWT FileDialog

Event Handling

What is an Event?

Change in the state of an object is known as event i.e. event describes the change in state of source. Events are generated as result of user interaction with the graphical user interface components. For example, clicking on a button, moving the mouse, entering a character through keyboard,selecting an item from list, scrolling the page are the activities that causes an event to happen.

Types of Event

The events can be broadly classified into two categories:

  • Foreground Events - Those events which require the direct interaction of user.They are generated as consequences of a person interacting with the graphical components in Graphical User Interface. For example, clicking on a button, moving the mouse, entering a character through keyboard,selecting an item from list, scrolling the page etc.

  • Background Events - Those events that require the interaction of end user are known as background events. Operating system interrupts, hardware or software failure, timer expires, an operation completion are the example of background events.

What is Event Handling?

Event Handling is the mechanism that controls the event and decides what should happen if an event occurs. This mechanism have the code which is known as event handler that is executed when an event occurs. Java Uses the Delegation Event Model to handle the events. This model defines the standard mechanism to generate and handle the events.Let's have a brief introduction to this model.

The Delegation Event Model has the following key participants namely:

  • Source - The source is an object on which event occurs. Source is responsible for providing information of the occurred event to it's handler. Java provide as with classes for source object.

  • Listener - It is also known as event handler.Listener is responsible for generating response to an event. From java implementation point of view the listener is also an object. Listener waits until it receives an event. Once the event is received , the listener process the event an then returns.

The benefit of this approach is that the user interface logic is completely separated from the logic that generates the event. The user interface element is able to delegate the processing of an event to the separate piece of code. In this model ,Listener needs to be registered with the source object so that the listener can receive the event notification. This is an efficient way of handling the event because the event notifications are sent only to those listener that want to receive them.

Steps involved in event handling

  • The User clicks the button and the event is generated.

  • Now the object of concerned event class is created automatically and information about the source and the event get populated with in same object.

  • Event object is forwarded to the method of registered listener class.

  • the method is now get executed and returns.

Points to remember about listener

  • In order to design a listener class we have to develop some listener interfaces.These Listener interfaces forecast some public abstract callback methods which must be implemented by the listener class.

  • If you do not implement the any if the predefined interfaces then your class can not act as a listener class for a source object.

Callback Methods

These are the methods that are provided by API provider and are defined by the application programmer and invoked by the application developer. Here the callback methods represents an event method. In response to an event java jre will fire callback method. All such callback methods are provided in listener interfaces.

If a component wants some listener will listen to it's events the the source must register itself to the listener.

Event Handling Example

Create the following java program using any editor of your choice in say D:/ > AWT > com > tutorialspoint > gui >

AwtControlDemo.java
package com.tutorialspoint.gui;

import java.awt.*;
import java.awt.event.*;

public class AwtControlDemo {

   private Frame mainFrame;
   private Label headerLabel;
   private Label statusLabel;
   private Panel controlPanel;

   public AwtControlDemo(){
      prepareGUI();
   }

   public static void main(String[] args){
      AwtControlDemo  awtControlDemo = new AwtControlDemo();
      awtControlDemo.showEventDemo();
   }

   private void prepareGUI(){
      mainFrame = new Frame("Java AWT Examples");
      mainFrame.setSize(400,400);
      mainFrame.setLayout(new GridLayout(3, 1));
      mainFrame.addWindowListener(new WindowAdapter() {
         public void windowClosing(WindowEvent windowEvent){
            System.exit(0);
         }        
      });    
      headerLabel = new Label();
      headerLabel.setAlignment(Label.CENTER);
      statusLabel = new Label();        
      statusLabel.setAlignment(Label.CENTER);
      statusLabel.setSize(350,100);

      controlPanel = new Panel();
      controlPanel.setLayout(new FlowLayout());

      mainFrame.add(headerLabel);
      mainFrame.add(controlPanel);
      mainFrame.add(statusLabel);
      mainFrame.setVisible(true);  
   }

   private void showEventDemo(){
      headerLabel.setText("Control in action: Button"); 

      Button okButton = new Button("OK");
      Button submitButton = new Button("Submit");
      Button cancelButton = new Button("Cancel");

      okButton.setActionCommand("OK");
      submitButton.setActionCommand("Submit");
      cancelButton.setActionCommand("Cancel");

      okButton.addActionListener(new ButtonClickListener()); 
      submitButton.addActionListener(new ButtonClickListener()); 
      cancelButton.addActionListener(new ButtonClickListener()); 

      controlPanel.add(okButton);
      controlPanel.add(submitButton);
      controlPanel.add(cancelButton);       

      mainFrame.setVisible(true);  
   }

   private class ButtonClickListener implements ActionListener{
      public void actionPerformed(ActionEvent e) {
         String command = e.getActionCommand();  
         if( command.equals( "OK" ))  {
            statusLabel.setText("Ok Button clicked.");
         }
         else if( command.equals( "Submit" ) )  {
            statusLabel.setText("Submit Button clicked."); 
         }
         else  {
            statusLabel.setText("Cancel Button clicked.");
         }  	
      }		
   }
}

Compile the program using command prompt. Go to D:/ > AWT and type the following command.

D:\AWT>javac com\tutorialspoint\gui\AwtControlDemo.java

If no error comes that means compilation is successful. Run the program using following command.

D:\AWT>java com.tutorialspoint.gui.AwtControlDemo

Verify the following output

AWT Event Handling

AWT Event Classes

The Event classes represent the event. Java provides us various Event classes but we will discuss those which are more frequently used.

EventObject class

It is the root class from which all event state objects shall be derived. All Events are constructed with a reference to the object, the source, that is logically deemed to be the object upon which the Event in question initially occurred upon. This class is defined in java.util package.

Class declaration

Following is the declaration for java.util.EventObject class:

public class EventObject
   extends Object
      implements Serializable

Field

Following are the fields for java.util.EventObject class:

  • protected Object source -- The object on which the Event initially occurred.

Class constructors

S.N.Constructor & Description
1EventObject(Object source)
Constructs a prototypical Event.

Class methods

S.N.Method & Description
1Object getSource()
The object on which the Event initially occurred.
2String toString()
Returns a String representation of this EventObject.

Methods inherited

This class inherits methods from the following classes:

  • java.lang.Object

AWT Event Classes:

Following is the list of commonly used event classes.

AWT AWTEvent Class

It is the root event class for all AWT events. This class and its subclasses supercede the original java.awt.Event class. This class is defined in java.awt package. This class has a method named getID() that can be used to determine the type of event.

Class declaration

Following is the declaration for java.awt.AWTEvent class:

public class AWTEvent
   extends EventObject

Field

Following are the fields for java.awt.AWTEvent class:

  • static int ACTION_FIRST -- The first number in the range of ids used for action events.

  • static long ACTION_EVENT_MASK -- The event mask for selecting action events.

  • static long ADJUSTMENT_EVENT_MASK -- The event mask for selecting adjustment events.

  • static long COMPONENT_EVENT_MASK -- The event mask for selecting component events.

  • protected boolean consumed -- Controls whether or not the event is sent back down to the peer once the source has processed it - false means it's sent to the peer; true means it's not.

  • static long CONTAINER_EVENT_MASK -- The event mask for selecting container events.

  • static long FOCUS_EVENT_MASK -- The event mask for selecting focus events.

  • static long HIERARCHY_BOUNDS_EVENT_MASK -- The event mask for selecting hierarchy bounds events.

  • static long HIERARCHY_EVENT_MASK -- The event mask for selecting hierarchy events.

  • protected int id -- The event's id.

  • static long INPUT_METHOD_EVENT_MASK -- The event mask for selecting input method events.

  • static long INVOCATION_EVENT_MASK -- The event mask for selecting invocation events.

  • static long ITEM_EVENT_MASK -- The event mask for selecting item events.

  • static long KEY_EVENT_MASK -- The event mask for selecting key events.

  • static long MOUSE_EVENT_MASK -- The event mask for selecting mouse events.

  • static long MOUSE_MOTION_EVENT_MASK -- The event mask for selecting mouse motion events.

  • static long MOUSE_WHEEL_EVENT_MASK -- The event mask for selecting mouse wheel events.

  • static long PAINT_EVENT_MASK -- The event mask for selecting paint events.

  • static int RESERVED_ID_MAX -- The maximum value for reserved AWT event IDs.

  • static long TEXT_EVENT_MASK -- The event mask for selecting text events.

  • static long WINDOW_EVENT_MASK -- The event mask for selecting window events.

  • static long WINDOW_FOCUS_EVENT_MASK -- The event mask for selecting window focus events.

  • static long WINDOW_STATE_EVENT_MASK -- The event mask for selecting window state events.

Class constructors

S.N.Constructor & Description
1AWTEvent(Event event)
Constructs an AWTEvent object from the parameters of a 1.0-style event.
2AWTEvent(java.lang.Object source, int id)
Constructs an AWTEvent object with the specified source object and type.

Class methods

S.N.Method & Description
1protected void consume()
Consumes this event, if this event can be consumed.
2int getID()
Returns the event type.
3protected boolean isConsumed()
Returns whether this event has been consumed.
4java.lang.String paramString()
Returns a string representing the state of this Event.
5void setSource(java.lang.Object newSource)
Retargets an event to a new source.
6java.lang.String toString()
Returns a String representation of this object.

Methods inherited

This class inherits methods from the following classes:

  • java.util.EventObject

  • java.lang.Object

AWT ActionEvent Class

This class is defined in java.awt.event package. The ActionEvent is generated when button is clicked or the item of a list is double clicked.

Class declaration

Following is the declaration for java.awt.event.ActionEvent class:

public class ActionEvent
   extends AWTEvent

Field

Following are the fields for java.awt.event.ActionEvent class:

  • static int ACTION_FIRST -- The first number in the range of ids used for action events.

  • static int ACTION_LAST -- The last number in the range of ids used for action events.

  • static int ACTION_PERFORMED -- This event id indicates that a meaningful action occured.

  • static int ALT_MASK -- The alt modifier.

  • static int CTRL_MASK -- The control modifier.

  • static int META_MASK -- The meta modifier.

  • static int SHIFT_MASK -- The shift modifier.

Class constructors

S.N.Constructor & Description
1ActionEvent(java.lang.Object source, int id, java.lang.String command)
Constructs an ActionEvent object.
2ActionEvent(java.lang.Object source, int id, java.lang.String command, int modifiers)
Constructs an ActionEvent object with modifier keys.
3ActionEvent(java.lang.Object source, int id, java.lang.String command, long when, int modifiers)
Constructs an ActionEvent object with the specified modifier keys and timestamp.

Class methods

S.N.Method & Description
1java.lang.String getActionCommand()
Returns the command string associated with this action.
2int getModifiers()
Returns the modifier keys held down during this action event.
3long getWhen()
Returns the timestamp of when this event occurred.
4java.lang.String paramString()
Returns a parameter string identifying this action event.

Methods inherited

This class inherits methods from the following classes:

  • java.awt.AWTEvent

  • java.util.EventObject

  • java.lang.Object

AWT InputEvent Class

The InputEvent class is root event class for all component-level input events. Input events are delivered to listeners before they are processed normally by the source where they originated. This allows listeners and component subclasses to "consume" the event so that the source will not process them in their default manner. For example, consuming mousePressed events on a Button component will prevent the Button from being activated.

Class declaration

Following is the declaration for java.awt.event.InputEvent class:

public abstract class InputEvent
   extends ComponentEvent

Field

Following are the fields for java.awt.event.InputEvent class:

  • static int ALT_DOWN_MASK -- The Alt key extended modifier constant.

  • static int ALT_GRAPH_DOWN_MASK -- The AltGraph key extended modifier constant.

  • static int ALT_GRAPH_MASK -- The AltGraph key modifier constant.

  • static int ALT_MASK -- The Alt key modifier constant.

  • static int BUTTON1_DOWN_MASK -- The Mouse Button1 extended modifier constant.

  • static int BUTTON1_MASK -- The Mouse Button1 modifier constant.

  • static int BUTTON2_DOWN_MASK -- The Mouse Button2 extended modifier constant.

  • static int BUTTON2_MASK -- The Mouse Button2 modifier constant.

  • static int BUTTON3_DOWN_MASK -- The Mouse Button3 extended modifier constant.

  • static int BUTTON3_MASK --The Mouse Button3 modifier constant.

  • static int CTRL_DOWN_MASK -- The Control key extended modifier constant.

  • static int CTRL_MASK -- The Control key modifier constant.

  • static int META_DOWN_MASK -- The Meta key extended modifier constant.

  • static int META_MASK -- The Meta key modifier constant.

  • static int SHIFT_DOWN_MASK -- The Shift key extended modifier constant.

  • static int SHIFT_MASK -- The Shift key modifier constant.

Class methods

S.N.Method & Description
1void consume()
Consumes this event so that it will not be processed in the default manner by the source which originated it.
2int getModifiers()
Returns the modifier mask for this event.
3int getModifiersEx()
Returns the extended modifier mask for this event.
4static String getModifiersExText(int modifiers)
Returns a String describing the extended modifier keys and mouse buttons, such as "Shift", "Button1", or "Ctrl+Shift".
5long getWhen()
Returns the timestamp of when this event occurred.
6boolean isAltDown()
Returns whether or not the Alt modifier is down on this event.
7boolean isAltGraphDown()
Returns whether or not the AltGraph modifier is down on this event.
8boolean isConsumed()
Returns whether or not this event has been consumed.
9boolean isControlDown()
Returns whether or not the Control modifier is down on this event.
10boolean isMetaDown()
Returns whether or not the Meta modifier is down on this event.
11boolean isShiftDown()
Returns whether or not the Shift modifier is down on this event.

Methods inherited

This class inherits methods from the following classes:

  • java.awt.event.ComponentEvent

  • java.awt.AWTEvent

  • java.util.EventObject

  • java.lang.Object

AWT KeyEvent Class

On entering the character the Key event is generated.There are three types of key events which are represented by the integer constants. These key events are following

  • KEY_PRESSED

  • KEY_RELASED

  • KEY_TYPED

Class declaration

Following is the declaration for java.awt.event.KeyEvent class:

public class KeyEvent
   extends InputEvent

Field

Following are the fields for java.awt.InputEvent class:

  • static char CHAR_UNDEFINED --KEY_PRESSED and KEY_RELEASED events which do not map to a valid Unicode character use this for the keyChar value.

  • static int KEY_FIRST --The first number in the range of ids used for key events.

  • static int KEY_LAST --The last number in the range of ids used for key events.

  • static int KEY_LOCATION_LEFT --A constant indicating that the key pressed or released is in the left key location (there is more than one possible location for this key).

  • static int KEY_LOCATION_NUMPAD --A constant indicating that the key event originated on the numeric keypad or with a virtual key corresponding to the numeric keypad.

  • static int KEY_LOCATION_RIGHT -- A constant indicating that the key pressed or released is in the right key location (there is more than one possible location for this key).

  • static int KEY_LOCATION_STANDARD --A constant indicating that the key pressed or released is not distinguished as the left or right version of a key, and did not originate on the numeric keypad (or did not originate with a virtual key corresponding to the numeric keypad).

  • static int KEY_LOCATION_UNKNOWN -- A constant indicating that the keyLocation is indeterminate or not relevant.

  • static int KEY_PRESSED --The "key pressed" event.

  • static int KEY_RELEASED --The "key released" event.

  • static int KEY_TYPED --The "key typed" event.

  • static int VK_0 --VK_0 thru VK_9 are the same as ASCII '0' thru '9' (0x30 - 0x39)

  • static int VK_1

  • static int VK_2

  • static int VK_3

  • static int VK_4

  • static int VK_5

  • static int VK_6

  • static int VK_7

  • static int VK_8

  • static int VK_9

  • static int VK_A --VK_A thru VK_Z are the same as ASCII 'A' thru 'Z' (0x41 - 0x5A)

  • static int VK_ACCEPT --Constant for the Accept or Commit function key.

  • static int VK_ADD

  • static int VK_AGAIN

  • static int VK_ALL_CANDIDATES --Constant for the All Candidates function key.

  • static int VK_ALPHANUMERIC --Constant for the Alphanumeric function key.

  • static int VK_ALT

  • static int VK_ALT_GRAPH --Constant for the AltGraph function key.

  • static int VK_AMPERSAND

  • static int VK_ASTERISK

  • static int VK_AT --constant for the "@" key.

  • static int VK_B

  • static int VK_BACK_QUOTE

  • static int VK_BACK_SLASH --Constant for the back slash key, "\"

  • static int VK_BACK_SPACE

  • static int VK_BEGIN --Constant for the Begin key.

  • static int VK_BRACELEFT

  • static int VK_BRACERIGHT

  • static int VK_C

  • static int VK_CANCEL

  • static int VK_CAPS_LOCK

  • static int VK_CIRCUMFLEX --Constant for the "^" key.

  • static int VK_CLEAR

  • static int VK_CLOSE_BRACKET --Constant for the close bracket key, "]"

  • static int VK_CODE_INPUT --Constant for the Code Input function key.

  • static int VK_COLON --Constant for the ":" key.

  • static int VK_COMMA --Constant for the comma key, ","

  • static int VK_COMPOSE --Constant for the Compose function key.

  • static int VK_CONTEXT_MENU --Constant for the Microsoft Windows Context Menu key.

  • static int VK_CONTROL

  • static int VK_CONVERT -- Constant for the Convert function key.

  • static int VK_COPY

  • static int VK_CUT

  • static int VK_D

  • static int VK_DEAD_ABOVEDOT

  • static int VK_DEAD_ABOVERING

  • static int VK_DEAD_ACUTE

  • static int VK_DEAD_BREVE

  • static int VK_DEAD_CARON

  • static int VK_DEAD_CEDILLA

  • static int VK_DEAD_CIRCUMFLEX

  • static int VK_DEAD_DIAERESIS

  • static int VK_DEAD_DOUBLEACUTE

  • static int VK_DEAD_GRAVE

  • static int VK_DEAD_IOTA

  • static int VK_DEAD_MACRON

  • static int VK_DEAD_OGONEK

  • static int VK_DEAD_SEMIVOICED_SOUND

  • static int VK_DEAD_TILDE

  • static int VK_DEAD_VOICED_SOUND

  • static int VK_DECIMAL

  • static int VK_DELETE

  • static int VK_DIVIDE

  • static int VK_DOLLAR --Constant for the "$" key.

  • static int VK_DOWN -- Constant for the non-numpad down arrow key.

  • static int VK_E

  • static int VK_END

  • static int VK_ENTER

  • static int VK_EQUALS --Constant for the equals key, "="

  • static int VK_ESCAPE

  • static int VK_EURO_SIGN --Constant for the Euro currency sign key.

  • static int VK_EXCLAMATION_MARK --Constant for the "!" key.

  • static int VK_F

  • static int VK_F1 --Constant for the F1 function key.

  • static int VK_F10 --Constant for the F10 function key.

  • static int VK_F11 --Constant for the F11 function key.

  • static int VK_F12 --Constant for the F12 function key.

  • static int VK_F13 --Constant for the F13 function key.

  • static int VK_F14 --Constant for the F14 function key.

  • static int VK_F15 --Constant for the F15 function key.

  • static int VK_F16 --Constant for the F16 function key.

  • static int VK_F17 --Constant for the F17 function key.

  • static int VK_F18 --Constant for the F18 function key.

  • static int VK_F19 --Constant for the F19 function key.

  • static int VK_F2 --Constant for the F2 function key.

  • static int VK_F20 --Constant for the F20 function key.

  • static int VK_F21 -- Constant for the F21 function key.

  • static int VK_F22 --Constant for the F22 function key.

  • static int VK_F23 --Constant for the F23 function key.

  • static int VK_F24 --Constant for the F24 function key.

  • static int VK_F3 --Constant for the F3 function key.

  • static int VK_F4 --Constant for the F4 function key.

  • static int VK_F5 -- Constant for the F5 function key.

  • static int VK_F6 --Constant for the F6 function key.

  • static int VK_F7 --Constant for the F7 function key.

  • static int VK_F8 --Constant for the F8 function key.

  • static int VK_F9 --Constant for the F9 function key.

  • static int VK_FINAL

  • static int VK_FIND

  • static int VK_FULL_WIDTH --Constant for the Full-Width Characters function key.

  • static int VK_G

  • static int VK_GREATER

  • static int VK_H

  • static int VK_HALF_WIDTH --Constant for the Half-Width Characters function key.

  • static int VK_HELP

  • static int VK_HIRAGANA --Constant for the Hiragana function key.

  • static int VK_HOME

  • static int VK_I

  • static int VK_INPUT_METHOD_ON_OFF -- Constant for the input method on/off key.

  • static int VK_INSERT

  • static int VK_INVERTED_EXCLAMATION_MARK --Constant for the inverted exclamation mark key.

  • static int VK_J

  • static int VK_JAPANESE_HIRAGANA --Constant for the Japanese-Hiragana function key.

  • static int VK_JAPANESE_KATAKANA --Constant for the Japanese-Katakana function key.

  • static int VK_JAPANESE_ROMAN --Constant for the Japanese-Roman function key.

  • static int VK_K

  • static int VK_KANA

  • static int VK_KANA_LOCK -- Constant for the locking Kana function key.

  • static int VK_KANJI

  • static int VK_KATAKANA --Constant for the Katakana function key.

  • static int VK_KP_DOWN -- Constant for the numeric keypad down arrow key.

  • static int VK_KP_LEFT --Constant for the numeric keypad left arrow key.

  • static int VK_KP_RIGHT --Constant for the numeric keypad right arrow key.

  • static int VK_KP_UP --Constant for the numeric keypad up arrow key.

  • static int VK_L

  • static int VK_LEFT --Constant for the non-numpad left arrow key.

  • static int VK_LEFT_PARENTHESIS --Constant for the "(" key.

  • static int VK_LESS

  • static int VK_M

  • static int VK_META

  • static int VK_MINUS -- Constant for the minus key, "-"

  • static int VK_MODECHANGE

  • static int VK_MULTIPLY

  • static int VK_N

  • static int VK_NONCONVERT --Constant for the Don't Convert function key.

  • static int VK_NUM_LOCK

  • static int VK_NUMBER_SIGN --Constant for the "#" key.

  • static int VK_NUMPAD0

  • static int VK_NUMPAD1

  • static int VK_NUMPAD2

  • static int VK_NUMPAD3

  • static int VK_NUMPAD4

  • static int VK_NUMPAD5

  • static int VK_NUMPAD6

  • static int VK_NUMPAD7

  • static int VK_NUMPAD8

  • static int VK_NUMPAD9

  • static int VK_O

  • static int VK_OPEN_BRACKET --Constant for the open bracket key, "["

  • static int VK_P

  • static int VK_PAGE_DOWN

  • static int VK_PAGE_UP

  • static int VK_PASTE

  • static int VK_PAUSE

  • static int VK_PERIOD --Constant for the period key, "."

  • static int VK_PLUS -- Constant for the "+" key.

  • static int VK_PREVIOUS_CANDIDATE -- Constant for the Previous Candidate function key.

  • static int VK_PRINTSCREEN

  • static int VK_PROPS

  • static int VK_Q

  • static int VK_QUOTE

  • static int VK_QUOTEDBL

  • static int VK_R

  • static int VK_RIGHT -- Constant for the non-numpad right arrow key.

  • static int VK_RIGHT_PARENTHESIS --Constant for the ")" key.

  • static int VK_ROMAN_CHARACTERS --Constant for the Roman Characters function key.

  • static int VK_S

  • static int VK_SCROLL_LOCK

  • static int VK_SEMICOLON -- Constant for the semicolon key, ";"

  • static int VK_SEPARATER --This constant is obsolete, and is included only for backwards compatibility.

  • static int VK_SEPARATOR --Constant for the Numpad Separator key.

  • static int VK_SHIFT

  • static int VK_SLASH -- Constant for the forward slash key, "/"

  • static int VK_SPACE

  • static int VK_STOP

  • static int VK_SUBTRACT

  • static int VK_T

  • static int VK_TAB

  • static int VK_U

  • static int VK_UNDEFINED -- This value is used to indicate that the keyCode is unknown.

  • static int VK_UNDERSCORE --Constant for the "_" key.

  • static int VK_UNDO

  • static int VK_UP --Constant for the non-numpad up arrow key.

  • static int VK_V

  • static int VK_W

  • static int VK_WINDOWS --Constant for the Microsoft Windows "Windows" key.

  • static int VK_X

  • static int VK_Y

  • static int VK_Z

Class constructors

S.N.Constructor & Description
1KeyEvent(Component source, int id, long when, int modifiers, int keyCode)
Deprecated. as of JDK1.1
2KeyEvent(Component source, int id, long when, int modifiers, int keyCode, char keyChar)
Constructs a KeyEvent object.
3KeyEvent(Component source, int id, long when, int modifiers, int keyCode, char keyChar, int keyLocation)

Class methods

S.N.Method & Description
1char getKeyChar()
Returns the character associated with the key in this event.
2int getKeyCode()
Returns the integer keyCode associated with the key in this event.
3int getKeyLocation()
Returns the location of the key that originated this key event.
4static String getKeyModifiersText(int modifiers)
Returns a String describing the modifier key(s), such as "Shift", or "Ctrl+Shift".
5static String getKeyText(int keyCode)
Returns a String describing the keyCode, such as "HOME", "F1" or "A".
6boolean isActionKey()
Returns whether the key in this event is an "action" key.
7String paramString()
Returns a parameter string identifying this event.
8void setKeyChar(char keyChar)
Set the keyChar value to indicate a logical character.
9void setKeyCode(int keyCode)
Set the keyCode value to indicate a physical key.
10void setModifiers(int modifiers)
Deprecated. as of JDK1.1.4

Methods inherited

This class inherits methods from the following classes:

  • java.awt.event.InputEvent

  • java.awt.event.ComponentEvent

  • java.awt.AWTEvent

  • java.util.EventObject

  • java.lang.Object

AWT MouseEvent Class

This event indicates a mouse action occurred in a component. This low-level event is generated by a component object for Mouse Events and Mouse motion events.

  • a mouse button is pressed

  • a mouse button is released

  • a mouse button is clicked (pressed and released)

  • a mouse cursor enters the unobscured part of component's geometry

  • a mouse cursor exits the unobscured part of component's geometry

  • a mouse is moved

  • the mouse is dragged

Class declaration

Following is the declaration for java.awt.event.MouseEvent class:

public class MouseEvent
   extends InputEvent

Field

Following are the fields for java.awt.event.MouseEvent class:

  • static int BUTTON1 --Indicates mouse button #1; used by getButton()

  • static int BUTTON2 --Indicates mouse button #2; used by getButton()

  • static int BUTTON3 --Indicates mouse button #3; used by getButton()

  • static int MOUSE_CLICKED --The "mouse clicked" event

  • static int MOUSE_DRAGGED --The "mouse dragged" event

  • static int MOUSE_ENTERED --The "mouse entered" event

  • static int MOUSE_EXITED --The "mouse exited" event

  • static int MOUSE_FIRST --The first number in the range of ids used for mouse events

  • static int MOUSE_LAST -- The last number in the range of ids used for mouse events

  • static int MOUSE_MOVED --The "mouse moved" event

  • static int MOUSE_PRESSED -- The "mouse pressed" event

  • static int MOUSE_RELEASED --The "mouse released" event

  • static int MOUSE_WHEEL --The "mouse wheel" event

  • static int NOBUTTON --Indicates no mouse buttons; used by getButton()

  • static int VK_WINDOWS --Constant for the Microsoft Windows "Windows" key.

Class constructors

S.N.Constructor & Description
1MouseEvent(Component source, int id, long when, int modifiers, int x, int y, int clickCount, boolean popupTrigger)
Constructs a MouseEvent object with the specified source component, type, modifiers, coordinates, and click count.
2MouseEvent(Component source, int id, long when, int modifiers, int x, int y, int clickCount, boolean popupTrigger, int button)
Constructs a MouseEvent object with the specified source component, type, modifiers, coordinates, and click count.
3MouseEvent(Component source, int id, long when, int modifiers, int x, int y, int xAbs, int yAbs, int clickCount, boolean popupTrigger, int button)
Constructs a MouseEvent object with the specified source component, type, modifiers, coordinates, absolute coordinates, and click count.

Class methods

S.N.Method & Description
1int getButton()
Returns which, if any, of the mouse buttons has changed state.
2int getClickCount()
Returns the number of mouse clicks associated with this event.
3Point getLocationOnScreen()
Returns the absolute x, y position of the event.
4static String getMouseModifiersText(int modifiers)
Returns a String describing the modifier keys and mouse buttons that were down during the event, such as "Shift", or "Ctrl+Shift".
5Point getPoint()
Returns the x,y position of the event relative to the source component.
6int getX()
Returns the horizontal x position of the event relative to the source component.
7int getXOnScreen()
Returns the absolute horizontal x position of the event.
8int getY()
Returns the vertical y position of the event relative to the source component.
9int getYOnScreen()
Returns the absolute vertical y position of the event.
10boolean isPopupTrigger() Returns whether or not this mouse event is the popup menu trigger event for the platform.
11String paramString()
Returns a parameter string identifying this event.
12void translatePoint(int x, int y)
Translates the event's coordinates to a new position by adding specified x (horizontal) and y (vertical) offsets.

Methods inherited

This class inherits methods from the following classes:

  • java.awt.event.InputEvent

  • java.awt.event.ComponentEvent

  • java.awt.AWTEvent

  • java.util.EventObject

  • java.lang.Object

AWT TextEvent Class

The object of this class represents the text events.The TextEvent is generated when character is entered in the text fields or text area. The TextEvent instance does not include the characters currently in the text component that generated the event rather we are provided with other methods to retrieve that information.

Class declaration

Following is the declaration for java.awt.event.TextEvent class:

public class TextEvent
   extends AWTEvent

Field

Following are the fields for java.awt.event.TextEvent class:

  • static int TEXT_FIRST --The first number in the range of ids used for text events.

  • static int TEXT_LAST --The last number in the range of ids used for text events.

  • static int TEXT_VALUE_CHANGED --This event id indicates that object's text changed.

Class constructors

<0tr>
S.N.Constructor & Description
1TextEvent(Object source, int id)
Constructs a TextEvent object.

Class methods

S.N.Method & Description
1String paramString()
Returns a parameter string identifying this text event.

Methods inherited

This class inherits methods from the following classes:

  • java.awt.AWTEvent

  • java.util.EventObject

  • java.lang.Object

AWT WindowEvent Class

The object of this class represents the change in state of a window.This low-level event is generated by a Window object when it is opened, closed, activated, deactivated, iconified, or deiconified, or when focus is transfered into or out of the Window.

Class declaration

Following is the declaration for java.awt.event.WindowEvent class:

public class WindowEvent
   extends ComponentEvent

Field

Following are the fields for java.awt.event.WindowEvent class:

  • static int WINDOW_ACTIVATED --The window-activated event type.

  • static int WINDOW_CLOSED -- The window closed event.

  • static int WINDOW_CLOSING -- The "window is closing" event.

  • static int WINDOW_DEACTIVATED -- The window-deactivated event type.

  • static int WINDOW_DEICONIFIED -- The window deiconified event type.

  • static int WINDOW_FIRST -- The first number in the range of ids used for window events.

  • static int WINDOW_GAINED_FOCUS -- The window-gained-focus event type.

  • static int WINDOW_ICONIFIED -- The window iconified event.

  • static int WINDOW_LAST -- The last number in the range of ids used for window events.

  • static int WINDOW_LOST_FOCUS -- The window-lost-focus event type.

  • static int WINDOW_OPENED -- The window opened event.

  • static int WINDOW_STATE_CHANGED -- The window-state-changed event type.

Class constructors

<0tr>
S.N.Constructor & Description
1WindowEvent(Window source, int id)
Constructs a WindowEvent object.
2WindowEvent(Window source, int id, int oldState, int newState)
Constructs a WindowEvent object with the specified previous and new window states.
3WindowEvent(Window source, int id, Window opposite)
Constructs a WindowEvent object with the specified opposite Window.
4WindowEvent(Window source, int id, Window opposite, int oldState, int newState)
Constructs a WindowEvent object.

Class methods

S.N.Method & Description
1int getNewState()
For WINDOW_STATE_CHANGED events returns the new state of the window.
2int getOldState()
For WINDOW_STATE_CHANGED events returns the previous state of the window.
3Window getOppositeWindow()
Returns the other Window involved in this focus or activation change.
4Window getWindow()
Returns the originator of the event.
5String paramString()
Returns a parameter string identifying this event.

Methods inherited

This class inherits methods from the following classes:

  • java.awt.event.ComponentEvent

  • java.awt.AWTEvent

  • java.util.EventObject

  • java.lang.Object

AWT AdjustmentEvent Class

Introduction

The Class AdjustmentEvent represents adjustment event emitted by Adjustable objects.

Class declaration

Following is the declaration for java.awt.event.AdjustmentEvent class:

public class AdjustmentEvent
   extends AWTEvent

Field

Following are the fields for java.awt.Component class:

  • static int ADJUSTMENT_FIRST -- Marks the first integer id for the range of adjustment event ids.

  • static int ADJUSTMENT_LAST -- Marks the last integer id for the range of adjustment event ids.

  • static int ADJUSTMENT_VALUE_CHANGED -- The adjustment value changed event.

  • static int BLOCK_DECREMENT -- The block decrement adjustment type.

  • static int BLOCK_INCREMENT -- The block increment adjustment type.

  • static int TRACK -- The absolute tracking adjustment type.

  • static int UNIT_DECREMENT -- The unit decrement adjustment type.

  • static int UNIT_INCREMENT -- The unit increment adjustment type.

Class constructors

S.N.Constructor & Description
1AdjustmentEvent(Adjustable source, int id, int type, int value)
Constructs an AdjustmentEvent object with the specified Adjustable source, event type, adjustment type, and value.
2AdjustmentEvent(Adjustable source, int id, int type, int value, boolean isAdjusting)
Constructs an AdjustmentEvent object with the specified Adjustable source, event type, adjustment type, and value.

Class methods

S.N.Method & Description
1Adjustable getAdjustable()
Returns the Adjustable object where this event originated.
2int getAdjustmentType()
Returns the type of adjustment which caused the value changed event.
3int getValue()
Returns the current value in the adjustment event.
4boolean getValueIsAdjusting()
Returns true if this is one of multiple adjustment events.
5String paramString()
Returns a string representing the state of this Event.

Methods inherited

This interface inherits methods from the following classes:

  • java.awt.AWTEvent

  • java.util.EventObject

  • java.lang.Object

AWT ComponentEvent Class

Introduction

The Class ComponentEvent represents that a component moved, changed size, or changed visibility

Class declaration

Following is the declaration for java.awt.event.ComponentEvent class:

public class ComponentEvent
   extends AWTEvent

Field

Following are the fields for java.awt.Component class:

  • static int COMPONENT_FIRST -- The first number in the range of ids used for component events.

  • static int COMPONENT_HIDDEN --This event indicates that the component was rendered invisible.

  • static int COMPONENT_LAST -- The last number in the range of ids used for component events.

  • static int COMPONENT_MOVED -- This event indicates that the component's position changed.

  • static int COMPONENT_RESIZED -- This event indicates that the component's size changed.

  • static int COMPONENT_SHOWN -- This event indicates that the component was made visible.

Class constructors

S.N.Constructor & Description
1ComponentEvent(Component source, int id)
Constructs a ComponentEvent object.

Class methods

S.N.Method & Description
1Component getComponent()
Returns the originator of the event.
2String paramString()
Returns a parameter string identifying this event.

Methods inherited

This interface inherits methods from the following classes:

  • java.awt.AWTEvent

  • java.util.EventObject

  • java.lang.Object

AWT ContainerEvent Class

Introduction

The Class ContainerEvent represents that a container's contents changed because a component was added or removed.

Class declaration

Following is the declaration for java.awt.event.ContainerEvent class:

public class ContainerEvent
   extends ComponentEvent

Field

Following are the fields for java.awt.Component class:

  • static int COMPONENT_ADDED -- This event indicates that a component was added to the container.

  • static int COMPONENT_REMOVED -- This event indicates that a component was removed from the container.

  • static int CONTAINER_FIRST -- The first number in the range of ids used for container events.

  • static int CONTAINER_LAST -- The last number in the range of ids used for container events.

Class constructors

Class methods

S.N.Constructor & Description
1ContainerEvent(Component source, int id, Component child)
Constructs a ContainerEvent object.
S.N.Method & Description
1Component getChild()
Returns the component that was affected by the event.
2Container getContainer()
Returns the originator of the event.
3String paramString()
Returns a parameter string identifying this event.

Methods inherited

This class inherits methods from the following classes:

  • java.awt.ComponentEvent

  • java.awt.AWTEvent

  • java.util.EventObject

  • java.lang.Object

AWT MouseMotionEvent Class

Introduction

The interface MouseMotionEvent indicates a mouse action occurred in a component. This low-level event is generated by a component object when mouse is dragged or moved.

Class declaration

Following is the declaration for java.awt.event.MouseMotionEvent Class:

public class MouseMotionEvent
   extends InputEvent

Interface methods

S.N.Method & Description
1void mouseDragged(MouseEvent e)
Invoked when a mouse button is pressed on a component and then dragged.
2void mouseMoved(MouseEvent e)
Invoked when the mouse cursor has been moved onto a component but no buttons have been pushed.

Methods inherited

This interface inherits methods from the following classes:

  • java.awt.event.InputEvent

  • java.awt.event.ComponentEvent

  • java.awt.AWTEvent

  • java.util.EventObject

  • java.lang.Object

AWT PaintEvent Class

Introduction

The Class PaintEvent used to ensure that paint/update method calls are serialized along with the other events delivered from the event queue

Class declaration

Following is the declaration for java.awt.event.PaintEvent class:

public class PaintEvent
   extends ComponentEvent

Field

Following are the fields for java.awt.Component class:

  • static int PAINT -- The paint event type.

  • static int PAINT_FIRST -- Marks the first integer id for the range of paint event ids.

  • static int PAINT_LAST -- Marks the last integer id for the range of paint event ids.

  • static int UPDATE -- The update event type.

Class constructors

S.N.Constructor & Description
1PaintEvent(Component source, int id, Rectangle updateRect)
Constructs a PaintEvent object with the specified source component and type.

Class methods

S.N.Method & Description
1Rectangle getUpdateRect()
Returns the rectangle representing the area which needs to be repainted in response to this event.
2String paramString()
Returns a parameter string identifying this event.
3void setUpdateRect(Rectangle updateRect)
Sets the rectangle representing the area which needs to be repainted in response to this event.

Methods inherited

This class inherits methods from the following classes:

  • java.awt.ComponentEvent

  • java.awt.AWTEvent

  • java.util.EventObject

  • java.lang.Object

AWT Event Listeners

The Event listener represent the interfaces responsible to handle events. Java provides us various Event listener classes but we will discuss those which are more frequently used. Every method of an event listener method has a single argument as an object which is subclass of EventObject class. For example, mouse event listener methods will accept instance of MouseEvent, where MouseEvent derives from EventObject.

EventListner interface

It is a marker interface which every listener interface has to extend.This class is defined in java.util package.

Class declaration

Following is the declaration for java.util.EventListener interface:

public interface EventListener

AWT Event Listener Interfaces:

Following is the list of commonly used event listeners.

AWT ActionListener Interface

The class which processes the ActionEvent should implement this interface.The object of that class must be registered with a component. The object can be registered using the addActionListener() method. When the action event occurs, that object's actionPerformed method is invoked.

Interface declaration

Following is the declaration for java.awt.event.ActionListener interface:

public interface ActionListener
   extends EventListener

Interface methods

S.N.Method & Description
1void actionPerformed(ActionEvent e)
Invoked when an action occurs.

Methods inherited

This interface inherits methods from the following interfaces:

  • java.awt.EventListener

ActionListener Example

Create the following java program using any editor of your choice in say D:/ > AWT > com > tutorialspoint > gui >

AwtListenerDemo.java
package com.tutorialspoint.gui;

import java.awt.*;
import java.awt.event.*;

public class AwtListenerDemo {
   private Frame mainFrame;
   private Label headerLabel;
   private Label statusLabel;
   private Panel controlPanel;

   public AwtListenerDemo(){
      prepareGUI();
   }

   public static void main(String[] args){
      AwtListenerDemo  awtListenerDemo = new AwtListenerDemo();  
      awtListenerDemo.showActionListenerDemo();
   }

   private void prepareGUI(){
      mainFrame = new Frame("Java AWT Examples");
      mainFrame.setSize(400,400);
      mainFrame.setLayout(new GridLayout(3, 1));
      mainFrame.addWindowListener(new WindowAdapter() {
         public void windowClosing(WindowEvent windowEvent){
            System.exit(0);
         }        
      });    
   
      headerLabel = new Label();
      headerLabel.setAlignment(Label.CENTER);
      statusLabel = new Label();        
      statusLabel.setAlignment(Label.CENTER);
      statusLabel.setSize(350,100);

      controlPanel = new Panel();
      controlPanel.setLayout(new FlowLayout());

      mainFrame.add(headerLabel);
      mainFrame.add(controlPanel);
      mainFrame.add(statusLabel);
      mainFrame.setVisible(true);  
   }

   private void showActionListenerDemo(){
      headerLabel.setText("Listener in action: ActionListener");      

      ScrollPane panel = new ScrollPane();      
      panel.setBackground(Color.magenta);            

      Button okButton = new Button("OK");

      okButton.addActionListener(new CustomActionListener());        
      panel.add(okButton);
      controlPanel.add(panel);

      mainFrame.setVisible(true); 
   }

   class CustomActionListener implements ActionListener{

      public void actionPerformed(ActionEvent e) {
         statusLabel.setText("Ok Button Clicked.");
      }
   }
}

Compile the program using command prompt. Go to D:/ > AWT and type the following command.

D:\AWT>javac com\tutorialspoint\gui\AwtListenerDemo.java

If no error comes that means compilation is successful. Run the program using following command.

D:\AWT>java com.tutorialspoint.gui.AwtListenerDemo

Verify the following output

AWT ActionListener

AWT ComponentListener Interface

The class which processes the ComponentEvent should implement this interface.The object of that class must be registered with a component. The object can be registered using the addComponentListener() method. Component event are raised for information only.

Interface declaration

Following is the declaration for java.awt.event.ComponentListener interface:

public interface ComponentListener
   extends EventListener

Interface methods

S.N.Method & Description
1void componentHidden(ComponentEvent e)
Invoked when the component has been made invisible.
2void componentMoved(ComponentEvent e)
Invoked when the component's position changes.
3void componentResized(ComponentEvent e)
Invoked when the component's size changes.
4void componentShown(ComponentEvent e)
Invoked when the component has been made visible.

Methods inherited

This interface inherits methods from the following interfaces:

  • java.awt.EventListener

ComponentListener Example

Create the following java program using any editor of your choice in say D:/ > AWT > com > tutorialspoint > gui >

AwtListenerDemo.java
package com.tutorialspoint.gui;

import java.awt.*;
import java.awt.event.*;

public class AwtListenerDemo {
   private Frame mainFrame;
   private Label headerLabel;
   private Label statusLabel;
   private Panel controlPanel;

   public AwtListenerDemo(){
      prepareGUI();
   }

   public static void main(String[] args){
      AwtListenerDemo  awtListenerDemo = new AwtListenerDemo();  
      awtListenerDemo.showComponentListenerDemo();
   }

   private void prepareGUI(){
      mainFrame = new Frame("Java AWT Examples");
      mainFrame.setSize(400,400);
      mainFrame.setLayout(new GridLayout(3, 1));
      mainFrame.addWindowListener(new WindowAdapter() {
         public void windowClosing(WindowEvent windowEvent){
            System.exit(0);
         }        
      });    
   
      headerLabel = new Label();
      headerLabel.setAlignment(Label.CENTER);
      statusLabel = new Label();        
      statusLabel.setAlignment(Label.CENTER);
      statusLabel.setSize(350,100);

      controlPanel = new Panel();
      controlPanel.setLayout(new FlowLayout());

      mainFrame.add(headerLabel);
      mainFrame.add(controlPanel);
      mainFrame.add(statusLabel);
      mainFrame.setVisible(true);  
   }

   private void showComponentListenerDemo(){
      headerLabel.setText("Listener in action: ComponentListener");      

      ScrollPane panel = new ScrollPane();      
      panel.setBackground(Color.magenta);            

      Label msglabel = new Label();
      msglabel.setAlignment(Label.CENTER);
      msglabel.setText("Welcome to TutorialsPoint AWT Tutorial.");
      panel.add(msglabel);

      msglabel.addComponentListener(new CustomComponentListener());      
      controlPanel.add(panel);
      mainFrame.setVisible(true);  
   }

   class CustomComponentListener implements ComponentListener {

      public void componentResized(ComponentEvent e) {
         statusLabel.setText(statusLabel.getText() 
         + e.getComponent().getClass().getSimpleName() + " resized. ");
      }

      public void componentMoved(ComponentEvent e) {
         statusLabel.setText(statusLabel.getText() 
         + e.getComponent().getClass().getSimpleName() + " moved. ");
      }

      public void componentShown(ComponentEvent e) {
         statusLabel.setText(statusLabel.getText() 
         + e.getComponent().getClass().getSimpleName() + " shown. ");
      }

      public void componentHidden(ComponentEvent e) {
         statusLabel.setText(statusLabel.getText() 
         + e.getComponent().getClass().getSimpleName() + " hidden. ");
      }
   }
}

Compile the program using command prompt. Go to D:/ > AWT and type the following command.

D:\AWT>javac com\tutorialspoint\gui\AwtListenerDemo.java

If no error comes that means compilation is successful. Run the program using following command.

D:\AWT>java com.tutorialspoint.gui.AwtListenerDemo

Verify the following output

AWT ComponentListener

AWT ItemListener Interface

The class which processes the ItemEvent should implement this interface.The object of that class must be registered with a component. The object can be registered using the addItemListener() method. When the action event occurs, that object's itemStateChanged method is invoked.

Interface declaration

Following is the declaration for java.awt.event.ItemListener interface:

public interface ItemListener
   extends EventListener

Interface methods

S.N.Method & Description
1void itemStateChanged(ItemEvent e)
Invoked when an item has been selected or deselected by the user.

Methods inherited

This interface inherits methods from the following interfaces:

  • java.awt.EventListener

ItemListener Example

Create the following java program using any editor of your choice in say D:/ > AWT > com > tutorialspoint > gui >

AwtListenerDemo.java
package com.tutorialspoint.gui;

import java.awt.*;
import java.awt.event.*;

public class AwtListenerDemo {
   private Frame mainFrame;
   private Label headerLabel;
   private Label statusLabel;
   private Panel controlPanel;

   public AwtListenerDemo(){
      prepareGUI();
   }

   public static void main(String[] args){
      AwtListenerDemo  awtListenerDemo = new AwtListenerDemo();  
      awtListenerDemo.showItemListenerDemo();
   }

   private void prepareGUI(){
      mainFrame = new Frame("Java AWT Examples");
      mainFrame.setSize(400,400);
      mainFrame.setLayout(new GridLayout(3, 1));
      mainFrame.addWindowListener(new WindowAdapter() {
         public void windowClosing(WindowEvent windowEvent){
            System.exit(0);
         }        
      });    
   
      headerLabel = new Label();
      headerLabel.setAlignment(Label.CENTER);
      statusLabel = new Label();        
      statusLabel.setAlignment(Label.CENTER);
      statusLabel.setSize(350,100);

      controlPanel = new Panel();
      controlPanel.setLayout(new FlowLayout());

      mainFrame.add(headerLabel);
      mainFrame.add(controlPanel);
      mainFrame.add(statusLabel);
      mainFrame.setVisible(true);  
   }

   private void showItemListenerDemo(){
      headerLabel.setText("Listener in action: ItemListener");      
      Checkbox chkApple = new Checkbox("Apple");
      Checkbox chkMango = new Checkbox("Mango");
      Checkbox chkPeer = new Checkbox("Peer");
      
      chkApple.addItemListener(new CustomItemListener());
      chkMango.addItemListener(new CustomItemListener());
      chkPeer.addItemListener(new CustomItemListener());

      controlPanel.add(chkApple);
      controlPanel.add(chkMango);
      controlPanel.add(chkPeer);               
      mainFrame.setVisible(true); 
   }

   class CustomItemListener implements ItemListener {
      public void itemStateChanged(ItemEvent e) {
         statusLabel.setText(e.getItem()
         +" Checkbox: " 
         + (e.getStateChange()==1?"checked":"unchecked"));
      }    
   }
}

Compile the program using command prompt. Go to D:/ > AWT and type the following command.

D:\AWT>javac com\tutorialspoint\gui\AwtListenerDemo.java

If no error comes that means compilation is successful. Run the program using following command.

D:\AWT>java com.tutorialspoint.gui.AwtListenerDemo

Verify the following output

AWT ItemListener

AWT KeyListener Interface

The class which processes the KeyEvent should implement this interface.The object of that class must be registered with a component. The object can be registered using the addKeyListener() method.

Interface declaration

Following is the declaration for java.awt.event.KeyListener interface:

public interface KeyListener
   extends EventListener

Interface methods

S.N.Method & Description
1void keyPressed(KeyEvent e)
Invoked when a key has been pressed.
2void keyReleased(KeyEvent e)
Invoked when a key has been released.
3void keyTyped(KeyEvent e)
Invoked when a key has been typed.

Methods inherited

This interface inherits methods from the following interfaces:

  • java.awt.EventListener

KeyListener Example

Create the following java program using any editor of your choice in say D:/ > AWT > com > tutorialspoint > gui >

AwtListenerDemo.java
package com.tutorialspoint.gui;

import java.awt.*;
import java.awt.event.*;

public class AwtListenerDemo {
   private Frame mainFrame;
   private Label headerLabel;
   private Label statusLabel;
   private Panel controlPanel;
   private TextField textField;
   
   public AwtListenerDemo(){
      prepareGUI();
   }

   public static void main(String[] args){
      AwtListenerDemo  awtListenerDemo = new AwtListenerDemo();  
      awtListenerDemo.showKeyListenerDemo();
   }

   private void prepareGUI(){
      mainFrame = new Frame("Java AWT Examples");
      mainFrame.setSize(400,400);
      mainFrame.setLayout(new GridLayout(3, 1));
      mainFrame.addWindowListener(new WindowAdapter() {
         public void windowClosing(WindowEvent windowEvent){
            System.exit(0);
         }        
      });    
   
      headerLabel = new Label();
      headerLabel.setAlignment(Label.CENTER);
      statusLabel = new Label();        
      statusLabel.setAlignment(Label.CENTER);
      statusLabel.setSize(350,100);

      controlPanel = new Panel();
      controlPanel.setLayout(new FlowLayout());

      mainFrame.add(headerLabel);
      mainFrame.add(controlPanel);
      mainFrame.add(statusLabel);
      mainFrame.setVisible(true);  
   }

   private void showKeyListenerDemo(){
      headerLabel.setText("Listener in action: KeyListener");      

      textField  = new TextField(10);

      textField.addKeyListener(new CustomKeyListener());
      Button okButton = new Button("OK");
      okButton.addActionListener(new ActionListener() {
         public void actionPerformed(ActionEvent e) {
            statusLabel.setText("Entered text: " + textField.getText());                
         }
      });

      controlPanel.add(textField);
      controlPanel.add(okButton);    
      mainFrame.setVisible(true);  
   }

   class CustomKeyListener implements KeyListener{
      public void keyTyped(KeyEvent e) {           
      }

      public void keyPressed(KeyEvent e) {
         if(e.getKeyCode() == KeyEvent.VK_ENTER){
            statusLabel.setText("Entered text: " + textField.getText());
         }
      }

      public void keyReleased(KeyEvent e) {            
      }    
   } 
}

Compile the program using command prompt. Go to D:/ > AWT and type the following command.

D:\AWT>javac com\tutorialspoint\gui\AwtListenerDemo.java

If no error comes that means compilation is successful. Run the program using following command.

D:\AWT>java com.tutorialspoint.gui.AwtListenerDemo

Verify the following output

AWT KeyListener

AWT MouseListener Interface

The class which processes the MouseEvent should implement this interface.The object of that class must be registered with a component. The object can be registered using the addMouseListener() method.

Interface declaration

Following is the declaration for java.awt.event.MouseListener interface:

public interface MouseListener
   extends EventListener

Interface methods

S.N.Method & Description
1void mouseClicked(MouseEvent e)
Invoked when the mouse button has been clicked (pressed and released) on a component.
2void mouseEntered(MouseEvent e)
Invoked when the mouse enters a component.
3void mouseExited(MouseEvent e)
Invoked when the mouse exits a component.
4void mousePressed(MouseEvent e)
Invoked when a mouse button has been pressed on a component.
5void mouseReleased(MouseEvent e)
Invoked when a mouse button has been released on a component.

Methods inherited

This interface inherits methods from the following interfaces:

  • java.awt.EventListener

MouseListener Example

Create the following java program using any editor of your choice in say D:/ > AWT > com > tutorialspoint > gui >

AwtListenerDemo.java
package com.tutorialspoint.gui;

import java.awt.*;
import java.awt.event.*;

public class AwtListenerDemo {
   private Frame mainFrame;
   private Label headerLabel;
   private Label statusLabel;
   private Panel controlPanel;

   public AwtListenerDemo(){
      prepareGUI();
   }

   public static void main(String[] args){
      AwtListenerDemo  awtListenerDemo = new AwtListenerDemo();  
      awtListenerDemo.showMouseListenerDemo();
   }

   private void prepareGUI(){
      mainFrame = new Frame("Java AWT Examples");
      mainFrame.setSize(400,400);
      mainFrame.setLayout(new GridLayout(3, 1));
      mainFrame.addWindowListener(new WindowAdapter() {
         public void windowClosing(WindowEvent windowEvent){
            System.exit(0);
         }        
      });    
   
      headerLabel = new Label();
      headerLabel.setAlignment(Label.CENTER);
      statusLabel = new Label();        
      statusLabel.setAlignment(Label.CENTER);
      statusLabel.setSize(350,100);

      controlPanel = new Panel();
      controlPanel.setLayout(new FlowLayout());

      mainFrame.add(headerLabel);
      mainFrame.add(controlPanel);
      mainFrame.add(statusLabel);
      mainFrame.setVisible(true);  
   }

   private void showMouseListenerDemo(){
      headerLabel.setText("Listener in action: MouseListener");      

      Panel panel = new Panel();      
      panel.setBackground(Color.magenta);
      panel.setLayout(new FlowLayout());        
      panel.addMouseListener(new CustomMouseListener());

      Label msglabel = new Label();
      msglabel.setAlignment(Label.CENTER);
      msglabel.setText("Welcome to TutorialsPoint AWT Tutorial.");

      msglabel.addMouseListener(new CustomMouseListener());
      panel.add(msglabel);

      controlPanel.add(panel);

      mainFrame.setVisible(true);  
   }

   class CustomMouseListener implements MouseListener{

      public void mouseClicked(MouseEvent e) {
         statusLabel.setText("Mouse Clicked: ("
         +e.getX()+", "+e.getY() +")");
      }   

      public void mousePressed(MouseEvent e) {
      }

      public void mouseReleased(MouseEvent e) {
      }

      public void mouseEntered(MouseEvent e) {
      }

      public void mouseExited(MouseEvent e) {
      }
   }
}

Compile the program using command prompt. Go to D:/ > AWT and type the following command.

D:\AWT>javac com\tutorialspoint\gui\AwtListenerDemo.java

If no error comes that means compilation is successful. Run the program using following command.

D:\AWT>java com.tutorialspoint.gui.AwtListenerDemo

Verify the following output

AWT MouseListener

AWT TextListener Interface

The class which processes the TextEvent should implement this interface.The object of that class must be registered with a component. The object can be registered using the addTextListener() method.

Interface declaration

Following is the declaration for java.awt.event.TextListener interface:

public interface TextListener
   extends EventListener

Interface methods

S.N.Method & Description
1void textValueChanged(TextEvent e)
Invoked when the value of the text has changed.

Methods inherited

This interface inherits methods from the following interfaces:

  • java.awt.EventListener

TextListener Example

Create the following java program using any editor of your choice in say D:/ > AWT > com > tutorialspoint > gui >

AwtListenerDemo.java
package com.tutorialspoint.gui;

import java.awt.*;
import java.awt.event.*;

public class AwtListenerDemo {
   private Frame mainFrame;
   private Label headerLabel;
   private Label statusLabel;
   private Panel controlPanel;
   private TextField textField;

   public AwtListenerDemo(){
      prepareGUI();
   }

   public static void main(String[] args){
      AwtListenerDemo  awtListenerDemo = new AwtListenerDemo();  
      awtListenerDemo.showTextListenerDemo();
   }

   private void prepareGUI(){
      mainFrame = new Frame("Java AWT Examples");
      mainFrame.setSize(400,400);
      mainFrame.setLayout(new GridLayout(3, 1));
      mainFrame.addWindowListener(new WindowAdapter() {
         public void windowClosing(WindowEvent windowEvent){
            System.exit(0);
         }        
      });    
   
      headerLabel = new Label();
      headerLabel.setAlignment(Label.CENTER);
      statusLabel = new Label();        
      statusLabel.setAlignment(Label.CENTER);
      statusLabel.setSize(350,100);

      controlPanel = new Panel();
      controlPanel.setLayout(new FlowLayout());

      mainFrame.add(headerLabel);
      mainFrame.add(controlPanel);
      mainFrame.add(statusLabel);
      mainFrame.setVisible(true);  
   }

   private void showTextListenerDemo(){
      headerLabel.setText("Listener in action: TextListener");      

      textField  = new TextField(10);

      textField.addTextListener(new CustomTextListener());
      Button okButton = new Button("OK");
      okButton.addActionListener(new ActionListener() {
         public void actionPerformed(ActionEvent e) {
            statusLabel.setText("Entered text: " 
            + textField.getText());                
         }
      });

      controlPanel.add(textField);
      controlPanel.add(okButton);    
      mainFrame.setVisible(true);  
   }

   class CustomTextListener implements TextListener {
      public void textValueChanged(TextEvent e) {
         statusLabel.setText("Entered text: " + textField.getText());               
      }
   }
}

Compile the program using command prompt. Go to D:/ > AWT and type the following command.

D:\AWT>javac com\tutorialspoint\gui\AwtListenerDemo.java

If no error comes that means compilation is successful. Run the program using following command.

D:\AWT>java com.tutorialspoint.gui.AwtListenerDemo

Verify the following output

AWT TextListener

AWT WindowListener Interface

The class which processes the WindowEvent should implement this interface.The object of that class must be registered with a component. The object can be registered using the addWindowListener() method.

Interface declaration

Following is the declaration for java.awt.event.WindowListener interface:

public interface WindowListener
   extends EventListener

Interface methods

S.N.Method & Description
1void windowActivated(WindowEvent e)
Invoked when the Window is set to be the active Window.
2void windowClosed(WindowEvent e)
Invoked when a window has been closed as the result of calling dispose on the window.
3void windowClosing(WindowEvent e)
Invoked when the user attempts to close the window from the window's system menu.
4void windowDeactivated(WindowEvent e)
Invoked when a Window is no longer the active Window.
5void windowDeiconified(WindowEvent e)
Invoked when a window is changed from a minimized to a normal state.
6void windowIconified(WindowEvent e)
Invoked when a window is changed from a normal to a minimized state.
7void windowOpened(WindowEvent e)
Invoked the first time a window is made visible.

Methods inherited

This interface inherits methods from the following interfaces:

  • java.awt.EventListener

WindowListener Example

Create the following java program using any editor of your choice in say D:/ > AWT > com > tutorialspoint > gui >

AwtListenerDemo.java
package com.tutorialspoint.gui;

import java.awt.*;
import java.awt.event.*;

public class AwtListenerDemo {
   private Frame mainFrame;
   private Label headerLabel;
   private Label statusLabel;
   private Panel controlPanel;

   public AwtListenerDemo(){
      prepareGUI();
   }

   public static void main(String[] args){
      AwtListenerDemo  awtListenerDemo = new AwtListenerDemo();  
      awtListenerDemo.showWindowListenerDemo();
   }

   private void prepareGUI(){
      mainFrame = new Frame("Java AWT Examples");
      mainFrame.setSize(400,400);
      mainFrame.setLayout(new GridLayout(3, 1));
      mainFrame.addWindowListener(new WindowAdapter() {
         public void windowClosing(WindowEvent windowEvent){
            System.exit(0);
         }        
      });    
   
      headerLabel = new Label();
      headerLabel.setAlignment(Label.CENTER);
      statusLabel = new Label();        
      statusLabel.setAlignment(Label.CENTER);
      statusLabel.setSize(350,100);

      controlPanel = new Panel();
      controlPanel.setLayout(new FlowLayout());

      mainFrame.add(headerLabel);
      mainFrame.add(controlPanel);
      mainFrame.add(statusLabel);
      mainFrame.setVisible(true);  
   }

   private void showWindowListenerDemo(){
      headerLabel.setText("Listener in action: WindowListener");      

      Button okButton = new Button("OK");

      aboutFrame = new Frame();
      aboutFrame.setSize(300,200);;
      aboutFrame.setTitle("WindowListener Demo");
      aboutFrame.addWindowListener(new CustomWindowListener());

      Label msgLabel = new Label("Welcome to tutorialspoint.");
      msgLabel.setAlignment(Label.CENTER);
      msgLabel.setSize(100,100);
      aboutFrame.add(msgLabel);
      aboutFrame.setVisible(true);
   }

   class CustomWindowListener implements WindowListener {
      public void windowOpened(WindowEvent e) {
      }

      public void windowClosing(WindowEvent e) {
         aboutFrame.dispose();      
      }
      
      public void windowClosed(WindowEvent e) {
      }

      public void windowIconified(WindowEvent e) {
      }

      public void windowDeiconified(WindowEvent e) {
      }

      public void windowActivated(WindowEvent e) {
      }

      public void windowDeactivated(WindowEvent e) {
      }
   }   
}

Compile the program using command prompt. Go to D:/ > AWT and type the following command.

D:\AWT>javac com\tutorialspoint\gui\AwtListenerDemo.java

If no error comes that means compilation is successful. Run the program using following command.

D:\AWT>java com.tutorialspoint.gui.AwtListenerDemo

Verify the following output

AWT WindowListener

AWT AdjustmentListener Interface

Introduction

The interfaceAdjustmentListener is used for receiving adjustment events. The class that process adjustment events needs to implements this interface.

Class declaration

Following is the declaration for java.awt.event.AdjustmentListener interface:

public interface AdjustmentListener
extends EventListener

Interface methods

S.N.Method & Description
1void adjustmentValueChanged(AdjustmentEvent e)
Invoked when the value of the adjustable has changed.

Methods inherited

This class inherits methods from the following interfaces:

  • java.awt.event.EventListener

AdjustmentListener Example

Create the following java program using any editor of your choice in say D:/ > AWT > com > tutorialspoint > gui >

AwtListenerDemo.java
package com.tutorialspoint.gui;

import java.awt.*;
import java.awt.event.*;

public class AwtListenerDemo {
   private Frame mainFrame;
   private Label headerLabel;
   private Label statusLabel;
   private Panel controlPanel;

   public AwtListenerDemo(){
      prepareGUI();
   }

   public static void main(String[] args){
      AwtListenerDemo  awtListenerDemo = new AwtListenerDemo();  
      awtListenerDemo.showAdjustmentListenerDemo();
   }

   private void prepareGUI(){
      mainFrame = new Frame("Java AWT Examples");
      mainFrame.setSize(400,400);
      mainFrame.setLayout(new GridLayout(3, 1));
      mainFrame.addWindowListener(new WindowAdapter() {
         public void windowClosing(WindowEvent windowEvent){
            System.exit(0);
         }        
      });    
   
      headerLabel = new Label();
      headerLabel.setAlignment(Label.CENTER);
      statusLabel = new Label();        
      statusLabel.setAlignment(Label.CENTER);
      statusLabel.setSize(350,100);

      controlPanel = new Panel();
      controlPanel.setLayout(new FlowLayout());

      mainFrame.add(headerLabel);
      mainFrame.add(controlPanel);
      mainFrame.add(statusLabel);
      mainFrame.setVisible(true);  
   }

   private void showAdjustmentListenerDemo(){
      headerLabel.setText("Listener in action: AdjustmentListener");      

      ScrollPane panel = new ScrollPane();      
      panel.setBackground(Color.magenta);
      panel.getHAdjustable().addAdjustmentListener(new CustomAdjustmentListener());

      Label msglabel = new Label();
      msglabel.setAlignment(Label.CENTER);   
      msglabel.setText("Welcome to TutorialsPoint AWT Tutorial.");
      panel.add(msglabel);
      
      controlPanel.add(panel);
      mainFrame.setVisible(true);  
   }

   class CustomAdjustmentListener implements AdjustmentListener {
      public void adjustmentValueChanged(AdjustmentEvent e) {
         statusLabel.setText("Adjustment value: "+Integer.toString(e.getValue()));
      }
   }
}

Compile the program using command prompt. Go to D:/ > AWT and type the following command.

D:\AWT>javac com\tutorialspoint\gui\AwtListenerDemo.java

If no error comes that means compilation is successful. Run the program using following command.

D:\AWT>java com.tutorialspoint.gui.AwtListenerDemo

Verify the following output

AWT AdjustmentListener

AWT ContainerListener Interface

Introduction

The interfaceContainerListener is used for receiving container events. The class that process container events needs to implements this interface.

Class declaration

Following is the declaration for java.awt.event.ContainerListener interface:

public interface ContainerListener
extends EventListener

Interface methods

S.N.Method & Description
1void componentAdded(ContainerEvent e)
Invoked when a component has been added to the container.
2void componentRemoved(ContainerEvent e)
Invoked when a component has been removed from the container.

Methods inherited

This class inherits methods from the following interfaces:

  • java.awt.event.EventListener

AdjustmentListener Example

Create the following java program using any editor of your choice in say D:/ > AWT > com > tutorialspoint > gui >

AwtListenerDemo.java
package com.tutorialspoint.gui;

import java.awt.*;
import java.awt.event.*;

public class AwtListenerDemo {
   private Frame mainFrame;
   private Label headerLabel;
   private Label statusLabel;
   private Panel controlPanel;

   public AwtListenerDemo(){
      prepareGUI();
   }

   public static void main(String[] args){
      AwtListenerDemo  awtListenerDemo = new AwtListenerDemo();  
      awtListenerDemo.showContainerListenerDemo();
   }

   private void prepareGUI(){
      mainFrame = new Frame("Java AWT Examples");
      mainFrame.setSize(400,400);
      mainFrame.setLayout(new GridLayout(3, 1));
      mainFrame.addWindowListener(new WindowAdapter() {
         public void windowClosing(WindowEvent windowEvent){
            System.exit(0);
         }        
      });    
   
      headerLabel = new Label();
      headerLabel.setAlignment(Label.CENTER);
      statusLabel = new Label();        
      statusLabel.setAlignment(Label.CENTER);
      statusLabel.setSize(350,100);

      controlPanel = new Panel();
      controlPanel.setLayout(new FlowLayout());

      mainFrame.add(headerLabel);
      mainFrame.add(controlPanel);
      mainFrame.add(statusLabel);
      mainFrame.setVisible(true);  
   }

   private void showContainerListenerDemo(){
      headerLabel.setText("Listener in action: ContainerListener");      

      ScrollPane panel = new ScrollPane();      
      panel.setBackground(Color.magenta);            
      panel.addContainerListener(new CustomContainerListener());  

      Label msglabel = new Label();
      msglabel.setAlignment(Label.CENTER);
      msglabel.setText("Welcome to TutorialsPoint AWT Tutorial.");
      panel.add(msglabel);
   
      controlPanel.add(panel);
      mainFrame.setVisible(true);  
   }

   class CustomContainerListener implements ContainerListener {
      public void componentAdded(ContainerEvent e) {
         statusLabel.setText(statusLabel.getText() 
         + e.getComponent().getClass().getSimpleName() + " added. ");
      }

      public void componentRemoved(ContainerEvent e) {
         statusLabel.setText(statusLabel.getText() 
         + e.getComponent().getClass().getSimpleName() + " removed. ");
      }
   }
}

Compile the program using command prompt. Go to D:/ > AWT and type the following command.

D:\AWT>javac com\tutorialspoint\gui\AwtListenerDemo.java

If no error comes that means compilation is successful. Run the program using following command.

D:\AWT>java com.tutorialspoint.gui.AwtListenerDemo

Verify the following output

AWT ContainerListener

AWT MouseMotionListener Interface

Introduction

The interfaceMouseMotionListener is used for receiving mouse motion events on a component. The class that process mouse motion events needs to implements this interface.

Class declaration

Following is the declaration for java.awt.event.MouseMotionListener interface:

public interface MouseMotionListener
extends EventListener

Interface methods

S.N.Method & Description
1void mouseDragged(MouseEvent e)
Invoked when a mouse button is pressed on a component and then dragged.
2void mouseMoved(MouseEvent e)
Invoked when the mouse cursor has been moved onto a component but no buttons have been pushed.

Methods inherited

This class inherits methods from the following interfaces:

  • java.awt.event.EventListener

MouseMotionListener Example

Create the following java program using any editor of your choice in say D:/ > AWT > com > tutorialspoint > gui >

AwtListenerDemo.java
package com.tutorialspoint.gui;

import java.awt.*;
import java.awt.event.*;

public class AwtListenerDemo {
   private Frame mainFrame;
   private Label headerLabel;
   private Label statusLabel;
   private Panel controlPanel;

   public AwtListenerDemo(){
      prepareGUI();
   }

   public static void main(String[] args){
      AwtListenerDemo  awtListenerDemo = new AwtListenerDemo();  
      awtListenerDemo.showMouseMotionListenerDemo();
   }

   private void prepareGUI(){
      mainFrame = new Frame("Java AWT Examples");
      mainFrame.setSize(400,400);
      mainFrame.setLayout(new GridLayout(3, 1));
      mainFrame.addWindowListener(new WindowAdapter() {
         public void windowClosing(WindowEvent windowEvent){
            System.exit(0);
         }        
      });    
   
      headerLabel = new Label();
      headerLabel.setAlignment(Label.CENTER);
      statusLabel = new Label();        
      statusLabel.setAlignment(Label.CENTER);
      statusLabel.setSize(350,100);

      controlPanel = new Panel();
      controlPanel.setLayout(new FlowLayout());

      mainFrame.add(headerLabel);
      mainFrame.add(controlPanel);
      mainFrame.add(statusLabel);
      mainFrame.setVisible(true);  
   }

   private void showMouseMotionListenerDemo(){
      headerLabel.setText("Listener in action: MouseMotionListener");      

      Panel panel = new Panel();      
      panel.setBackground(Color.magenta);
      panel.setLayout(new FlowLayout());        
      panel.addMouseMotionListener(new CustomMouseMotionListener());

      Label msglabel = new Label();
      msglabel.setAlignment(Label.CENTER);
      msglabel.setText("Welcome to TutorialsPoint AWT Tutorial.");
      panel.add(msglabel);

      controlPanel.add(panel);

      mainFrame.setVisible(true);  
   }   

   class CustomMouseMotionListener implements MouseMotionListener {

      public void mouseDragged(MouseEvent e) {
         statusLabel.setText("Mouse Dragged: ("+e.getX()+", "+e.getY() +")");
      }

      public void mouseMoved(MouseEvent e) {
         statusLabel.setText("Mouse Moved: ("+e.getX()+", "+e.getY() +")");
      }    
   }    
}

Compile the program using command prompt. Go to D:/ > AWT and type the following command.

D:\AWT>javac com\tutorialspoint\gui\AwtListenerDemo.java

If no error comes that means compilation is successful. Run the program using following command.

D:\AWT>java com.tutorialspoint.gui.AwtListenerDemo

Verify the following output

AWT MouseMotionListener

AWT FocusListener Interface

Introduction

The interfaceFocusListener is used for receiving keyboard focus events. The class that process focus events needs to implements this interface.

Class declaration

Following is the declaration for java.awt.event.FocusListener interface:

public interface FocusListener
extends EventListener

Interface methods

S.N.Method & Description
1void focusGained(FocusEvent e)
Invoked when a component gains the keyboard focus.
2void focusLost(FocusEvent e)
Invoked when a component loses the keyboard focus.

Methods inherited

This class inherits methods from the following interfaces:

  • java.awt.event.EventListener

FocusListener Example

Create the following java program using any editor of your choice in say D:/ > AWT > com > tutorialspoint > gui >

AwtListenerDemo.java
package com.tutorialspoint.gui;

import java.awt.*;
import java.awt.event.*;

public class AwtListenerDemo {
   private Frame mainFrame;
   private Label headerLabel;
   private Label statusLabel;
   private Panel controlPanel;

   public AwtListenerDemo(){
      prepareGUI();
   }

   public static void main(String[] args){
      AwtListenerDemo  awtListenerDemo = new AwtListenerDemo();  
      awtListenerDemo.showFocusListenerDemo();
   }

   private void prepareGUI(){
      mainFrame = new Frame("Java AWT Examples");
      mainFrame.setSize(400,400);
      mainFrame.setLayout(new GridLayout(3, 1));
      mainFrame.addWindowListener(new WindowAdapter() {
         public void windowClosing(WindowEvent windowEvent){
            System.exit(0);
         }        
      });    
   
      headerLabel = new Label();
      headerLabel.setAlignment(Label.CENTER);
      statusLabel = new Label();        
      statusLabel.setAlignment(Label.CENTER);
      statusLabel.setSize(350,100);

      controlPanel = new Panel();
      controlPanel.setLayout(new FlowLayout());

      mainFrame.add(headerLabel);
      mainFrame.add(controlPanel);
      mainFrame.add(statusLabel);
      mainFrame.setVisible(true);  
   }

       
   private void showFocusListenerDemo(){

      headerLabel.setText("Listener in action: FocusListener");      

      Button okButton = new Button("OK");
      Button cancelButton = new Button("Cancel");
      okButton.addFocusListener(new CustomFocusListener());  
      cancelButton.addFocusListener(new CustomFocusListener());  

      controlPanel.add(okButton);
      controlPanel.add(cancelButton);     
      mainFrame.setVisible(true);  
   }

   class CustomFocusListener implements FocusListener{
      public void focusGained(FocusEvent e) {
         statusLabel.setText(statusLabel.getText() 
         + e.getComponent().getClass().getSimpleName() + " gained focus. ");
      }

      public void focusLost(FocusEvent e) {
         statusLabel.setText(statusLabel.getText() 
         + e.getComponent().getClass().getSimpleName() + " lost focus. ");
      }
   }
}

Compile the program using command prompt. Go to D:/ > AWT and type the following command.

D:\AWT>javac com\tutorialspoint\gui\AwtListenerDemo.java

If no error comes that means compilation is successful. Run the program using following command.

D:\AWT>java com.tutorialspoint.gui.AwtListenerDemo

Verify the following output

AWT focusListener

AWT Event Adapters

Adapters are abstract classes for receiving various events. The methods in these classes are empty. These classes exists as convenience for creating listener objects.

AWT Adapters:

Following is the list of commonly used adapters while listening GUI events in AWT.

AWT FocusAdapter Class

Introduction

The class FocusAdapter is an abstract (adapter) class for receiving keyboard focus events. All methods of this class are empty. This class is convenience class for creating listener objects.

Class declaration

Following is the declaration for java.awt.event.FocusAdapter class:

public abstract class FocusAdapter
   extends Object
      implements FocusListener

Class constructors

S.N.Constructor & Description
1FocusAdapter()

Class methods

S.N.Method & Description
1void focusGained(FocusEvent e)
Invoked when a component gains the keyboard focus.
2focusLost(FocusEvent e)
Invoked when a component loses the keyboard focus.

Methods inherited

This class inherits methods from the following classes:

  • java.lang.Object

FocusAdapter Example

Create the following java program using any editor of your choice in say D:/ > AWT > com > tutorialspoint > gui >

AwtAdapterDemo.java
package com.tutorialspoint.gui;

import java.awt.*;
import java.awt.event.*;

public class AwtAdapterDemo {
   private Frame mainFrame;
   private Label headerLabel;
   private Label statusLabel;
   private Panel controlPanel;

   public AwtAdapterDemo(){
      prepareGUI();
   }

   public static void main(String[] args){
      AwtAdapterDemo  awtAdapterDemo = new AwtAdapterDemo();        
      awtAdapterDemo.showFocusAdapterDemo();
   }

   private void prepareGUI(){
      mainFrame = new Frame("Java AWT Examples");
      mainFrame.setSize(400,400);
      mainFrame.setLayout(new GridLayout(3, 1));
      mainFrame.addWindowListener(new WindowAdapter() {
         public void windowClosing(WindowEvent windowEvent){
            System.exit(0);
         }        
      });    
      headerLabel = new Label();
      headerLabel.setAlignment(Label.CENTER);
      statusLabel = new Label();        
      statusLabel.setAlignment(Label.CENTER);
      statusLabel.setSize(350,100);

      controlPanel = new Panel();
      controlPanel.setLayout(new FlowLayout());

      mainFrame.add(headerLabel);
      mainFrame.add(controlPanel);
      mainFrame.add(statusLabel);
      mainFrame.setVisible(true);  
   }

   private void showFocusAdapterDemo(){

      headerLabel.setText("Listener in action: FocusAdapter");      

      Button okButton = new Button("OK");
      Button cancelButton = new Button("Cancel");
      okButton.addFocusListener(new FocusAdapter(){
         public void focusGained(FocusEvent e) {
            statusLabel.setText(statusLabel.getText() 
            + e.getComponent().getClass().getSimpleName() 
            + " gained focus. ");
         }
      });  
      
      cancelButton.addFocusListener(new FocusAdapter(){
         public void focusLost(FocusEvent e) {
            statusLabel.setText(statusLabel.getText() 
            + e.getComponent().getClass().getSimpleName() 
            + " lost focus. ");
         }
      });  
      
      controlPanel.add(okButton);
      controlPanel.add(cancelButton);     
      mainFrame.setVisible(true);  
   }
}

Compile the program using command prompt. Go to D:/ > AWT and type the following command.

D:\AWT>javac com\tutorialspoint\gui\AwtAdapterDemo.java

If no error comes that means compilation is successful. Run the program using following command.

D:\AWT>java com.tutorialspoint.gui.AwtAdapterDemo

Verify the following output

AWT FocusAdapter

AWT KeyAdapter Class

Introduction

The class KeyAdapter is an abstract (adapter) class for receiving keyboard events. All methods of this class are empty. This class is convenience class for creating listener objects.

Class declaration

Following is the declaration for java.awt.event.KeyAdapter class:

public abstract class KeyAdapter
   extends Object
      implements KeyListener

Class constructors

S.N.Constructor & Description
1KeyAdapter()

Class methods

S.N.Method & Description
1void keyPressed(KeyEvent e)
Invoked when a key has been pressed.
2void keyReleased(KeyEvent e)
Invoked when a key has been released.
3void keyTyped(KeyEvent e)
Invoked when a key has been typed.

Methods inherited

This class inherits methods from the following classes:

  • java.lang.Object

KeyAdapter Example

Create the following java program using any editor of your choice in say D:/ > AWT > com > tutorialspoint > gui >

AwtAdapterDemo.java
package com.tutorialspoint.gui;

import java.awt.*;
import java.awt.event.*;

public class AwtAdapterDemo {
   private Frame mainFrame;
   private Label headerLabel;
   private Label statusLabel;
   private Panel controlPanel;

   public AwtAdapterDemo(){
      prepareGUI();
   }

   public static void main(String[] args){
      AwtAdapterDemo  awtAdapterDemo = new AwtAdapterDemo();        
      awtAdapterDemo.showKeyAdapterDemo();
   }

   private void prepareGUI(){
      mainFrame = new Frame("Java AWT Examples");
      mainFrame.setSize(400,400);
      mainFrame.setLayout(new GridLayout(3, 1));
      mainFrame.addWindowListener(new WindowAdapter() {
         public void windowClosing(WindowEvent windowEvent){
            System.exit(0);
         }        
      });    
      headerLabel = new Label();
      headerLabel.setAlignment(Label.CENTER);
      statusLabel = new Label();        
      statusLabel.setAlignment(Label.CENTER);
      statusLabel.setSize(350,100);

      controlPanel = new Panel();
      controlPanel.setLayout(new FlowLayout());

      mainFrame.add(headerLabel);
      mainFrame.add(controlPanel);
      mainFrame.add(statusLabel);
      mainFrame.setVisible(true);  
   }

   private void showKeyAdapterDemo(){
      headerLabel.setText("Listener in action: KeyAdapter");      

      final TextField textField = new TextField(10);

      textField.addKeyListener(new KeyAdapter() {
         public void keyPressed(KeyEvent e) {                
            if(e.getKeyCode() == KeyEvent.VK_ENTER){
               statusLabel.setText("Entered text: " + textField.getText());
            }
         }        
      });
      Button okButton = new Button("OK");
      okButton.addActionListener(new ActionListener() {
         public void actionPerformed(ActionEvent e) {
            statusLabel.setText("Entered text: " + textField.getText());                
         }
      });

      controlPanel.add(textField);
      controlPanel.add(okButton);    
      mainFrame.setVisible(true);  
   }
}

Compile the program using command prompt. Go to D:/ > AWT and type the following command.

D:\AWT>javac com\tutorialspoint\gui\AwtAdapterDemo.java

If no error comes that means compilation is successful. Run the program using following command.

D:\AWT>java com.tutorialspoint.gui.AwtAdapterDemo

Verify the following output

AWT KeyAdapter

AWT MouseAdapter Class

Introduction

The class MouseAdapter is an abstract (adapter) class for receiving mouse events. All methods of this class are empty. This class is convenience class for creating listener objects.

Class declaration

Following is the declaration for java.awt.event.MouseAdapter class:

public abstract class MouseAdapter
   extends Object
      implements MouseListener, MouseWheelListener, MouseMotionListener

Class constructors

S.N.Constructor & Description
1MouseAdapter()

Class methods

S.N.Method & Description
1void mouseClicked(MouseEvent e)
Invoked when the mouse button has been clicked (pressed and released) on a component.
2void mouseDragged(MouseEvent e)
Invoked when a mouse button is pressed on a component and then dragged.
3void mouseEntered(MouseEvent e)
Invoked when the mouse enters a component.
4void mouseExited(MouseEvent e)
Invoked when the mouse exits a component.
5void mouseMoved(MouseEvent e)
Invoked when the mouse cursor has been moved onto a component but no buttons have been pushed.
6void mousePressed(MouseEvent e)
Invoked when a mouse button has been pressed on a component.
7void mouseReleased(MouseEvent e)
Invoked when a mouse button has been released on a component.
8void mouseWheelMoved(MouseWheelEvent e)
Invoked when the mouse wheel is rotated.

Methods inherited

This class inherits methods from the following classes:

  • java.lang.Object

MouseAdapter Example

Create the following java program using any editor of your choice in say D:/ > AWT > com > tutorialspoint > gui >

AwtAdapterDemo.java
package com.tutorialspoint.gui;

import java.awt.*;
import java.awt.event.*;

public class AwtAdapterDemo {
   private Frame mainFrame;
   private Label headerLabel;
   private Label statusLabel;
   private Panel controlPanel;

   public AwtAdapterDemo(){
      prepareGUI();
   }

   public static void main(String[] args){
      AwtAdapterDemo  awtAdapterDemo = new AwtAdapterDemo();  
      awtAdapterDemo.showMouseAdapterDemo();
   }

   private void prepareGUI(){
      mainFrame = new Frame("Java AWT Examples");
      mainFrame.setSize(400,400);
      mainFrame.setLayout(new GridLayout(3, 1));
      mainFrame.addWindowListener(new WindowAdapter() {
         public void windowClosing(WindowEvent windowEvent){
            System.exit(0);
         }        
      });    
      headerLabel = new Label();
      headerLabel.setAlignment(Label.CENTER);
      statusLabel = new Label();        
      statusLabel.setAlignment(Label.CENTER);
      statusLabel.setSize(350,100);

      controlPanel = new Panel();
      controlPanel.setLayout(new FlowLayout());

      mainFrame.add(headerLabel);
      mainFrame.add(controlPanel);
      mainFrame.add(statusLabel);
      mainFrame.setVisible(true);  
   }

   private void showMouseAdapterDemo(){
      headerLabel.setText("Listener in action: MouseAdapter");      

      Panel panel = new Panel();      
      panel.setBackground(Color.magenta);
      panel.setLayout(new FlowLayout());        
      panel.addMouseListener(new MouseAdapter(){
         public void mouseClicked(MouseEvent e) {
            statusLabel.setText("Mouse Clicked: ("
            +e.getX()+", "+e.getY() +")");
         }                
      });

      Label msglabel = new Label();
      msglabel.setAlignment(Label.CENTER);
      msglabel.setText("Welcome to TutorialsPoint AWT Tutorial.");

      msglabel.addMouseListener(new MouseAdapter(){
         public void mouseClicked(MouseEvent e) {
            statusLabel.setText("Mouse Clicked: ("
            +e.getX()+", "+e.getY() +")");
         }                
      });
      panel.add(msglabel);
      controlPanel.add(panel);
      mainFrame.setVisible(true);  
   }
}

Compile the program using command prompt. Go to D:/ > AWT and type the following command.

D:\AWT>javac com\tutorialspoint\gui\AwtAdapterDemo.java

If no error comes that means compilation is successful. Run the program using following command.

D:\AWT>java com.tutorialspoint.gui.AwtAdapterDemo

Verify the following output

AWT MouseAdapter

AWT MouseMotionAdapter Class

Introduction

The class MouseMotionAdapter is an abstract (adapter) class for receiving mouse motion events. All methods of this class are empty. This class is convenience class for creating listener objects.

Class declaration

Following is the declaration for java.awt.event.MouseMotionAdapter class:

public abstract class MouseMotionAdapter
   extends Object
      implements MouseMotionListener

Class constructors

S.N.Constructor & Description
1MouseMotionAdapter()

Class methods

S.N.Method & Description
1void mouseDragged(MouseEvent e)
Invoked when a mouse button is pressed on a component and then dragged.
2void mouseMoved(MouseEvent e)
Invoked when the mouse cursor has been moved onto a component but no buttons have been pushed.

Methods inherited

This class inherits methods from the following classes:

  • java.lang.Object

MouseMotionAdapter Example

Create the following java program using any editor of your choice in say D:/ > AWT > com > tutorialspoint > gui >

AwtAdapterDemo.java
package com.tutorialspoint.gui;

import java.awt.*;
import java.awt.event.*;

public class AwtAdapterDemo {
   private Frame mainFrame;
   private Label headerLabel;
   private Label statusLabel;
   private Panel controlPanel;

   public AwtAdapterDemo(){
      prepareGUI();
   }

   public static void main(String[] args){
      AwtAdapterDemo  awtAdapterDemo = new AwtAdapterDemo();        
      awtAdapterDemo.showMouseMotionAdapterDemo();
   }

   private void prepareGUI(){
      mainFrame = new Frame("Java AWT Examples");
      mainFrame.setSize(400,400);
      mainFrame.setLayout(new GridLayout(3, 1));
      mainFrame.addWindowListener(new WindowAdapter() {
         public void windowClosing(WindowEvent windowEvent){
            System.exit(0);
         }        
      });    
      headerLabel = new Label();
      headerLabel.setAlignment(Label.CENTER);
      statusLabel = new Label();        
      statusLabel.setAlignment(Label.CENTER);
      statusLabel.setSize(350,100);

      controlPanel = new Panel();
      controlPanel.setLayout(new FlowLayout());

      mainFrame.add(headerLabel);
      mainFrame.add(controlPanel);
      mainFrame.add(statusLabel);
      mainFrame.setVisible(true);  
   }

   private void showMouseMotionAdapterDemo(){
      headerLabel.setText("Listener in action: MouseMotionAdapter");      

      Panel panel = new Panel();      
      panel.setBackground(Color.magenta);
      panel.setLayout(new FlowLayout());        
      panel.addMouseMotionListener(new MouseMotionAdapter(){
         public void mouseMoved(MouseEvent e) {
            statusLabel.setText("Mouse Moved: ("+e.getX()+", "+e.getY() +")");
         }                
      });

      Label msglabel = new Label();
      msglabel.setAlignment(Label.CENTER);
      msglabel.setText("Welcome to TutorialsPoint AWT Tutorial.");
      panel.add(msglabel);

      controlPanel.add(panel);

      mainFrame.setVisible(true);  
   }
}

Compile the program using command prompt. Go to D:/ > AWT and type the following command.

D:\AWT>javac com\tutorialspoint\gui\AwtAdapterDemo.java

If no error comes that means compilation is successful. Run the program using following command.

D:\AWT>java com.tutorialspoint.gui.AwtAdapterDemo

Verify the following output

AWT MouseMotionAdapter

AWT WindowAdapter Class

Introduction

The class WindowAdapter is an abstract (adapter) class for receiving window events. All methods of this class are empty. This class is convenience class for creating listener objects.

Class declaration

Following is the declaration for java.awt.event.WindowAdapter class:

public abstract class WindowAdapter
   extends Object
      implements WindowListener, WindowStateListener, WindowFocusListener

Class constructors

S.N.Constructor & Description
1WindowAdapter()

Class methods

S.N.Method & Description
1void windowActivated(WindowEvent e)
Invoked when a window is activated.
2void windowClosed(WindowEvent e)
Invoked when a window has been closed.
3void windowClosing(WindowEvent e)
Invoked when a window is in the process of being closed.
4void windowDeactivated(WindowEvent e)
Invoked when a window is de-activated.
5void windowDeiconified(WindowEvent e)
Invoked when a window is de-iconified.
6void windowGainedFocus(WindowEvent e)
Invoked when the Window is set to be the focused Window, which means that the Window, or one of its subcomponents, will receive keyboard events.
7void windowIconified(WindowEvent e)
Invoked when a window is iconified.
8void windowLostFocus(WindowEvent e)
Invoked when the Window is no longer the focused Window, which means that keyboard events will no longer be delivered to the Window or any of its subcomponents.
9void windowOpened(WindowEvent e)
Invoked when a window has been opened.
10void windowStateChanged(WindowEvent e)
Invoked when a window state is changed.

Methods inherited

This class inherits methods from the following classes:

  • java.lang.Object

WindowAdapter Example

Create the following java program using any editor of your choice in say D:/ > AWT > com > tutorialspoint > gui >

AwtAdapterDemo.java
package com.tutorialspoint.gui;

import java.awt.*;
import java.awt.event.*;

public class AwtAdapterDemo {
   private Frame mainFrame;
   private Label headerLabel;
   private Label statusLabel;
   private Panel controlPanel;

   public AwtAdapterDemo(){
      prepareGUI();
   }

   public static void main(String[] args){
      AwtAdapterDemo  awtAdapterDemo = new AwtAdapterDemo();        
      awtAdapterDemo.showWindowAdapterDemo();
   }

   private void prepareGUI(){
      mainFrame = new Frame("Java AWT Examples");
      mainFrame.setSize(400,400);
      mainFrame.setLayout(new GridLayout(3, 1));
      mainFrame.addWindowListener(new WindowAdapter() {
         public void windowClosing(WindowEvent windowEvent){
            System.exit(0);
         }        
      });    
      headerLabel = new Label();
      headerLabel.setAlignment(Label.CENTER);
      statusLabel = new Label();        
      statusLabel.setAlignment(Label.CENTER);
      statusLabel.setSize(350,100);

      controlPanel = new Panel();
      controlPanel.setLayout(new FlowLayout());

      mainFrame.add(headerLabel);
      mainFrame.add(controlPanel);
      mainFrame.add(statusLabel);
      mainFrame.setVisible(true);  
   }

   private void showWindowAdapterDemo(){
      headerLabel.setText("Listener in action: WindowAdapter");      

      Button okButton = new Button("OK");

      final Frame aboutFrame = new Frame();
      aboutFrame.setSize(300,200);;
      aboutFrame.setTitle("WindowAdapter Demo");
      aboutFrame.addWindowListener(new WindowAdapter() {
            public void windowClosing(WindowEvent windowEvent){
               aboutFrame.dispose();
         }        
      });    
      Label msgLabel = new Label("Welcome to tutorialspoint.");
      msgLabel.setAlignment(Label.CENTER);
      msgLabel.setSize(100,100);
      aboutFrame.add(msgLabel);
      aboutFrame.setVisible(true);
   }
}

Compile the program using command prompt. Go to D:/ > AWT and type the following command.

D:\AWT>javac com\tutorialspoint\gui\AwtAdapterDemo.java

If no error comes that means compilation is successful. Run the program using following command.

D:\AWT>java com.tutorialspoint.gui.AwtAdapterDemo

Verify the following output

AWT WindowAdapter

AWT Layouts

Introduction

Layout means the arrangement of components within the container. In other way we can say that placing the components at a particular position within the container. The task of layouting the controls is done automatically by the Layout Manager.

Layout Manager

The layout manager automatically positions all the components within the container. If we do not use layout manager then also the components are positioned by the default layout manager. It is possible to layout the controls by hand but it becomes very difficult because of the following two reasons.

  • It is very tedious to handle a large number of controls within the container.

  • Oftenly the width and height information of a component is not given when we need to arrange them.

Java provide us with various layout manager to position the controls. The properties like size,shape and arrangement varies from one layout manager to other layout manager. When the size of the applet or the application window changes the size, shape and arrangement of the components also changes in response i.e. the layout managers adapt to the dimensions of appletviewer or the application window.

The layout manager is associated with every Container object. Each layout manager is an object of the class that implements the LayoutManager interface.

Following are the interfaces and classes defining functionalities of Layout Managers.

AWT LayoutManager Interface

Introduction

The interfaceLayoutManager is used to define the interface for classes that know how to lay out Containers.

Class declaration

Following is the declaration for java.awt.LayoutManager interface:

public interface LayoutManager

Interface methods

S.N.Method & Description
1void addLayoutComponent(String name, Component comp)
If the layout manager uses a per-component string, adds the component comp to the layout, associating it with the string specified by name.
2void layoutContainer(Container parent)
Lays out the specified container.
3Dimension minimumLayoutSize(Container parent)
Calculates the minimum size dimensions for the specified container, given the components it contains.
4Dimension preferredLayoutSize(Container parent)
Calculates the preferred size dimensions for the specified container, given the components it contains.
5void removeLayoutComponent(Component comp)
Removes the specified component from the layout.

AWT LayoutManager2 Interface

Introduction

The interfaceLayoutManger is used to define the interface for classes that know how to lay out Containers based on a layout constraints object.

Class declaration

Following is the declaration for java.awt.LayoutManager2 interface:

public interface LayoutManger2
   extends LayoutManager

Interface methods

S.N.Method & Description
1void addLayoutComponent(Component comp, Object constraints)
Adds the specified component to the layout, using the specified constraint object.
2float getLayoutAlignmentX(Container target)
Returns the alignment along the x axis.
3float getLayoutAlignmentY(Container target)
Returns the alignment along the y axis.
4void invalidateLayout(Container target)
Invalidates the layout, indicating that if the layout manager has cached information it should be discarded.
5Dimension maximumLayoutSize(Container target)
Calculates the maximum size dimensions for the specified container, given the components it contains.

AWT BorderLayout Class

Introduction

The class BorderLayout arranges the components to fit in the five regions: east, west, north, south and center. Each region is can contain only one component and each component in each region is identified by the corresponding constant NORTH, SOUTH, EAST, WEST, and CENTER.

Class declaration

Following is the declaration for java.awt.BorderLayout class:

public class BorderLayout
   extends Object
      implements LayoutManager2, Serializable

Field

Following are the fields for java.awt.BorderLayout class:

  • static String AFTER_LAST_LINE -- Synonym for PAGE_END.

  • static String AFTER_LINE_ENDS -- Synonym for LINE_END.

  • static String BEFORE_FIRST_LINE -- Synonym for PAGE_START.

  • static String BEFORE_LINE_BEGINS -- Synonym for LINE_START.

  • static String CENTER -- The center layout constraint (middle of container).

  • static String EAST -- The east layout constraint (right side of container).

  • static String LINE_END -- The component goes at the end of the line direction for the layout.

  • static String LINE_START -- The component goes at the beginning of the line direction for the layout.

  • static String NORTH -- The north layout constraint (top of container).

  • static String PAGE_END -- The component comes after the last line of the layout's content.

  • static String PAGE_START -- The component comes before the first line of the layout's content.

  • static String SOUTH -- The south layout constraint (bottom of container).

  • static String WEST -- The west layout constraint (left side of container).

Class constructors

S.N.Constructor & Description
1BorderLayout()
Constructs a new border layout with no gaps between components.
2BorderLayout(int hgap, int vgap)
Constructs a border layout with the specified gaps between components.

Class methods

S.N.Method & Description
1void addLayoutComponent(Component comp, Object constraints)
Adds the specified component to the layout, using the specified constraint object.
2void addLayoutComponent(String name, Component comp)
If the layout manager uses a per-component string, adds the component comp to the layout, associating it with the string specified by name.
3int getHgap()
Returns the horizontal gap between components.
4float getLayoutAlignmentX(Container parent)
Returns the alignment along the x axis.
5float getLayoutAlignmentY(Container parent)
Returns the alignment along the y axis.
6int getVgap()
Returns the vertical gap between components.
7void invalidateLayout(Container target)
Invalidates the layout, indicating that if the layout manager has cached information it should be discarded.
8void layoutContainer(Container target)
9Dimension maximumLayoutSize(Container target)
Returns the maximum dimensions for this layout given the components in the specified target container.
10Dimension minimumLayoutSize(Container target)
Determines the minimum size of the target container using this layout manager.
11Dimension preferredLayoutSize(Container target)
Determines the preferred size of the target container using this layout manager, based on the components in the container.
12void removeLayoutComponent(Component comp)
Removes the specified component from this border layout.
13void setHgap(int hgap)
Sets the horizontal gap between components.
14void setVgap(int vgap)
Sets the vertical gap between components.
15String toString()
Returns a string representation of the state of this border layout.

Methods inherited

This class inherits methods from the following classes:

  • java.lang.Object

BorderLayout Example

Create the following java program using any editor of your choice in say D:/ > AWT > com > tutorialspoint > gui >

AwtLayoutDemo.java
package com.tutorialspoint.gui;

import java.awt.*;
import java.awt.event.*;

public class AwtLayoutDemo {
   private Frame mainFrame;
   private Label headerLabel;
   private Label statusLabel;
   private Panel controlPanel;
   private Label msglabel;

   public AwtLayoutDemo(){
      prepareGUI();
   }

   public static void main(String[] args){
      AwtLayoutDemo  awtLayoutDemo = new AwtLayoutDemo();  
      awtLayoutDemo.showBorderLayoutDemo();       
   }
      
   private void prepareGUI(){
      mainFrame = new Frame("Java AWT Examples");
      mainFrame.setSize(400,400);
      mainFrame.setLayout(new GridLayout(3, 1));
      mainFrame.addWindowListener(new WindowAdapter() {
         public void windowClosing(WindowEvent windowEvent){
            System.exit(0);
         }        
      });    
      headerLabel = new Label();
      headerLabel.setAlignment(Label.CENTER);
      statusLabel = new Label();        
      statusLabel.setAlignment(Label.CENTER);
      statusLabel.setSize(350,100);

      msglabel = new Label();
      msglabel.setAlignment(Label.CENTER);
      msglabel.setText("Welcome to TutorialsPoint AWT Tutorial.");

      controlPanel = new Panel();
      controlPanel.setLayout(new FlowLayout());

      mainFrame.add(headerLabel);
      mainFrame.add(controlPanel);
      mainFrame.add(statusLabel);
      mainFrame.setVisible(true);  
   }

   private void showBorderLayoutDemo(){
      headerLabel.setText("Layout in action: BorderLayout");      

      Panel panel = new Panel();
      panel.setBackground(Color.darkGray);
      panel.setSize(300,300);
      BorderLayout layout = new BorderLayout();
      layout.setHgap(10);
      layout.setVgap(10);
      panel.setLayout(layout);        
	  
      panel.add(new Button("Center"),BorderLayout.CENTER);
      panel.add(new Button("Line Start"),BorderLayout.LINE_START); 
      panel.add(new Button("Line End"),BorderLayout.LINE_END);
      panel.add(new Button("East"),BorderLayout.EAST);   
      panel.add(new Button("West"),BorderLayout.WEST); 
      panel.add(new Button("North"),BorderLayout.NORTH); 
      panel.add(new Button("South"),BorderLayout.SOUTH); 

      controlPanel.add(panel);

      mainFrame.setVisible(true);  
   }
}

Compile the program using command prompt. Go to D:/ > AWT and type the following command.

D:\AWT>javac com\tutorialspoint\gui\AwtlayoutDemo.java

If no error comes that means compilation is successful. Run the program using following command.

D:\AWT>java com.tutorialspoint.gui.AwtlayoutDemo

Verify the following output

AWT BorderLayout

AWT CardLayout Class

Introduction

The class CardLayout arranges 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.

Class declaration

Following is the declaration for java.awt.CardLayout class:

public class CardLayout
   extends Object
      implements LayoutManager2, Serializable

Class constructors

S.N.Constructor & Description
1CardLayout()
Creates a new card layout with gaps of size zero.
2CardLayout(int hgap, int vgap)
Creates a new card layout with the specified horizontal and vertical gaps.

Class methods

S.N.Method & Description
1void addLayoutComponent(Component comp, Object constraints)
Adds the specified component to this card layout's internal table of names.
2void addLayoutComponent(String name, Component comp)
If the layout manager uses a per-component string, adds the component comp to the layout, associating it with the string specified by name.
3void first(Container parent)
Flips to the first card of the container.
4int getHgap()
Gets the horizontal gap between components.
5float getLayoutAlignmentX(Container parent)
Returns the alignment along the x axis.
6float getLayoutAlignmentY(Container parent)
Returns the alignment along the y axis.
7int getVgap()
Gets the vertical gap between components.
8void invalidateLayout(Container target)
Invalidates the layout, indicating that if the layout manager has cached information it should be discarded.
9void last(Container parent)
Flips to the last card of the container.
10void layoutContainer(Container parent)
Lays out the specified container using this card layout.
11Dimension maximumLayoutSize(Container target)
Returns the maximum dimensions for this layout given the components in the specified target container.
12Dimension minimumLayoutSize(Container parent)
Calculates the minimum size for the specified panel.
13void next(Container parent)
Flips to the next card of the specified container.
14Dimension preferredLayoutSize(Container parent)
Determines the preferred size of the container argument using this card layout.
15void previous(Container parent)
Flips to the previous card of the specified container.
16void removeLayoutComponent(Component comp)
Removes the specified component from the layout.
17void setHgap(int hgap)
Sets the horizontal gap between components.
18void setVgap(int vgap)
Sets the vertical gap between components.
19void show(Container parent, String name)
Flips to the component that was added to this layout with the specified name, using addLayoutComponent.
20String toString()
Returns a string representation of the state of this card layout.

Methods inherited

This class inherits methods from the following classes:

  • java.lang.Object

CardLayout Example

Create the following java program using any editor of your choice in say D:/ > AWT > com > tutorialspoint > gui >

AwtLayoutDemo.java
package com.tutorialspoint.gui;

import java.awt.*;
import java.awt.event.*;

public class AwtLayoutDemo {
   private Frame mainFrame;
   private Label headerLabel;
   private Label statusLabel;
   private Panel controlPanel;
   private Label msglabel;

   public AwtLayoutDemo(){
      prepareGUI();
   }

   public static void main(String[] args){
      AwtLayoutDemo  awtLayoutDemo = new AwtLayoutDemo();  
      awtLayoutDemo.showCardLayoutDemo();       
   }
      
   private void prepareGUI(){
      mainFrame = new Frame("Java AWT Examples");
      mainFrame.setSize(400,400);
      mainFrame.setLayout(new GridLayout(3, 1));
      mainFrame.addWindowListener(new WindowAdapter() {
         public void windowClosing(WindowEvent windowEvent){
            System.exit(0);
         }        
      });    
      headerLabel = new Label();
      headerLabel.setAlignment(Label.CENTER);
      statusLabel = new Label();        
      statusLabel.setAlignment(Label.CENTER);
      statusLabel.setSize(350,100);

      msglabel = new Label();
      msglabel.setAlignment(Label.CENTER);
      msglabel.setText("Welcome to TutorialsPoint AWT Tutorial.");

      controlPanel = new Panel();
      controlPanel.setLayout(new FlowLayout());

      mainFrame.add(headerLabel);
      mainFrame.add(controlPanel);
      mainFrame.add(statusLabel);
      mainFrame.setVisible(true);  
   }

   private void showCardLayoutDemo(){
      headerLabel.setText("Layout in action: CardLayout");      

      final Panel panel = new Panel();
      panel.setBackground(Color.CYAN);
      panel.setSize(300,300);

      CardLayout layout = new CardLayout();
      layout.setHgap(10);
      layout.setVgap(10);
      panel.setLayout(layout);        

      Panel buttonPanel = new Panel(new FlowLayout());

      buttonPanel.add(new Button("OK"));
      buttonPanel.add(new Button("Cancel"));    

      Panel textBoxPanel = new Panel(new FlowLayout());

      textBoxPanel.add(new Label("Name:"));
      textBoxPanel.add(new TextField(20));

      panel.add("Button", buttonPanel);
      panel.add("Text", textBoxPanel);

      Choice choice = new Choice();
      choice.add("Button");
      choice.add("Text");

      choice.addItemListener(new ItemListener() {
         public void itemStateChanged(ItemEvent e) {
            CardLayout cardLayout = (CardLayout)(panel.getLayout());
            cardLayout.show(panel, (String)e.getItem());
         }
      });
      controlPanel.add(choice);
      controlPanel.add(panel);

      mainFrame.setVisible(true);  
   }
}

Compile the program using command prompt. Go to D:/ > AWT and type the following command.

D:\AWT>javac com\tutorialspoint\gui\AwtlayoutDemo.java

If no error comes that means compilation is successful. Run the program using following command.

D:\AWT>java com.tutorialspoint.gui.AwtlayoutDemo

Verify the following output

AWT CardLayout

AWT FlowLayout Class

Introduction

The class FlowLayout components in a left-to-right flow.

Class declaration

Following is the declaration for java.awt.FlowLayout class:

public class FlowLayout
   extends Object
      implements LayoutManager, Serializable

Field

Following are the fields for java.awt.BorderLayout class:

  • static int CENTER -- This value indicates that each row of components should be centered.

  • static int LEADING -- This value indicates that each row of components should be justified to the leading edge of the container's orientation, for example, to the left in left-to-right orientations.

  • static int LEFT -- This value indicates that each row of components should be left-justified.

  • static int RIGHT -- This value indicates that each row of components should be right-justified.

  • static int TRAILING -- This value indicates that each row of components should be justified to the trailing edge of the container's orientation, for example, to the right in left-to-right orientations.

Class constructors

S.N.Constructor & Description
1FlowLayout()
Constructs a new FlowLayout with a centered alignment and a default 5-unit horizontal and vertical gap.
2FlowLayout(int align)
Constructs a new FlowLayout with the specified alignment and a default 5-unit horizontal and vertical gap.
3FlowLayout(int align, int hgap, int vgap)
Creates a new flow layout manager with the indicated alignment and the indicated horizontal and vertical gaps.

Class methods

S.N.Method & Description
1void addLayoutComponent(String name, Component comp)
Adds the specified component to the layout.
2int getAlignment()
Gets the alignment for this layout.
3int getHgap()
Gets the horizontal gap between components.
4int getVgap()
Gets the vertical gap between components.
5void layoutContainer(Container target)
Lays out the container.
6Dimension minimumLayoutSize(Container target)
Returns the minimum dimensions needed to layout the visible components contained in the specified target container.
7Dimension preferredLayoutSize(Container target)
Returns the preferred dimensions for this layout given the visible components in the specified target container.
8void removeLayoutComponent(Component comp)
Removes the specified component from the layout.
9void setAlignment(int align)
Sets the alignment for this layout.
10void setHgap(int hgap)
Sets the horizontal gap between components.
11void setVgap(int vgap)
Sets the vertical gap between components.
12String toString()
Returns a string representation of this FlowLayout object and its values.

Methods inherited

This class inherits methods from the following classes:

  • java.lang.Object

FlowLayout Example

Create the following java program using any editor of your choice in say D:/ > AWT > com > tutorialspoint > gui >

AwtLayoutDemo.java
package com.tutorialspoint.gui;

import java.awt.*;
import java.awt.event.*;

public class AwtLayoutDemo {
   private Frame mainFrame;
   private Label headerLabel;
   private Label statusLabel;
   private Panel controlPanel;
   private Label msglabel;

   public AwtLayoutDemo(){
      prepareGUI();
   }

   public static void main(String[] args){
      AwtLayoutDemo  awtLayoutDemo = new AwtLayoutDemo();  
      awtLayoutDemo.showFlowLayoutDemo();       
   }
      
   private void prepareGUI(){
      mainFrame = new Frame("Java AWT Examples");
      mainFrame.setSize(400,400);
      mainFrame.setLayout(new GridLayout(3, 1));
      mainFrame.addWindowListener(new WindowAdapter() {
         public void windowClosing(WindowEvent windowEvent){
            System.exit(0);
         }        
      });    
      headerLabel = new Label();
      headerLabel.setAlignment(Label.CENTER);
      statusLabel = new Label();        
      statusLabel.setAlignment(Label.CENTER);
      statusLabel.setSize(350,100);

      msglabel = new Label();
      msglabel.setAlignment(Label.CENTER);
      msglabel.setText("Welcome to TutorialsPoint AWT Tutorial.");

      controlPanel = new Panel();
      controlPanel.setLayout(new FlowLayout());

      mainFrame.add(headerLabel);
      mainFrame.add(controlPanel);
      mainFrame.add(statusLabel);
      mainFrame.setVisible(true);  
   }

   private void showFlowLayoutDemo(){
      headerLabel.setText("Layout in action: FlowLayout");      

      Panel panel = new Panel();
      panel.setBackground(Color.darkGray);
      panel.setSize(200,200);
      FlowLayout layout = new FlowLayout();
      layout.setHgap(10);              
      layout.setVgap(10);
      panel.setLayout(layout);        
      panel.add(new Button("OK"));
      panel.add(new Button("Cancel"));       

      controlPanel.add(panel);

      mainFrame.setVisible(true);  
   }
}

Compile the program using command prompt. Go to D:/ > AWT and type the following command.

D:\AWT>javac com\tutorialspoint\gui\AwtlayoutDemo.java

If no error comes that means compilation is successful. Run the program using following command.

D:\AWT>java com.tutorialspoint.gui.AwtlayoutDemo

Verify the following output

AWT FlowLayout

AWT GridLayout Class

Introduction

The class GridLayout arranges components in a rectangular grid.

Class declaration

Following is the declaration for java.awt.GridLayout class:

public class GridLayout
   extends Object
      implements LayoutManager, Serializable

Class constructors

S.N.Constructor & Description
1GridLayout()
Creates a grid layout with a default of one column per component, in a single row.
2GridLayout(int rows, int cols)
Creates a grid layout with the specified number of rows and columns.
3GridLayout(int rows, int cols, int hgap, int vgap)
Creates a grid layout with the specified number of rows and columns.

Class methods

S.N.Method & Description
1void addLayoutComponent(String name, Component comp)
Adds the specified component with the specified name to the layout.
2int getColumns()
Gets the number of columns in this layout.
3int getHgap()
Gets the horizontal gap between components.
4int getRows()
Gets the number of rows in this layout.
5int getVgap()
Gets the vertical gap between components.
6void layoutContainer(Container parent)
Lays out the specified container using this layout.
7Dimension minimumLayoutSize(Container parent)
Determines the minimum size of the container argument using this grid layout.
8Dimension preferredLayoutSize(Container parent)
Determines the preferred size of the container argument using this grid layout.
9void removeLayoutComponent(Component comp)
Removes the specified component from the layout.
10void setColumns(int cols)
Sets the number of columns in this layout to the specified value.
11void setHgap(int hgap)
Sets the horizontal gap between components to the specified value.
12void setRows(int rows)
Sets the number of rows in this layout to the specified value.
13void setVgap(int vgap)
Sets the vertical gap between components to the specified value.
14String toString()
Returns the string representation of this grid layout's values.

Methods inherited

This class inherits methods from the following classes:

  • java.lang.Object

GridLayout Example

Create the following java program using any editor of your choice in say D:/ > AWT > com > tutorialspoint > gui >

AwtLayoutDemo.java
package com.tutorialspoint.gui;

import java.awt.*;
import java.awt.event.*;

public class AwtLayoutDemo {
   private Frame mainFrame;
   private Label headerLabel;
   private Label statusLabel;
   private Panel controlPanel;
   private Label msglabel;

   public AwtLayoutDemo(){
      prepareGUI();
   }

   public static void main(String[] args){
      AwtLayoutDemo  awtLayoutDemo = new AwtLayoutDemo();  
      awtLayoutDemo.showGridLayoutDemo();       
   }
      
   private void prepareGUI(){
      mainFrame = new Frame("Java AWT Examples");
      mainFrame.setSize(400,400);
      mainFrame.setLayout(new GridLayout(3, 1));
      mainFrame.addWindowListener(new WindowAdapter() {
         public void windowClosing(WindowEvent windowEvent){
            System.exit(0);
         }        
      });    
      headerLabel = new Label();
      headerLabel.setAlignment(Label.CENTER);
      statusLabel = new Label();        
      statusLabel.setAlignment(Label.CENTER);
      statusLabel.setSize(350,100);

      msglabel = new Label();
      msglabel.setAlignment(Label.CENTER);
      msglabel.setText("Welcome to TutorialsPoint AWT Tutorial.");

      controlPanel = new Panel();
      controlPanel.setLayout(new FlowLayout());

      mainFrame.add(headerLabel);
      mainFrame.add(controlPanel);
      mainFrame.add(statusLabel);
      mainFrame.setVisible(true);  
   }

   private void showGridLayoutDemo(){
      headerLabel.setText("Layout in action: GridLayout");      

      Panel panel = new Panel();
      panel.setBackground(Color.darkGray);
      panel.setSize(300,300);
      GridLayout layout = new GridLayout(0,3);
      layout.setHgap(10);
      layout.setVgap(10);
      
      panel.setLayout(layout);        
      panel.add(new Button("Button 1"));
      panel.add(new Button("Button 2")); 
      panel.add(new Button("Button 3")); 
      panel.add(new Button("Button 4")); 
      panel.add(new Button("Button 5")); 
      controlPanel.add(panel);
      mainFrame.setVisible(true);  
   }
}

Compile the program using command prompt. Go to D:/ > AWT and type the following command.

D:\AWT>javac com\tutorialspoint\gui\AwtlayoutDemo.java

If no error comes that means compilation is successful. Run the program using following command.

D:\AWT>java com.tutorialspoint.gui.AwtlayoutDemo

Verify the following output

AWT GridLayout

AWT GridBagLayout Class

Introduction

The class GridBagLayout arranges components in a horizontal and vertical manner.

Class declaration

Following is the declaration for java.awt.GridBagLayout class:

public class GridBagLayout
   extends Object
      implements LayoutManager2, Serializable

Field

Following are the fields for java.awt.BorderLayout class:

  • double[] columnWeights -- This field holds the overrides to the column weights.

  • int[] columnWidths -- This field holds the overrides to the column minimum width.

  • protected Hashtable comptable -- This hashtable maintains the association between a component and its gridbag constraints.

  • protected GridBagConstraints defaultConstraints -- This field holds a gridbag constraints instance containing the default values, so if a component does not have gridbag constraints associated with it, then the component will be assigned a copy of the defaultConstraints.

  • protected java.awt.GridBagLayoutInfo layoutInfo -- This field holds the layout information for the gridbag.

  • protected static int MAXGRIDSIZE -- The maximum number of grid positions (both horizontally and vertically) that can be laid out by the grid bag layout.

  • protected static int MINSIZE -- The smallest grid that can be laid out by the grid bag layout.

  • protected static int PREFERREDSIZE -- The preferred grid size that can be laid out by the grid bag layout.

  • int[] rowHeights -- This field holds the overrides to the row minimum heights.

  • double[] rowWeights -- This field holds the overrides to the row weights.

Class constructors

S.N.Constructor & Description
1GridBagLayout()
Creates a grid bag layout manager.

Class methods

S.N.Method & Description
1void addLayoutComponent(Component comp, Object constraints)
Adds the specified component to the layout, using the specified constraints object.
2void addLayoutComponent(String name, Component comp)
Adds the specified component with the specified name to the layout.
3protected void adjustForGravity(GridBagConstraints constraints, Rectangle r)
Adjusts the x, y, width, and height fields to the correct values depending on the constraint geometry and pads.
4protected void AdjustForGravity(GridBagConstraints constraints, Rectangle r)
This method is obsolete and supplied for backwards compatability only; new code should call adjustForGravity instead.
5protected void arrangeGrid(Container parent)
Lays out the grid.
6protected void ArrangeGrid(Container parent)
This method is obsolete and supplied for backwards compatability only; new code should call arrangeGrid instead.
7GridBagConstraints getConstraints(Component comp)
Gets the constraints for the specified component.
8float getLayoutAlignmentX(Container parent)
Returns the alignment along the x axis.
9float getLayoutAlignmentY(Container parent)
Returns the alignment along the y axis.
10int[][] getLayoutDimensions()
Determines column widths and row heights for the layout grid.
11protected java.awt.GridBagLayoutInfo getLayoutInfo(Container parent, int sizeflag)
Fills in an instance of GridBagLayoutInfo for the current set of managed children.
12protected java.awt.GridBagLayoutInfo GetLayoutInfo(Container parent, int sizeflag)
This method is obsolete and supplied for backwards compatability only; new code should call getLayoutInfo instead.
13Point getLayoutOrigin()
Determines the origin of the layout area, in the graphics coordinate space of the target container.
14double[][] getLayoutWeights()
Determines the weights of the layout grid's columns and rows.
15protected Dimension getMinSize(Container parent, java.awt.GridBagLayoutInfo info)
Figures out the minimum size of the master based on the information from getLayoutInfo().
16protected Dimension GetMinSize(Container parent, java.awt.GridBagLayoutInfo info)
This method is obsolete and supplied for backwards compatability only; new code should call getMinSize instead.
17void invalidateLayout(Container target)
Invalidates the layout, indicating that if the layout manager has cached information it should be discarded.
18void layoutContainer(Container parent)
Lays out the specified container using this grid bag layout.
19Point location(int x, int y)
Determines which cell in the layout grid contains the point specified by (x, y).
20protected GridBagConstraints lookupConstraints(Component comp)
Retrieves the constraints for the specified component.
21Dimension maximumLayoutSize(Container target)
Returns the maximum dimensions for this layout given the components in the specified target container.
22Dimension minimumLayoutSize(Container parent)
Determines the minimum size of the parent container using this grid bag layout.
23Dimension preferredLayoutSize(Container parent)
Determines the preferred size of the parent container using this grid bag layout.
24void removeLayoutComponent(Component comp)
Removes the specified component from this layout.
25void setConstraints(Component comp, GridBagConstraints constraints)
Sets the constraints for the specified component in this layout.
26String toString()
Returns a string representation of this grid bag layout's values.

Methods inherited

This class inherits methods from the following classes:

  • java.lang.Object

GridBagLayout Example

Create the following java program using any editor of your choice in say D:/ > AWT > com > tutorialspoint > gui >

AwtLayoutDemo.java
package com.tutorialspoint.gui;

import java.awt.*;
import java.awt.event.*;

public class AwtLayoutDemo {
   private Frame mainFrame;
   private Label headerLabel;
   private Label statusLabel;
   private Panel controlPanel;
   private Label msglabel;

   public AwtLayoutDemo(){
      prepareGUI();
   }

   public static void main(String[] args){
      AwtLayoutDemo  awtLayoutDemo = new AwtLayoutDemo();  
      awtLayoutDemo.showGridBagLayoutDemo();       
   }
      
   private void prepareGUI(){
      mainFrame = new Frame("Java AWT Examples");
      mainFrame.setSize(400,400);
      mainFrame.setLayout(new GridLayout(3, 1));
      mainFrame.addWindowListener(new WindowAdapter() {
         public void windowClosing(WindowEvent windowEvent){
            System.exit(0);
         }        
      });    
      headerLabel = new Label();
      headerLabel.setAlignment(Label.CENTER);
      statusLabel = new Label();        
      statusLabel.setAlignment(Label.CENTER);
      statusLabel.setSize(350,100);

      msglabel = new Label();
      msglabel.setAlignment(Label.CENTER);
      msglabel.setText("Welcome to TutorialsPoint AWT Tutorial.");

      controlPanel = new Panel();
      controlPanel.setLayout(new FlowLayout());

      mainFrame.add(headerLabel);
      mainFrame.add(controlPanel);
      mainFrame.add(statusLabel);
      mainFrame.setVisible(true);  
   }

   private void showGridBagLayoutDemo(){
      headerLabel.setText("Layout in action: GridBagLayout");      

      Panel panel = new Panel();
      panel.setBackground(Color.darkGray);
      panel.setSize(300,300);
      GridBagLayout layout = new GridBagLayout();

      panel.setLayout(layout);        
      GridBagConstraints gbc = new GridBagConstraints();

      gbc.fill = GridBagConstraints.HORIZONTAL;
      gbc.gridx = 0;
      gbc.gridy = 0;
      panel.add(new Button("Button 1"),gbc);

      gbc.gridx = 1;
      gbc.gridy = 0;
      panel.add(new Button("Button 2"),gbc); 

      gbc.fill = GridBagConstraints.HORIZONTAL;
      gbc.ipady = 20;   
      gbc.gridx = 0;
      gbc.gridy = 1;
      panel.add(new Button("Button 3"),gbc); 

      gbc.gridx = 1;
      gbc.gridy = 1;       
      panel.add(new Button("Button 4"),gbc);  

      gbc.gridx = 0;
      gbc.gridy = 2;      
      gbc.fill = GridBagConstraints.HORIZONTAL;
      gbc.gridwidth = 2;
      panel.add(new Button("Button 5"),gbc);  

      controlPanel.add(panel);

      mainFrame.setVisible(true);  
   }
}

Compile the program using command prompt. Go to D:/ > AWT and type the following command.

D:\AWT>javac com\tutorialspoint\gui\AwtlayoutDemo.java

If no error comes that means compilation is successful. Run the program using following command.

D:\AWT>java com.tutorialspoint.gui.AwtlayoutDemo

Verify the following output

AWT GridBagLayout

AWT Containers

Containers are integral part of AWT GUI components. A container provides a space where a component can be located. A Container in AWT is a component itself and it adds the capability to add component to itself. Following are noticable points to be considered.

  • Sub classes of Container are called as Containter. For example Panel, Frame and Window.

  • Container can add only Component to itself.

  • A default layout is present in each container which can be overridden using setLayout method.

AWT Container Class

Introduction

The class Container is the super class for the containers of AWT. Container object can contain other AWT components.

Class declaration

Following is the declaration for java.awt.Container class:

public class Container
   extends Component

Class constructors

S.N.Constructor & Description
1Container()
This creates a new Container.

Class methods

S.N.Method & Description
1Component add(Component comp)
Appends the specified component to the end of this container.
2Component add(Component comp, int index)
Adds the specified component to this container at the given position.
3void add(Component comp, Object constraints)
Adds the specified component to the end of this container.
4void add(Component comp, Object constraints, int index)
Adds the specified component to this container with the specified constraints at the specified index.
5Component add(String name, Component comp)
Adds the specified component to this container.
6void addContainerListener(ContainerListener l)
Adds the specified container listener to receive container events from this container.
7protected void addImpl(Component comp, Object constraints, int index)
Adds the specified component to this container at the specified index.
8void addNotify()
Makes this Container displayable by connecting it to a native screen resource.
9void addPropertyChangeListener(PropertyChangeListener listener)
Adds a PropertyChangeListener to the listener list.
10void addPropertyChangeListener(String propertyName, PropertyChangeListener listener)
Adds a PropertyChangeListener to the listener list for a specific property.
11void applyComponentOrientation(ComponentOrientation o)
Sets the ComponentOrientation property of this container and all components contained within it.
12boolean areFocusTraversalKeysSet(int id)
Returns whether the Set of focus traversal keys for the given focus traversal operation has been explicitly defined for this Container.
13int countComponents()
Deprecated. As of JDK version 1.1, replaced by getComponentCount().
14void deliverEvent(Event e)
Deprecated. As of JDK version 1.1, replaced by dispatchEvent(AWTEvent e)
15void doLayout()
Causes this container to lay out its components.
16Component findComponentAt(int x, int y)
Locates the visible child component that contains the specified position.
17Component findComponentAt(Point p)
Locates the visible child component that contains the specified point.
18float getAlignmentX()
Returns the alignment along the x axis.
19float getAlignmentY()
Returns the alignment along the y axis.
20Component getComponent(int n)
Gets the nth component in this container.
21Component getComponentAt(int x, int y)
Locates the component that contains the x,y position.
22Component getComponentAt(Point p)
Gets the component that contains the specified point.
23int getComponentCount()
Gets the number of components in this panel.
24Component[] getComponents()
Gets all the components in this container.
25int getComponentZOrder(Component comp)
Returns the z-order index of the component inside the container.
26ContainerListener[] getContainerListeners()
Returns an array of all the container listeners registered on this container.
27Set<AWTKeyStroke> getFocusTraversalKeys(int id)
Returns the Set of focus traversal keys for a given traversal operation for this Container.
28FocusTraversalPolicy getFocusTraversalPolicy()
Returns the focus traversal policy that will manage keyboard traversal of this Container's children, or null if this Container is not a focus cycle root.
29Insets getInsets()
Determines the insets of this container, which indicate the size of the container's border.
30LayoutManager getLayout()
Gets the layout manager for this container.
31<T extends EventListener> T[] getListeners(Class<T> listenerType)
Returns an array of all the objects currently registered as FooListeners upon this Container.
32Dimension getMaximumSize()
Returns the maximum size of this container.
33Dimension getMinimumSize()
Returns the minimum size of this container.
34Point getMousePosition(boolean allowChildren)
Returns the position of the mouse pointer in this Container's coordinate space if the Container is under the mouse pointer, otherwise returns null.
35Dimension getPreferredSize()
Returns the preferred size of this container.
36Insets insets()
Deprecated. As of JDK version 1.1, replaced by getInsets().
37void invalidate()
Invalidates the container.
38boolean isAncestorOf(Component c)
Checks if the component is contained in the component hierarchy of this container.
39boolean isFocusCycleRoot()
Returns whether this Container is the root of a focus traversal cycle.
40boolean isFocusCycleRoot(Container container)
Returns whether the specified Container is the focus cycle root of this Container's focus traversal cycle.
41boolean isFocusTraversalPolicyProvider()
Returns whether this container provides focus traversal policy.
42boolean isFocusTraversalPolicySet()
Returns whether the focus traversal policy has been explicitly set for this Container.
43void layout()
Deprecated. As of JDK version 1.1, replaced by doLayout().
44void list(PrintStream out, int indent)
Prints a listing of this container to the specified output stream.
45void list(PrintWriter out, int indent)
Prints out a list, starting at the specified indentation, to the specified print writer.
46Component locate(int x, int y)
Deprecated. As of JDK version 1.1, replaced by getComponentAt(int, int).
47Dimension minimumSize()
Deprecated. As of JDK version 1.1, replaced by getMinimumSize().
48void paint(Graphics g)
Paints the container.
49void paintComponents(Graphics g)
Paints each of the components in this container.
50protected String paramString()
Returns a string representing the state of this Container.
51Dimension preferredSize()
Deprecated. As of JDK version 1.1, replaced by getPreferredSize().
52void print(Graphics g)
Prints the container.
53void printComponents(Graphics g)
Prints each of the components in this container.
54protected void processContainerEvent(ContainerEvent e)
Processes container events occurring on this container by dispatching them to any registered ContainerListener objects.
55protected void processEvent(AWTEvent e)
Processes events on this container.
56void remove(Component comp)
Removes the specified component from this container.
57void remove(int index)
Removes the component, specified by index, from this container.
58void removeAll()
Removes all the components from this container.
59void removeContainerListener(ContainerListener l)
Removes the specified container listener so it no longer receives container events from this container.
60void removeNotify()
Makes this Container undisplayable by removing its connection to its native screen resource.
61void setComponentZOrder(Component comp, int index)
Moves the specified component to the specified z-order index in the container.
62void setFocusCycleRoot(boolean focusCycleRoot)
Sets whether this Container is the root of a focus traversal cycle.
63void setFocusTraversalKeys(int id, Set<? extends AWTKeyStroke> keystrokes)
Sets the focus traversal keys for a given traversal operation for this Container.
64void setFocusTraversalPolicy(FocusTraversalPolicy policy)
Sets the focus traversal policy that will manage keyboard traversal of this Container's children, if this Container is a focus cycle root.
65void setFocusTraversalPolicyProvider(boolean provider)
Sets whether this container will be used to provide focus traversal policy.
66void setFont(Font f)
Sets the font of this container.
67void setLayout(LayoutManager mgr)
Sets the layout manager for this container.
68void transferFocusBackward()
Transfers the focus to the previous component, as though this Component were the focus owner.
69void transferFocusDownCycle()
Transfers the focus down one focus traversal cycle.
70void update(Graphics g)
Updates the container.
71void validate()
Validates this container and all of its subcomponents.
72protected void validateTree()
Recursively descends the container tree and recomputes the layout for any subtrees marked as needing it (those marked as invalid).

Methods inherited

This class inherits methods from the following classes:

  • java.awt.Component

  • java.lang.Object

AWT Panel Class

Introduction

The class Panel is the simplest container class. It provides space in which an application can attach any other component, including other panels. It uses FlowLayout as default layout manager.

Class declaration

Following is the declaration for java.awt.Panel class:

public class Panel
   extends Container
      implements Accessible

Class constructors

S.N.Constructor & Description
1Panel()
Creates a new panel using the default layout manager.
2Panel(LayoutManager layout)
Creates a new panel with the specified layout manager.

Class methods

S.N.Method & Description
1void addNotify()
Creates the Panel's peer.
2AccessibleContext getAccessibleContext()
Gets the AccessibleContext associated with this Panel.

Methods inherited

This class inherits methods from the following classes:

  • java.awt.Container

  • java.awt.Component

  • java.lang.Object

Panel Example

Create the following java program using any editor of your choice in say D:/ > AWT > com > tutorialspoint > gui >

AwtContainerDemo.java
package com.tutorialspoint.gui;

import java.awt.*;
import java.awt.event.*;

public class AwtContainerDemo {
   private Frame mainFrame;
   private Label headerLabel;
   private Label statusLabel;
   private Panel controlPanel;
   private Label msglabel;

   public AwtContainerDemo(){
      prepareGUI();
   }

   public static void main(String[] args){
      AwtContainerDemo  awtContainerDemo = new AwtContainerDemo();          
      awtContainerDemo.showPanelDemo();
   }

   private void prepareGUI(){
      mainFrame = new Frame("Java AWT Examples");
      mainFrame.setSize(400,400);
      mainFrame.setLayout(new GridLayout(3, 1));
      mainFrame.addWindowListener(new WindowAdapter() {
         public void windowClosing(WindowEvent windowEvent){
            System.exit(0);
         }        
      });    
      headerLabel = new Label();
      headerLabel.setAlignment(Label.CENTER);
      statusLabel = new Label();        
      statusLabel.setAlignment(Label.CENTER);
      statusLabel.setSize(350,100);
   
      msglabel = new Label();
      msglabel.setAlignment(Label.CENTER);
      msglabel.setText("Welcome to TutorialsPoint AWT Tutorial.");

      controlPanel = new Panel();
      controlPanel.setLayout(new FlowLayout());

      mainFrame.add(headerLabel);
      mainFrame.add(controlPanel);
      mainFrame.add(statusLabel);
      mainFrame.setVisible(true);  
   }

   private void showPanelDemo(){
      headerLabel.setText("Container in action: Panel");      

      Panel panel = new Panel();
      panel.setBackground(Color.magenta);
      panel.setLayout(new FlowLayout());        
      panel.add(msglabel);

      controlPanel.add(panel);

      mainFrame.setVisible(true);  
   }
}

Compile the program using command prompt. Go to D:/ > AWT and type the following command.

D:\AWT>javac com\tutorialspoint\gui\AwtContainerDemo.java

If no error comes that means compilation is successful. Run the program using following command.

D:\AWT>java com.tutorialspoint.gui.AwtContainerDemo

Verify the following output

AWT Panel

AWT Frame Class

Introduction

The class Frame is a top level window with border and title. It uses BorderLayout as default layout manager.

Class declaration

Following is the declaration for java.awt.Frame class:

public class Frame
   extends Window
      implements MenuContainer

Field

Following are the fields for java.awt.Frame class:

  • static float BOTTOM_ALIGNMENT -- Ease-of-use constant for getAlignmentY.

  • static int CROSSHAIR_CURSOR -- Deprecated. replaced by Cursor.CROSSHAIR_CURSOR.

  • static int DEFAULT_CURSOR -- Deprecated. replaced by Cursor.DEFAULT_CURSOR.

  • static int E_RESIZE_CURSOR -- Deprecated. replaced by Cursor.E_RESIZE_CURSOR.

  • static int HAND_CURSOR -- Deprecated. replaced by Cursor.HAND_CURSOR.

  • static int ICONIFIED -- This state bit indicates that frame is iconified.

  • static int MAXIMIZED_BOTH -- This state bit mask indicates that frame is fully maximized (that is both horizontally and vertically).

  • static int MAXIMIZED_HORIZ -- This state bit indicates that frame is maximized in the horizontal direction.

  • static int MAXIMIZED_VERT -- This state bit indicates that frame is maximized in the vertical direction.

  • static int MOVE_CURSOR -- Deprecated. replaced by Cursor.MOVE_CURSOR.

  • static int N_RESIZE_CURSOR -- Deprecated. replaced by Cursor.N_RESIZE_CURSOR.

  • static int NE_RESIZE_CURSOR -- Deprecated. replaced by Cursor.NE_RESIZE_CURSOR.

  • static int NORMAL -- Frame is in the "normal" state.

  • static int NW_RESIZE_CURSOR -- Deprecated. replaced by Cursor.NW_RESIZE_CURSOR.

  • static int S_RESIZE_CURSOR -- Deprecated. replaced by Cursor.S_RESIZE_CURSOR.

  • static int SE_RESIZE_CURSOR -- Deprecated. replaced by Cursor.SE_RESIZE_CURSOR.

  • static int SW_RESIZE_CURSOR -- Deprecated. replaced by Cursor.SW_RESIZE_CURSOR.

  • static int TEXT_CURSOR -- Deprecated. replaced by Cursor.TEXT_CURSOR.

  • static int W_RESIZE_CURSOR -- Deprecated. replaced by Cursor.W_RESIZE_CURSOR.

  • static int WAIT_CURSOR -- Deprecated. replaced by Cursor.WAIT_CURSOR.

Class constructors

S.N.Constructor & Description
1Frame()
Constructs a new instance of Frame that is initially invisible.
2Frame(GraphicsConfiguration gc)
Constructs a new, initially invisible Frame with the specified GraphicsConfiguration.
3Frame(String title)
Constructs a new, initially invisible Frame object with the specified title.
4Frame(String title, GraphicsConfiguration gc)
Constructs a new, initially invisible Frame object with the specified title and a GraphicsConfiguration.

Class methods

S.N.Method & Description
1void addNotify()
Makes this Frame displayable by connecting it to a native screen resource.
2AccessibleContext getAccessibleContext()
Gets the AccessibleContext associated with this Frame.
3int getCursorType()
Deprecated. As of JDK version 1.1, replaced by Component.getCursor().
4int getExtendedState()
Gets the state of this frame.
5static Frame[] getFrames()
Returns an array of all Frames created by this application.
6Image getIconImage()
Returns the image to be displayed as the icon for this frame.
7Rectangle getMaximizedBounds()
Gets maximized bounds for this frame.
8MenuBar getMenuBar()
Gets the menu bar for this frame.
9int getState()
Gets the state of this frame (obsolete).
10String getTitle()
Gets the title of the frame.
11boolean isResizable()
Indicates whether this frame is resizable by the user.
12boolean isUndecorated()
Indicates whether this frame is undecorated.
13protected String paramString()
Returns a string representing the state of this Frame.
14void remove(MenuComponent m)
Removes the specified menu bar from this frame.
15void removeNotify()
Makes this Frame undisplayable by removing its connection to its native screen resource.
16void setCursor(int cursorType)
Deprecated. As of JDK version 1.1, replaced by Component.setCursor(Cursor).
17void setExtendedState(int state)
Sets the state of this frame.
18void setIconImage(Image image)
Sets the image to be displayed as the icon for this window.
19void setMaximizedBounds(Rectangle bounds)
Sets the maximized bounds for this frame.
20void setMenuBar(MenuBar mb)
Sets the menu bar for this frame to the specified menu bar.
21void setResizable(boolean resizable)
Sets whether this frame is resizable by the user.
22void setState(int state)
Sets the state of this frame (obsolete).
23void setTitle(String title)
Sets the title for this frame to the specified string.
24void setUndecorated(boolean undecorated)
Disables or enables decorations for this frame.

Methods inherited

This class inherits methods from the following classes:

  • java.awt.Window

  • java.awt.Container

  • java.awt.Component

  • java.lang.Object

Frame Example

Create the following java program using any editor of your choice in say D:/ > AWT > com > tutorialspoint > gui >

AwtContainerDemo.java
package com.tutorialspoint.gui;

import java.awt.*;
import java.awt.event.*;

public class AwtContainerDemo {
   private Frame mainFrame;
   private Label headerLabel;
   private Label statusLabel;
   private Panel controlPanel;
   private Label msglabel;

   public AwtContainerDemo(){
      prepareGUI();
   }

   public static void main(String[] args){
      AwtContainerDemo  awtContainerDemo = new AwtContainerDemo();          
      awtContainerDemo.showFrameDemo();
   }

   private void prepareGUI(){
      mainFrame = new Frame("Java AWT Examples");
      mainFrame.setSize(400,400);
      mainFrame.setLayout(new GridLayout(3, 1));
      mainFrame.addWindowListener(new WindowAdapter() {
         public void windowClosing(WindowEvent windowEvent){
            System.exit(0);
         }        
      });    
      headerLabel = new Label();
      headerLabel.setAlignment(Label.CENTER);
      statusLabel = new Label();        
      statusLabel.setAlignment(Label.CENTER);
      statusLabel.setSize(350,100);
   
      msglabel = new Label();
      msglabel.setAlignment(Label.CENTER);
      msglabel.setText("Welcome to TutorialsPoint AWT Tutorial.");

      controlPanel = new Panel();
      controlPanel.setLayout(new FlowLayout());

      mainFrame.add(headerLabel);
      mainFrame.add(controlPanel);
      mainFrame.add(statusLabel);
      mainFrame.setVisible(true);  
   }
   
   private void showFrameDemo(){
      headerLabel.setText("Container in action: Frame");   

      final Frame frame = new Frame();
      frame.setSize(300, 300);
      frame.setLayout(new FlowLayout());       
      frame.add(msglabel);
      frame.addWindowListener(new WindowAdapter() {
         public void windowClosing(WindowEvent windowEvent){
            frame.dispose();
         }        
      });    
      Button okButton = new Button("Open a Frame");

      okButton.addActionListener(new ActionListener() {
         public void actionPerformed(ActionEvent e) {
            statusLabel.setText("A Frame shown to the user.");
            frame.setVisible(true);
         }
      });
      controlPanel.add(okButton);

      mainFrame.setVisible(true);  
   }
}

Compile the program using command prompt. Go to D:/ > AWT and type the following command.

D:\AWT>javac com\tutorialspoint\gui\AwtContainerDemo.java

If no error comes that means compilation is successful. Run the program using following command.

D:\AWT>java com.tutorialspoint.gui.AwtContainerDemo

Verify the following output

AWT Frame

AWT Window Class

Introduction

The class Window is a top level window with no border and no menubar. It uses BorderLayout as default layout manager.

Class declaration

Following is the declaration for java.awt.Window class:

public class Window
   extends Container
      implements Accessible

Class constructors

S.N.Constructor & Description
1Window(Frame owner)
Constructs a new, initially invisible window with the specified Frame as its owner.
2Window(Window owner)
Constructs a new, initially invisible window with the specified Window as its owner.
3Window(Window owner, GraphicsConfiguration gc)
Constructs a new, initially invisible window with the specified owner Window and a GraphicsConfiguration of a screen device.

Class methods

S.N.Method & Description
1void addNotify()
Makes this Window displayable by creating the connection to its native screen resource.
2void addPropertyChangeListener(PropertyChangeListener listener)
Adds a PropertyChangeListener to the listener list.
3void addPropertyChangeListener(String propertyName, PropertyChangeListener listener)
Adds a PropertyChangeListener to the listener list for a specific property.
4void addWindowFocusListener(WindowFocusListener l)
Adds the specified window focus listener to receive window events from this window.
5void addWindowListener(WindowListener l)
Adds the specified window listener to receive window events from this window.
6void addWindowStateListener(WindowStateListener l)
Adds the specified window state listener to receive window events from this window.
7void applyResourceBundle(ResourceBundle rb)
Deprecated. As of J2SE 1.4, replaced by Component.applyComponentOrientation.
8void applyResourceBundle(String rbName)
Deprecated. As of J2SE 1.4, replaced by Component.applyComponentOrientation.
9void createBufferStrategy(int numBuffers)
Creates a new strategy for multi-buffering on this component.
10void createBufferStrategy(int numBuffers, BufferCapabilities caps)
Creates a new strategy for multi-buffering on this component with the required buffer capabilities.
11void dispose()
Releases all of the native screen resources used by this Window, its subcomponents, and all of its owned children.
12AccessibleContext getAccessibleContext()
Gets the AccessibleContext associated with this Window.
13BufferStrategy getBufferStrategy()
Returns the BufferStrategy used by this component.
14boolean getFocusableWindowState()
Returns whether this Window can become the focused Window if it meets the other requirements outlined in isFocusableWindow.
15Container getFocusCycleRootAncestor()
Always returns null because Windows have no ancestors; they represent the top of the Component hierarchy.
16Component getFocusOwner()
Returns the child Component of this Window that has focus if this Window is focused; returns null otherwise.
17Set<AWTKeyStroke> getFocusTraversalKeys(int id)
Gets a focus traversal key for this Window.
18GraphicsConfiguration getGraphicsConfiguration()
This method returns the GraphicsConfiguration used by this Window.
19List<Image> getIconImages()
Returns the sequence of images to be displayed as the icon for this window.
20InputContext getInputContext()
Gets the input context for this window.
21<T extends EventListener> T[] getListeners(Class<T> listenerType)
Returns an array of all the objects currently registered as FooListeners upon this Window.
22Locale getLocale()
Gets the Locale object that is associated with this window, if the locale has been set.
23Dialog.ModalExclusionType getModalExclusionType()
Returns the modal exclusion type of this window.
24Component getMostRecentFocusOwner()
Returns the child Component of this Window that will receive the focus when this Window is focused.
25Window[] getOwnedWindows()
Return an array containing all the windows this window currently owns.
26Window getOwner()
Returns the owner of this window.
27static Window[] getOwnerlessWindows()
Returns an array of all Windows created by this application that have no owner.
28Toolkit getToolkit()
Returns the toolkit of this frame.
29String getWarningString()
Gets the warning string that is displayed with this window.
30WindowFocusListener[] getWindowFocusListeners()
Returns an array of all the window focus listeners registered on this window.
31WindowListener[] getWindowListeners()
Returns an array of all the window listeners registered on this window.
32static Window[] getWindows()
Returns an array of all Windows, both owned and ownerless, created by this application.
33WindowStateListener[] getWindowStateListeners()
Returns an array of all the window state listeners registered on this window.
34void hide()
Deprecated. As of JDK version 1.5, replaced by setVisible(boolean).
35boolean isActive()
Returns whether this Window is active.
36boolean isAlwaysOnTop()
Returns whether this window is an always-on-top window.
37boolean isAlwaysOnTopSupported()
Returns whether the always-on-top mode is supported for this window.
38boolean isFocusableWindow()
Returns whether this Window can become the focused Window, that is, whether this Window or any of its subcomponents can become the focus owner.
39boolean isFocusCycleRoot()
Always returns true because all Windows must be roots of a focus traversal cycle.
40boolean isFocused()
Returns whether this Window is focused.
41boolean isLocationByPlatform()
Returns true if this Window will appear at the default location for the native windowing system the next time this Window is made visible.
42boolean isShowing()
Checks if this Window is showing on screen.
43void pack()
Causes this Window to be sized to fit the preferred size and layouts of its subcomponents.
44void paint(Graphics g)
Paints the container.
45boolean postEvent(Event e)
Deprecated. As of JDK version 1.1 replaced by dispatchEvent(AWTEvent).
46protected void processEvent(AWTEvent e)
Processes events on this window.
47protected void processWindowEvent(WindowEvent e)
Processes window events occurring on this window by dispatching them to any registered WindowListener objects.
48protected void processWindowFocusEvent(WindowEvent e)
Processes window focus event occuring on this window by dispatching them to any registered WindowFocusListener objects.
49protected void processWindowStateEvent(WindowEvent e)
Processes window state event occuring on this window by dispatching them to any registered WindowStateListener objects.
50void removeNotify()
Makes this Container undisplayable by removing its connection to its native screen resource.
51void removeWindowFocusListener(WindowFocusListener l)
Removes the specified window focus listener so that it no longer receives window events from this window.
52void removeWindowListener(WindowListener l)
Removes the specified window listener so that it no longer receives window events from this window.
53void removeWindowStateListener(WindowStateListener l)
Removes the specified window state listener so that it no longer receives window events from this window.
54void reshape(int x, int y, int width, int height)
Deprecated. As of JDK version 1.1, replaced by setBounds(int, int, int, int).
55void setAlwaysOnTop(boolean alwaysOnTop)
Sets whether this window should always be above other windows.
56void setBounds(int x, int y, int width, int height)
Moves and resizes this component.
57void setBounds(Rectangle r)
Moves and resizes this component to conform to the new bounding rectangle r.
58void setCursor(Cursor cursor)
Set the cursor image to a specified cursor.
59void setFocusableWindowState(boolean focusableWindowState)
Sets whether this Window can become the focused Window if it meets the other requirements outlined in isFocusableWindow.
60void setFocusCycleRoot(boolean focusCycleRoot)
Does nothing because Windows must always be roots of a focus traversal cycle.
61void setIconImage(Image image)
Sets the image to be displayed as the icon for this window.
62void setIconImages(List<? extends Image> icons)
Sets the sequence of images to be displayed as the icon for this window.
63void setLocationByPlatform(boolean locationByPlatform)
Sets whether this Window should appear at the default location for the native windowing system or at the current location (returned by getLocation) the next time the Window is made visible.
64void setLocationRelativeTo(Component c)
Sets the location of the window relative to the specified component.
65void setMinimumSize(Dimension minimumSize)
Sets the minimum size of this window to a constant value.
66void setModalExclusionType(Dialog.ModalExclusionType exclusionType)
Specifies the modal exclusion type for this window.
67void setSize(Dimension d)
Resizes this component so that it has width d.width and height d.height.
68void setSize(int width, int height)
Resizes this component so that it has width width and height height.
69void setVisible(boolean b)
Shows or hides this Window depending on the value of parameter b.
70void show()
Deprecated. As of JDK version 1.5, replaced by setVisible(boolean).
71void toBack()
If this Window is visible, sends this Window to the back and may cause it to lose focus or activation if it is the focused or active Window.
72void toFront()
If this Window is visible, brings this Window to the front and may make it the focused Window.

Methods inherited

This class inherits methods from the following classes:

  • java.awt.Window

  • java.awt.Container

  • java.awt.Component

  • java.lang.Object

Window Example

Create the following java program using any editor of your choice in say D:/ > AWT > com > tutorialspoint > gui >

AwtContainerDemo.java
package com.tutorialspoint.gui;

import java.awt.*;
import java.awt.event.*;

public class AwtContainerDemo {
   private Frame mainFrame;
   private Label headerLabel;
   private Label statusLabel;
   private Panel controlPanel;
   private Label msglabel;

   public AwtContainerDemo(){
      prepareGUI();
   }

   public static void main(String[] args){
      AwtContainerDemo  awtContainerDemo = new AwtContainerDemo();          
      awtContainerDemo.showFrameDemo();
   }

   private void prepareGUI(){
      mainFrame = new Frame("Java AWT Examples");
      mainFrame.setSize(400,400);
      mainFrame.setLayout(new GridLayout(3, 1));
      mainFrame.addWindowListener(new WindowAdapter() {
         public void windowClosing(WindowEvent windowEvent){
            System.exit(0);
         }        
      });    
      headerLabel = new Label();
      headerLabel.setAlignment(Label.CENTER);
      statusLabel = new Label();        
      statusLabel.setAlignment(Label.CENTER);
      statusLabel.setSize(350,100);
   
      msglabel = new Label();
      msglabel.setAlignment(Label.CENTER);
      msglabel.setText("Welcome to TutorialsPoint AWT Tutorial.");

      controlPanel = new Panel();
      controlPanel.setLayout(new FlowLayout());

      mainFrame.add(headerLabel);
      mainFrame.add(controlPanel);
      mainFrame.add(statusLabel);
      mainFrame.setVisible(true);  
   }
   
   private void showWindowDemo(){
      headerLabel.setText("Container in action: Window");   
      final MessageWindow window = 
         new MessageWindow(mainFrame,
         "Welcome to TutorialsPoint AWT Tutorial.");

      Button okButton = new Button("Open a Window");
      okButton.addActionListener(new ActionListener() {
         public void actionPerformed(ActionEvent e) {
            window.setVisible(true);
            statusLabel.setText("A Window shown to the user.");                
         }
      });
      controlPanel.add(okButton);
      mainFrame.setVisible(true);  
   }

   class MessageWindow extends Window{
      private String message; 

      public MessageWindow(Frame parent, String message) { 
         super(parent);               
         this.message = message; 
         setSize(300, 300);       
         setLocationRelativeTo(parent);
         setBackground(Color.gray);
      }

      public void paint(Graphics g) { 
         super.paint(g);
         g.drawRect(0,0,getSize().width - 1,getSize().height - 1); 
         g.drawString(message,50,150); 
      } 
   }
}

Compile the program using command prompt. Go to D:/ > AWT and type the following command.

D:\AWT>javac com\tutorialspoint\gui\AwtContainerDemo.java

If no error comes that means compilation is successful. Run the program using following command.

D:\AWT>java com.tutorialspoint.gui.AwtContainerDemo

Verify the following output

AWT Window

AWT Menu Classes

As we know that every top-level window has a menu bar associated with it. This menu bar consist of various menu choices available to the end user. Further each choice contains list of options which is called drop down menus. Menu and MenuItem controls are subclass of MenuComponent class.

Menu Hiearchy

AWT Menu Hiearchy

AWT MenuComponent Class

Introduction

MenuComponent is an abstract class and is the superclass for all menu-related components.

Class declaration

Following is the declaration for java.awt.MenuComponent class:

public abstract class MenuComponent
   extends Object
      implements Serializable

Class constructors

S.N.Constructor & Description
1MenuComponent()
Creates a MenuComponent.

Class methods

void dispatchEvent(AWTEvent e)
S.N.Method & Description
1AccessibleContext getAccessibleContext()
Gets the AccessibleContext associated with this MenuComponent.
2Font getFont()
Gets the font used for this menu component.
3String getName()
Gets the name of the menu component.
4MenuContainer getParent()
Returns the parent container for this menu component.
5java.awt.peer.MenuComponentPeer getPeer()
Deprecated. As of JDK version 1.1, programs should not directly manipulate peers.
6protected Object getTreeLock()
Gets this component's locking object (the object that owns the thread sychronization monitor) for AWT component-tree and layout operations.
7protected String paramString()
Returns a string representing the state of this MenuComponent.
8boolean postEvent(Event evt)
Deprecated. As of JDK version 1.1, replaced by dispatchEvent.
9protected void processEvent(AWTEvent e)
Processes events occurring on this menu component.
10void removeNotify()
Removes the menu component's peer.
11void setFont(Font f)
Sets the font to be used for this menu component to the specified font.
12void setName(String name)
Sets the name of the component to the specified string.
13String toString()
Returns a representation of this menu component as a string.

Methods inherited

This class inherits methods from the following classes:

  • java.lang.Object

AWT MenuBar Class

Introduction

The MenuBar class provides menu bar bound to a frame and is platform specific.

Class declaration

Following is the declaration for java.awt.MenuBar class:

public class MenuBar
   extends MenuComponent
      implements MenuContainer, Accessible

Class constructors

S.N.Constructor & Description
1MenuBar()
Creates a new menu bar.

Class methods

S.N.Method & Description
1void dispatchEvent(AWTEvent e)
2Menu add(Menu m)
Adds the specified menu to the menu bar.
3void addNotify()
Creates the menu bar's peer.
4int countMenus()
Deprecated. As of JDK version 1.1, replaced by getMenuCount().
5void deleteShortcut(MenuShortcut s)
Deletes the specified menu shortcut.
6AccessibleContext getAccessibleContext()
Gets the AccessibleContext associated with this MenuBar.
7Menu getHelpMenu()
Gets the help menu on the menu bar.
8Menu getMenu(int i)
Gets the specified menu.
9int getMenuCount()
Gets the number of menus on the menu bar.
10MenuItem getShortcutMenuItem(MenuShortcut s)
Gets the instance of MenuItem associated with the specified MenuShortcut object, or null if none of the menu items being managed by this menu bar is associated with the specified menu shortcut.
11void remove(int index)
Removes the menu located at the specified index from this menu bar.
12void remove(MenuComponent m)
Removes the specified menu component from this menu bar.
13void removeNotify()
Removes the menu bar's peer.
14void setHelpMenu(Menu m)
Sets the specified menu to be this menu bar's help menu.
15Enumeration shortcuts()
Gets an enumeration of all menu shortcuts this menu bar is managing.

Methods inherited

This class inherits methods from the following classes:

  • java.awt.MenuComponent

  • java.lang.Object

MenuBar Example

Create the following java program using any editor of your choice in say D:/ > AWT > com > tutorialspoint > gui >

AWTMenuDemo.java
package com.tutorialspoint.gui;

import java.awt.*;
import java.awt.event.*;

public class AWTMenuDemo {
   private Frame mainFrame;
   private Label headerLabel;
   private Label statusLabel;
   private Panel controlPanel;

   public AWTMenuDemo(){
      prepareGUI();
   }

   public static void main(String[] args){
      AWTMenuDemo  awtMenuDemo = new AWTMenuDemo();     
      awtMenuDemo.showMenuDemo();
   }

   private void prepareGUI(){
      mainFrame = new Frame("Java AWT Examples");
      mainFrame.setSize(400,400);
      mainFrame.setLayout(new GridLayout(3, 1));
      mainFrame.addWindowListener(new WindowAdapter() {
         public void windowClosing(WindowEvent windowEvent){
            System.exit(0);
         }        
      });    
      headerLabel = new Label();
      headerLabel.setAlignment(Label.CENTER);
      statusLabel = new Label();        
      statusLabel.setAlignment(Label.CENTER);
      statusLabel.setSize(350,100);

      controlPanel = new Panel();
      controlPanel.setLayout(new FlowLayout());

      mainFrame.add(headerLabel);
      mainFrame.add(controlPanel);
      mainFrame.add(statusLabel);
      mainFrame.setVisible(true);  
   }

   private void showMenuDemo(){
      //create a menu bar
      final MenuBar menuBar = new MenuBar();

      //create menus
      Menu fileMenu = new Menu("File");
      Menu editMenu = new Menu("Edit"); 
      final Menu aboutMenu = new Menu("About");

      //create menu items
      MenuItem newMenuItem = 
         new MenuItem("New",new MenuShortcut(KeyEvent.VK_N));
      newMenuItem.setActionCommand("New");

      MenuItem openMenuItem = new MenuItem("Open");
      openMenuItem.setActionCommand("Open");

      MenuItem saveMenuItem = new MenuItem("Save");
      saveMenuItem.setActionCommand("Save");

      MenuItem exitMenuItem = new MenuItem("Exit");
      exitMenuItem.setActionCommand("Exit");

      MenuItem cutMenuItem = new MenuItem("Cut");
      cutMenuItem.setActionCommand("Cut");

      MenuItem copyMenuItem = new MenuItem("Copy");
      copyMenuItem.setActionCommand("Copy");

      MenuItem pasteMenuItem = new MenuItem("Paste");
      pasteMenuItem.setActionCommand("Paste");
   
      MenuItemListener menuItemListener = new MenuItemListener();

      newMenuItem.addActionListener(menuItemListener);
      openMenuItem.addActionListener(menuItemListener);
      saveMenuItem.addActionListener(menuItemListener);
      exitMenuItem.addActionListener(menuItemListener);
      cutMenuItem.addActionListener(menuItemListener);
      copyMenuItem.addActionListener(menuItemListener);
      pasteMenuItem.addActionListener(menuItemListener);

      final CheckboxMenuItem showWindowMenu = 
         new CheckboxMenuItem("Show About", true);
      showWindowMenu.addItemListener(new ItemListener() {
         public void itemStateChanged(ItemEvent e) {
            if(showWindowMenu.getState()){
               menuBar.add(aboutMenu);
            }else{
               menuBar.remove(aboutMenu);
            }
         }
      });

      //add menu items to menus
      fileMenu.add(newMenuItem);
      fileMenu.add(openMenuItem);
      fileMenu.add(saveMenuItem);
      fileMenu.addSeparator();
      fileMenu.add(showWindowMenu);
      fileMenu.addSeparator();
      fileMenu.add(exitMenuItem);

      editMenu.add(cutMenuItem);
      editMenu.add(copyMenuItem);
      editMenu.add(pasteMenuItem);

      //add menu to menubar
      menuBar.add(fileMenu);
      menuBar.add(editMenu);
      menuBar.add(aboutMenu);

      //add menubar to the frame
      mainFrame.setMenuBar(menuBar);
      mainFrame.setVisible(true);  
   }

   class MenuItemListener implements ActionListener {
      public void actionPerformed(ActionEvent e) {            
         statusLabel.setText(e.getActionCommand() 
            + " MenuItem clicked.");
      }    
   }
}

Compile the program using command prompt. Go to D:/ > AWT and type the following command.

D:\AWT>javac com\tutorialspoint\gui\AWTMenuDemo.java

If no error comes that means compilation is successful. Run the program using following command.

D:\AWT>java com.tutorialspoint.gui.AWTMenuDemo

Verify the following output

AWT MenuBar

AWT MenuItem Class

Introduction

The MenuBar class represents the actual item in a menu. All items in a menu should derive from class MenuItem, or one of its subclasses. By default, it embodies a simple labeled menu item.

Class declaration

Following is the declaration for java.awt.MenuItem class:

public class MenuItem
   extends MenuComponent
      implements Accessible

Class constructors

S.N.Constructor & Description
1MenuItem()
Constructs a new MenuItem with an empty label and no keyboard shortcut.
2MenuItem(String label)
Constructs a new MenuItem with the specified label and no keyboard shortcut.
3MenuItem(String label, MenuShortcut s)
Create a menu item with an associated keyboard shortcut.

Class methods

S.N.Method & Description
1void addActionListener(ActionListener l)
Adds the specified action listener to receive action events from this menu item.
2void addNotify()
Creates the menu item's peer.
3void deleteShortcut()
Delete any MenuShortcut object associated with this menu item.
4void disable()
Deprecated. As of JDK version 1.1, replaced by setEnabled(boolean).
5protected void disableEvents(long eventsToDisable)
Disables event delivery to this menu item for events defined by the specified event mask parameter.
6void enable()
Deprecated. As of JDK version 1.1, replaced by setEnabled(boolean).
7void enable(boolean b)
Deprecated. As of JDK version 1.1, replaced by setEnabled(boolean).
8protected void enableEvents(long eventsToEnable)
Enables event delivery to this menu item for events to be defined by the specified event mask parameter.
9AccessibleContext getAccessibleContext()
Gets the AccessibleContext associated with this MenuItem.
10String getActionCommand()
Gets the command name of the action event that is fired by this menu item.
11ActionListener[] getActionListeners()
Returns an array of all the action listeners registered on this menu item.
12String getLabel()
Gets the label for this menu item.
13EventListener[] getListeners(Class listenerType)
Returns an array of all the objects currently registered as FooListeners upon this MenuItem.
14MenuShortcut getShortcut()
Get the MenuShortcut object associated with this menu item.
15boolean isEnabled()
Checks whether this menu item is enabled.
16String paramString()
Returns a string representing the state of this MenuItem.
17protected void processActionEvent(ActionEvent e)
Processes action events occurring on this menu item, by dispatching them to any registered ActionListener objects.
18protected void processEvent(AWTEvent e)
Processes events on this menu item.
19void removeActionListener(ActionListener l)
Removes the specified action listener so it no longer receives action events from this menu item.
20void setActionCommand(String command)
Sets the command name of the action event that is fired by this menu item.
21void setEnabled(boolean b)
Sets whether or not this menu item can be chosen.
22void setLabel(String label)
Sets the label for this menu item to the specified label.
23void setShortcut(MenuShortcut s)
Set the MenuShortcut object associated with this menu item.

Methods inherited

This class inherits methods from the following classes:

  • java.awt.MenuComponent

  • java.lang.Object

MenuItem Example

Create the following java program using any editor of your choice in say D:/ > AWT > com > tutorialspoint > gui >

AWTMenuDemo.java
package com.tutorialspoint.gui;

import java.awt.*;
import java.awt.event.*;

public class AWTMenuDemo {
   private Frame mainFrame;
   private Label headerLabel;
   private Label statusLabel;
   private Panel controlPanel;

   public AWTMenuDemo(){
      prepareGUI();
   }

   public static void main(String[] args){
      AWTMenuDemo  awtMenuDemo = new AWTMenuDemo();     
      awtMenuDemo.showMenuDemo();
   }

   private void prepareGUI(){
      mainFrame = new Frame("Java AWT Examples");
      mainFrame.setSize(400,400);
      mainFrame.setLayout(new GridLayout(3, 1));
      mainFrame.addWindowListener(new WindowAdapter() {
         public void windowClosing(WindowEvent windowEvent){
            System.exit(0);
         }        
      });    
      headerLabel = new Label();
      headerLabel.setAlignment(Label.CENTER);
      statusLabel = new Label();        
      statusLabel.setAlignment(Label.CENTER);
      statusLabel.setSize(350,100);

      controlPanel = new Panel();
      controlPanel.setLayout(new FlowLayout());

      mainFrame.add(headerLabel);
      mainFrame.add(controlPanel);
      mainFrame.add(statusLabel);
      mainFrame.setVisible(true);  
   }

   private void showMenuDemo(){
      //create a menu bar
      final MenuBar menuBar = new MenuBar();

      //create menus
      Menu fileMenu = new Menu("File");
      Menu editMenu = new Menu("Edit"); 
      final Menu aboutMenu = new Menu("About");

      //create menu items
      MenuItem newMenuItem = 
         new MenuItem("New",new MenuShortcut(KeyEvent.VK_N));
      newMenuItem.setActionCommand("New");

      MenuItem openMenuItem = new MenuItem("Open");
      openMenuItem.setActionCommand("Open");

      MenuItem saveMenuItem = new MenuItem("Save");
      saveMenuItem.setActionCommand("Save");

      MenuItem exitMenuItem = new MenuItem("Exit");
      exitMenuItem.setActionCommand("Exit");

      MenuItem cutMenuItem = new MenuItem("Cut");
      cutMenuItem.setActionCommand("Cut");

      MenuItem copyMenuItem = new MenuItem("Copy");
      copyMenuItem.setActionCommand("Copy");

      MenuItem pasteMenuItem = new MenuItem("Paste");
      pasteMenuItem.setActionCommand("Paste");
   
      MenuItemListener menuItemListener = new MenuItemListener();

      newMenuItem.addActionListener(menuItemListener);
      openMenuItem.addActionListener(menuItemListener);
      saveMenuItem.addActionListener(menuItemListener);
      exitMenuItem.addActionListener(menuItemListener);
      cutMenuItem.addActionListener(menuItemListener);
      copyMenuItem.addActionListener(menuItemListener);
      pasteMenuItem.addActionListener(menuItemListener);

      final CheckboxMenuItem showWindowMenu = 
         new CheckboxMenuItem("Show About", true);
      showWindowMenu.addItemListener(new ItemListener() {
         public void itemStateChanged(ItemEvent e) {
            if(showWindowMenu.getState()){
               menuBar.add(aboutMenu);
            }else{
               menuBar.remove(aboutMenu);
            }
         }
      });

      //add menu items to menus
      fileMenu.add(newMenuItem);
      fileMenu.add(openMenuItem);
      fileMenu.add(saveMenuItem);
      fileMenu.addSeparator();
      fileMenu.add(showWindowMenu);
      fileMenu.addSeparator();
      fileMenu.add(exitMenuItem);

      editMenu.add(cutMenuItem);
      editMenu.add(copyMenuItem);
      editMenu.add(pasteMenuItem);

      //add menu to menubar
      menuBar.add(fileMenu);
      menuBar.add(editMenu);
      menuBar.add(aboutMenu);

      //add menubar to the frame
      mainFrame.setMenuBar(menuBar);
      mainFrame.setVisible(true);  
   }

   class MenuItemListener implements ActionListener {
      public void actionPerformed(ActionEvent e) {            
         statusLabel.setText(e.getActionCommand() 
            + " MenuItem clicked.");
      }    
   }
}

Compile the program using command prompt. Go to D:/ > AWT and type the following command.

D:\AWT>javac com\tutorialspoint\gui\AWTMenuDemo.java

If no error comes that means compilation is successful. Run the program using following command.

D:\AWT>java com.tutorialspoint.gui.AWTMenuDemo

Verify the following output. (Click on File Menu. Select any menu item.)

AWT MenuItem

AWT Menu Class

Introduction

The Menu class represents pull-down menu component which is deployed from a menu bar.

Class declaration

Following is the declaration for java.awt.Menu class:

public class Menu
   extends MenuItem
      implements MenuContainer, Accessible

Class constructors

S.N.Constructor & Description
1Menu()
Constructs a new menu with an empty label.
2Menu(String label)
Constructs a new menu with the specified label.
3Menu(String label, boolean tearOff)
Constructs a new menu with the specified label, indicating whether the menu can be torn off.

Class methods

S.N.Method & Description
1MenuItem add(MenuItem mi)
Adds the specified menu item to this menu.
2void add(String label)
Adds an item with the specified label to this menu.
3void addNotify()
Creates the menu's peer.
4void addSeparator()
Adds a separator line, or a hypen, to the menu at the current position.
5int countItems()
Deprecated. As of JDK version 1.1, replaced by getItemCount().
6AccessibleContext getAccessibleContext()
Gets the AccessibleContext associated with this Menu.
7MenuItem getItem(int index)
Gets the item located at the specified index of this menu.
8int getItemCount()
Get the number of items in this menu.
9void insert(MenuItem menuitem, int index)
Inserts a menu item into this menu at the specified position.
10void insert(String label, int index)
Inserts a menu item with the specified label into this menu at the specified position.
11void insertSeparator(int index)
Inserts a separator at the specified position.
12boolean isTearOff()
Indicates whether this menu is a tear-off menu.
13String paramString()
Returns a string representing the state of this Menu.
14void remove(int index)
Removes the menu item at the specified index from this menu.
15void remove(MenuComponent item)
Removes the specified menu item from this menu.
16void removeAll()
Removes all items from this menu.
17void removeNotify()
Removes the menu's peer.

Methods inherited

This class inherits methods from the following classes:

  • java.awt.MenuItem

  • java.awt.MenuComponent

  • java.lang.Object

Menu Example

Create the following java program using any editor of your choice in say D:/ > AWT > com > tutorialspoint > gui >

AWTMenuDemo.java
package com.tutorialspoint.gui;

import java.awt.*;
import java.awt.event.*;

public class AWTMenuDemo {
   private Frame mainFrame;
   private Label headerLabel;
   private Label statusLabel;
   private Panel controlPanel;

   public AWTMenuDemo(){
      prepareGUI();
   }

   public static void main(String[] args){
      AWTMenuDemo  awtMenuDemo = new AWTMenuDemo();     
      awtMenuDemo.showMenuDemo();
   }

   private void prepareGUI(){
      mainFrame = new Frame("Java AWT Examples");
      mainFrame.setSize(400,400);
      mainFrame.setLayout(new GridLayout(3, 1));
      mainFrame.addWindowListener(new WindowAdapter() {
         public void windowClosing(WindowEvent windowEvent){
            System.exit(0);
         }        
      });    
      headerLabel = new Label();
      headerLabel.setAlignment(Label.CENTER);
      statusLabel = new Label();        
      statusLabel.setAlignment(Label.CENTER);
      statusLabel.setSize(350,100);

      controlPanel = new Panel();
      controlPanel.setLayout(new FlowLayout());

      mainFrame.add(headerLabel);
      mainFrame.add(controlPanel);
      mainFrame.add(statusLabel);
      mainFrame.setVisible(true);  
   }

   private void showMenuDemo(){
      //create a menu bar
      final MenuBar menuBar = new MenuBar();

      //create menus
      Menu fileMenu = new Menu("File");
      Menu editMenu = new Menu("Edit"); 
      final Menu aboutMenu = new Menu("About");

      //create menu items
      MenuItem newMenuItem = 
         new MenuItem("New",new MenuShortcut(KeyEvent.VK_N));
      newMenuItem.setActionCommand("New");

      MenuItem openMenuItem = new MenuItem("Open");
      openMenuItem.setActionCommand("Open");

      MenuItem saveMenuItem = new MenuItem("Save");
      saveMenuItem.setActionCommand("Save");

      MenuItem exitMenuItem = new MenuItem("Exit");
      exitMenuItem.setActionCommand("Exit");

      MenuItem cutMenuItem = new MenuItem("Cut");
      cutMenuItem.setActionCommand("Cut");

      MenuItem copyMenuItem = new MenuItem("Copy");
      copyMenuItem.setActionCommand("Copy");

      MenuItem pasteMenuItem = new MenuItem("Paste");
      pasteMenuItem.setActionCommand("Paste");
   
      MenuItemListener menuItemListener = new MenuItemListener();

      newMenuItem.addActionListener(menuItemListener);
      openMenuItem.addActionListener(menuItemListener);
      saveMenuItem.addActionListener(menuItemListener);
      exitMenuItem.addActionListener(menuItemListener);
      cutMenuItem.addActionListener(menuItemListener);
      copyMenuItem.addActionListener(menuItemListener);
      pasteMenuItem.addActionListener(menuItemListener);

      final CheckboxMenuItem showWindowMenu = 
         new CheckboxMenuItem("Show About", true);
      showWindowMenu.addItemListener(new ItemListener() {
         public void itemStateChanged(ItemEvent e) {
            if(showWindowMenu.getState()){
               menuBar.add(aboutMenu);
            }else{
               menuBar.remove(aboutMenu);
            }
         }
      });

      //add menu items to menus
      fileMenu.add(newMenuItem);
      fileMenu.add(openMenuItem);
      fileMenu.add(saveMenuItem);
      fileMenu.addSeparator();
      fileMenu.add(showWindowMenu);
      fileMenu.addSeparator();
      fileMenu.add(exitMenuItem);

      editMenu.add(cutMenuItem);
      editMenu.add(copyMenuItem);
      editMenu.add(pasteMenuItem);

      //add menu to menubar
      menuBar.add(fileMenu);
      menuBar.add(editMenu);
      menuBar.add(aboutMenu);

      //add menubar to the frame
      mainFrame.setMenuBar(menuBar);
      mainFrame.setVisible(true);  
   }

   class MenuItemListener implements ActionListener {
      public void actionPerformed(ActionEvent e) {            
         statusLabel.setText(e.getActionCommand() 
            + " MenuItem clicked.");
      }    
   }
}

Compile the program using command prompt. Go to D:/ > AWT and type the following command.

D:\AWT>javac com\tutorialspoint\gui\AWTMenuDemo.java

If no error comes that means compilation is successful. Run the program using following command.

D:\AWT>java com.tutorialspoint.gui.AWTMenuDemo

Verify the following output. (Click on File Menu.)

AWT Menu

AWT CheckboxMenuItem Class

Introduction

The CheckboxMenuItem class represents a check box which can be included in a menu. Selecting the check box in the menu changes control's state from on to off or from off to on.

Class declaration

Following is the declaration for java.awt.CheckboxMenuItem class:

public class CheckboxMenuItem
   extends MenuItem
      implements ItemSelectable, Accessible

Class constructors

S.N.Constructor & Description
1CheckboxMenuItem()
Create a check box menu item with an empty label.
2CheckboxMenuItem(String label)
Create a check box menu item with the specified label.
3CheckboxMenuItem(String label, boolean state)
Create a check box menu item with the specified label and state.

Class methods

S.N.Method & Description
1void addItemListener(ItemListener l)
Adds the specified item listener to receive item events from this check box menu item.
2void addNotify()
Creates the peer of the checkbox item.
3AccessibleContext getAccessibleContext()
Gets the AccessibleContext associated with this CheckboxMenuItem.
4ItemListener[] getItemListeners()
Returns an array of all the item listeners registered on this checkbox menuitem.
5<T extends EventListener> T[] getListeners(Class<T> listenerType)
Returns an array of all the objects currently registered as FooListeners upon this CheckboxMenuItem.
6Object[] getSelectedObjects()
Returns the an array (length 1) containing the checkbox menu item label or null if the checkbox is not selected.
7boolean getState()
Determines whether the state of this check box menu item is "on" or "off."
8String paramString()
Returns a string representing the state of this CheckBoxMenuItem.
9protected void processEvent(AWTEvent e)
Processes events on this check box menu item.
10protected void processItemEvent(ItemEvent e)
Processes item events occurring on this check box menu item by dispatching them to any registered ItemListener objects.
11void removeItemListener(ItemListener l)
Removes the specified item listener so that it no longer receives item events from this check box menu item.
12void setState(boolean b)
Sets this check box menu item to the specifed state.

Methods inherited

This class inherits methods from the following classes:

  • java.awt.MenuItem

  • java.awt.MenuComponent

  • java.lang.Object

CheckboxMenuItem Example

Create the following java program using any editor of your choice in say D:/ > AWT > com > tutorialspoint > gui >

AWTMenuDemo.java
package com.tutorialspoint.gui;

import java.awt.*;
import java.awt.event.*;

public class AWTMenuDemo {
   private Frame mainFrame;
   private Label headerLabel;
   private Label statusLabel;
   private Panel controlPanel;

   public AWTMenuDemo(){
      prepareGUI();
   }

   public static void main(String[] args){
      AWTMenuDemo  awtMenuDemo = new AWTMenuDemo();     
      awtMenuDemo.showMenuDemo();
   }

   private void prepareGUI(){
      mainFrame = new Frame("Java AWT Examples");
      mainFrame.setSize(400,400);
      mainFrame.setLayout(new GridLayout(3, 1));
      mainFrame.addWindowListener(new WindowAdapter() {
         public void windowClosing(WindowEvent windowEvent){
            System.exit(0);
         }        
      });    
      headerLabel = new Label();
      headerLabel.setAlignment(Label.CENTER);
      statusLabel = new Label();        
      statusLabel.setAlignment(Label.CENTER);
      statusLabel.setSize(350,100);

      controlPanel = new Panel();
      controlPanel.setLayout(new FlowLayout());

      mainFrame.add(headerLabel);
      mainFrame.add(controlPanel);
      mainFrame.add(statusLabel);
      mainFrame.setVisible(true);  
   }

   private void showMenuDemo(){
      //create a menu bar
      final MenuBar menuBar = new MenuBar();

      //create menus
      Menu fileMenu = new Menu("File");
      Menu editMenu = new Menu("Edit"); 
      final Menu aboutMenu = new Menu("About");

      //create menu items
      MenuItem newMenuItem = 
         new MenuItem("New",new MenuShortcut(KeyEvent.VK_N));
      newMenuItem.setActionCommand("New");

      MenuItem openMenuItem = new MenuItem("Open");
      openMenuItem.setActionCommand("Open");

      MenuItem saveMenuItem = new MenuItem("Save");
      saveMenuItem.setActionCommand("Save");

      MenuItem exitMenuItem = new MenuItem("Exit");
      exitMenuItem.setActionCommand("Exit");

      MenuItem cutMenuItem = new MenuItem("Cut");
      cutMenuItem.setActionCommand("Cut");

      MenuItem copyMenuItem = new MenuItem("Copy");
      copyMenuItem.setActionCommand("Copy");

      MenuItem pasteMenuItem = new MenuItem("Paste");
      pasteMenuItem.setActionCommand("Paste");
   
      MenuItemListener menuItemListener = new MenuItemListener();

      newMenuItem.addActionListener(menuItemListener);
      openMenuItem.addActionListener(menuItemListener);
      saveMenuItem.addActionListener(menuItemListener);
      exitMenuItem.addActionListener(menuItemListener);
      cutMenuItem.addActionListener(menuItemListener);
      copyMenuItem.addActionListener(menuItemListener);
      pasteMenuItem.addActionListener(menuItemListener);

      final CheckboxMenuItem showWindowMenu = 
         new CheckboxMenuItem("Show About", true);
      showWindowMenu.addItemListener(new ItemListener() {
         public void itemStateChanged(ItemEvent e) {
            if(showWindowMenu.getState()){
               menuBar.add(aboutMenu);
            }else{
               menuBar.remove(aboutMenu);
            }
         }
      });

      //add menu items to menus
      fileMenu.add(newMenuItem);
      fileMenu.add(openMenuItem);
      fileMenu.add(saveMenuItem);
      fileMenu.addSeparator();
      fileMenu.add(showWindowMenu);
      fileMenu.addSeparator();
      fileMenu.add(exitMenuItem);

      editMenu.add(cutMenuItem);
      editMenu.add(copyMenuItem);
      editMenu.add(pasteMenuItem);

      //add menu to menubar
      menuBar.add(fileMenu);
      menuBar.add(editMenu);
      menuBar.add(aboutMenu);

      //add menubar to the frame
      mainFrame.setMenuBar(menuBar);
      mainFrame.setVisible(true);  
   }

   class MenuItemListener implements ActionListener {
      public void actionPerformed(ActionEvent e) {            
         statusLabel.setText(e.getActionCommand() 
            + " MenuItem clicked.");
      }    
   }
}

Compile the program using command prompt. Go to D:/ > AWT and type the following command.

D:\AWT>javac com\tutorialspoint\gui\AWTMenuDemo.java

If no error comes that means compilation is successful. Run the program using following command.

D:\AWT>java com.tutorialspoint.gui.AWTMenuDemo

Verify the following output. (Click on File Menu. Unselect "Show About" menu item.)

AWT CheckboxMenuItem

AWT PopupMenu Class

Introduction

Popup menu represents a menu which can be dynamically popped up at a specified position within a component.

Class declaration

Following is the declaration for java.awt.PopupMenu class:

public class CheckboxMenuItem
   extends MenuItem
      implements ItemSelectable, Accessible

Class constructors

S.N.Constructor & Description
1PopupMenu()
Creates a new popup menu with an empty name.
2PopupMenu(String label)
Creates a new popup menu with the specified name.

Class methods

S.N.Method & Description
1void addNotify()
Creates the popup menu's peer.
2AccessibleContext getAccessibleContext()
Gets the AccessibleContext associated with this PopupMenu.
3MenuContainer getParent()
Returns the parent container for this menu component.
4void show(Component origin, int x, int y)
Shows the popup menu at the x, y position relative to an origin component.

Methods inherited

This class inherits methods from the following classes:

  • java.awt.MenuItem

  • java.awt.MenuComponent

  • java.lang.Object

PopupMenu Example

Create the following java program using any editor of your choice in say D:/ > AWT > com > tutorialspoint > gui >

AWTMenuDemo.java
package com.tutorialspoint.gui;

import java.awt.*;
import java.awt.event.*;

public class AWTMenuDemo {
   private Frame mainFrame;
   private Label headerLabel;
   private Label statusLabel;
   private Panel controlPanel;

   public AWTMenuDemo(){
      prepareGUI();
   }

   public static void main(String[] args){
      AWTMenuDemo  awtMenuDemo = new AWTMenuDemo();     
      awtMenuDemo.showPopupMenuDemo();
   }

   private void prepareGUI(){
      mainFrame = new Frame("Java AWT Examples");
      mainFrame.setSize(400,400);
      mainFrame.setLayout(new GridLayout(3, 1));
      mainFrame.addWindowListener(new WindowAdapter() {
         public void windowClosing(WindowEvent windowEvent){
            System.exit(0);
         }        
      });    
      headerLabel = new Label();
      headerLabel.setAlignment(Label.CENTER);
      statusLabel = new Label();        
      statusLabel.setAlignment(Label.CENTER);
      statusLabel.setSize(350,100);

      controlPanel = new Panel();
      controlPanel.setLayout(new FlowLayout());

      mainFrame.add(headerLabel);
      mainFrame.add(controlPanel);
      mainFrame.add(statusLabel);
      mainFrame.setVisible(true);  
   }

   private void showPopupMenuDemo(){
      final PopupMenu editMenu = new PopupMenu("Edit"); 

      MenuItem cutMenuItem = new MenuItem("Cut");
      cutMenuItem.setActionCommand("Cut");

      MenuItem copyMenuItem = new MenuItem("Copy");
      copyMenuItem.setActionCommand("Copy");

      MenuItem pasteMenuItem = new MenuItem("Paste");
      pasteMenuItem.setActionCommand("Paste");

      MenuItemListener menuItemListener = new MenuItemListener();

      cutMenuItem.addActionListener(menuItemListener);
      copyMenuItem.addActionListener(menuItemListener);
      pasteMenuItem.addActionListener(menuItemListener);

      editMenu.add(cutMenuItem);
      editMenu.add(copyMenuItem);
      editMenu.add(pasteMenuItem);   
      
      controlPanel.addMouseListener(new MouseAdapter() {
         public void mouseClicked(MouseEvent e) {            
               editMenu.show(controlPanel, e.getX(), e.getY());
         }               
      });
      controlPanel.add(editMenu); 

      mainFrame.setVisible(true);
   }
	
   class MenuItemListener implements ActionListener {
      public void actionPerformed(ActionEvent e) {            
         statusLabel.setText(e.getActionCommand() 
            + " MenuItem clicked.");
      }    
   }
}

Compile the program using command prompt. Go to D:/ > AWT and type the following command.

D:\AWT>javac com\tutorialspoint\gui\AWTMenuDemo.java

If no error comes that means compilation is successful. Run the program using following command.

D:\AWT>java com.tutorialspoint.gui.AWTMenuDemo

Verify the following output. (Click in the middle on the screen.)

AWT PopupMenu

AWT Graphics Classes

Graphics controls allows application to draw onto the component or on image.

AWT Graphics Class

Introduction

The Graphics class is the abstract super class for all graphics contexts which allow an application to draw onto components that can be realized on various devices, or onto off-screen images as well.

A Graphics object encapsulates all state information required for the basic rendering operations that Java supports. State information includes the following properties.

  • The Component object on which to draw.

  • A translation origin for rendering and clipping coordinates.

  • The current clip.

  • The current color.

  • The current font.

  • The current logical pixel operation function.

  • The current XOR alternation color

Class declaration

Following is the declaration for java.awt.Graphics class:

public abstract class Graphics
   extends Object

Class constructors

S.N.Constructor & Description
1Graphics() ()
Constructs a new Graphics object.

Class methods

S.N.Method & Description
1abstract void clearRect(int x, int y, int width, int height)
Clears the specified rectangle by filling it with the background color of the current drawing surface.
2abstract void clipRect(int x, int y, int width, int height)
Intersects the current clip with the specified rectangle.
3abstract void copyArea(int x, int y, int width, int height, int dx, int dy)
Copies an area of the component by a distance specified by dx and dy.
4abstract Graphics create()
Creates a new Graphics object that is a copy of this Graphics object.
5Graphics create(int x, int y, int width, int height)
Creates a new Graphics object based on this Graphics object, but with a new translation and clip area.
6abstract void dispose()
Disposes of this graphics context and releases any system resources that it is using.
7void draw3DRect(int x, int y, int width, int height, boolean raised)
Draws a 3-D highlighted outline of the specified rectangle.
8abstract void drawArc(int x, int y, int width, int height, int startAngle, int arcAngle)
Draws the outline of a circular or elliptical arc covering the specified rectangle.
9void drawBytes(byte[] data, int offset, int length, int x, int y)
Draws the text given by the specified byte array, using this graphics context's current font and color.
10void drawChars(char[] data, int offset, int length, int x, int y)
Draws the text given by the specified character array, using this graphics context's current font and color.
11abstract boolean drawImage(Image img, int x, int y, Color bgcolor, ImageObserver observer)
Draws as much of the specified image as is currently available.
12abstract boolean drawImage(Image img, int x, int y, ImageObserver observer)
Draws as much of the specified image as is currently available.
13abstract boolean drawImage(Image img, int x, int y, int width, int height, Color bgcolor, ImageObserver observer)
Draws as much of the specified image as has already been scaled to fit inside the specified rectangle.
14abstract boolean drawImage(Image img, int x, int y, int width, int height, ImageObserver observer)
Draws as much of the specified image as has already been scaled to fit inside the specified rectangle.
15abstract boolean drawImage(Image img, int dx1, int dy1, int dx2, int dy2, int sx1, int sy1, int sx2, int sy2, Color bgcolor, ImageObserver observer)
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.
16abstract boolean drawImage(Image img, int dx1, int dy1, int dx2, int dy2, int sx1, int sy1, int sx2, int sy2, ImageObserver observer)
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.
17abstract void drawLine(int x1, int y1, int x2, int y2)
Draws a line, using the current color, between the points (x1, y1) and (x2, y2) in this graphics context's coordinate system.
18abstract void drawOval(int x, int y, int width, int height)
Draws the outline of an oval.
19abstract void drawPolygon(int[] xPoints, int[] yPoints, int nPoints)
Draws a closed polygon defined by arrays of x and y coordinates.
20void drawPolygon(Polygon p)
Draws the outline of a polygon defined by the specified Polygon object.
21abstract void drawPolyline(int[] xPoints, int[] yPoints, int nPoints)
Draws a sequence of connected lines defined by arrays of x and y coordinates.
22void drawRect(int x, int y, int width, int height)
Draws the outline of the specified rectangle.
23abstract void drawRoundRect(int x, int y, int width, int height, int arcWidth, int arcHeight)
Draws an outlined round-cornered rectangle using this graphics context's current color.
24abstract void drawString(AttributedCharacterIterator iterator, int x, int y)
Renders the text of the specified iterator applying its attributes in accordance with the specification of the TextAttribute class.
25abstract void drawString(String str, int x, int y)
Draws the text given by the specified string, using this graphics context's current font and color.
26void fill3DRect(int x, int y, int width, int height, boolean raised)
Paints a 3-D highlighted rectangle filled with the current color.
27abstract void fillArc(int x, int y, int width, int height, int startAngle, int arcAngle)
Fills a circular or elliptical arc covering the specified rectangle.
28abstract void fillOval(int x, int y, int width, int height)
Fills an oval bounded by the specified rectangle with the current color.
29abstract void fillPolygon(int[] xPoints, int[] yPoints, int nPoints)
Fills a closed polygon defined by arrays of x and y coordinates.
30void fillPolygon(Polygon p)
Fills the polygon defined by the specified Polygon object with the graphics context's current color.
31abstract void fillRect(int x, int y, int width, int height)
Fills the specified rectangle.
32abstract void fillRoundRect(int x, int y, int width, int height, int arcWidth, int arcHeight)
Fills the specified rounded corner rectangle with the current color.
33void finalize()
Disposes of this graphics context once it is no longer referenced.
34abstract Shape getClip()
Gets the current clipping area.
35abstract Rectangle getClipBounds()
Returns the bounding rectangle of the current clipping area.
36Rectangle getClipBounds(Rectangle r)
Returns the bounding rectangle of the current clipping area.
37Rectangle getClipRect()
Deprecated. As of JDK version 1.1, replaced by getClipBounds().
38abstract Color getColor()
Gets this graphics context's current color.
39abstract Font getFont()
Gets the current font.
40FontMetrics getFontMetrics()
Gets the font metrics of the current font.
41abstract FontMetrics getFontMetrics(Font f)
Gets the font metrics for the specified font.
42boolean hitClip(int x, int y, int width, int height)
Returns true if the specified rectangular area might intersect the current clipping area.
43abstract void setClip(int x, int y, int width, int height)
Sets the current clip to the rectangle specified by the given coordinates.
44abstract void setClip(Shape clip)
Sets the current clipping area to an arbitrary clip shape.
45abstract void setColor(Color c)
Sets this graphics context's current color to the specified color.
46abstract void setFont(Font font)
Sets this graphics context's font to the specified font.
47abstract void setPaintMode()
Sets the paint mode of this graphics context to overwrite the destination with this graphics context's current color.
48abstract void setXORMode(Color c1)
Sets the paint mode of this graphics context to alternate between this graphics context's current color and the new specified color.
49String toString()
Returns a String object representing this Graphics object's value.
50abstract void translate(int x, int y)
Translates the origin of the graphics context to the point (x, y) in the current coordinate system.

Methods inherited

This class inherits methods from the following classes:

  • java.lang.Object

Graphics Example

Create the following java program using any editor of your choice in say D:/ > AWT > com > tutorialspoint > gui >

AWTGraphicsDemo.java
package com.tutorialspoint.gui;

import java.awt.*;
import java.awt.event.*;
import java.awt.geom.*;

public class AWTGraphicsDemo extends Frame {
       
   public AWTGraphicsDemo(){
      super("Java AWT Examples");
      prepareGUI();
   }

   public static void main(String[] args){
      AWTGraphicsDemo  awtGraphicsDemo = new AWTGraphicsDemo();  
      awtGraphicsDemo.setVisible(true);
   }

   private void prepareGUI(){
      setSize(400,400);
      addWindowListener(new WindowAdapter() {
         public void windowClosing(WindowEvent windowEvent){
            System.exit(0);
         }        
      }); 
   }    

   @Override
   public void paint(Graphics g) {
      g.setColor(Color.GRAY);
      Font font = new Font("Serif", Font.PLAIN, 24);
      g.setFont(font);
      g.drawString("Welcome to TutorialsPoint", 50, 150);      
   }
}

Compile the program using command prompt. Go to D:/ > AWT and type the following command.

D:\AWT>javac com\tutorialspoint\gui\AWTGraphicsDemo.java

If no error comes that means compilation is successful. Run the program using following command.

D:\AWT>java com.tutorialspoint.gui.AWTGraphicsDemo

Verify the following output

AWT Graphics

AWT Graphics2D Class

Introduction

The Graphics2D class extends the Graphics class to provide more sophisticated control over geometry, coordinate transformations, color management, and text layout.

Class declaration

Following is the declaration for java.awt.Graphics2D class:

public abstract class Graphics2D
   extends Graphics

Class constructors

S.N.Constructor & Description
1Graphics2D()
Constructs a new Graphics2D object.

Class methods

S.N.Method & Description
1abstract void addRenderingHints(Map hints)
Sets the values of an arbitrary number of preferences for the rendering algorithms.
2abstract void clip(Shape s)
Intersects the current Clip with the interior of the specified Shape and sets the Clip to the resulting intersection.
3abstract void draw(Shape s)
Strokes the outline of a Shape using the settings of the current Graphics2D context.
4void draw3DRect(int x, int y, int width, int height, boolean raised)
Draws a 3-D highlighted outline of the specified rectangle.
5abstract void drawGlyphVector(GlyphVector g, float x, float y)
Renders the text of the specified GlyphVector using the Graphics2D context's rendering attributes.
6abstract void drawImage(BufferedImage img, BufferedImageOp op, int x, int y)
Renders a BufferedImage that is filtered with a BufferedImageOp.
7abstract boolean drawImage(Image img, AffineTransform xform, ImageObserver obs)
Renders an image, applying a transform from image space into user space before drawing.
8abstract void drawRenderableImage(RenderableImage img, AffineTransform xform)
Renders a RenderableImage, applying a transform from image space into user space before drawing.
9abstract void drawRenderedImage(RenderedImage img, AffineTransform xform)
Renders a RenderedImage, applying a transform from image space into user space before drawing.
10abstract void drawString(AttributedCharacterIterator iterator, float x, float y)
Renders the text of the specified iterator applying its attributes in accordance with the specification of the TextAttribute class.
11abstract void drawString(AttributedCharacterIterator iterator, int x, int y)
Renders the text of the specified iterator applying its attributes in accordance with the specification of the TextAttribute class.
12abstract void drawString(String str, float x, float y)
Renders the text specified by the specified String, using the current text attribute state in the Graphics2D context.
13abstract void drawString(String str, int x, int y)
Renders the text of the specified String, using the current text attribute state in the Graphics2D context.
14abstract void fill(Shape s)
Fills the interior of a Shape using the settings of the Graphics2D context.
15void fill3DRect(int x, int y, int width, int height, boolean raised)
Paints a 3-D highlighted rectangle filled with the current color.
16abstract Color getBackground()
Returns the background color used for clearing a region.
17abstract Composite getComposite()
Returns the current Composite in the Graphics2D context.
18abstract GraphicsConfiguration getDeviceConfiguration()
Returns the device configuration associated with this Graphics2D.
19abstract FontRenderContext getFontRenderContext()
Get the rendering context of the Font within this Graphics2D context.
20abstract Paint getPaint()
Returns the current Paint of the Graphics2D context.
21abstract Object getRenderingHint(RenderingHints.Key hintKey)
Returns the value of a single preference for the rendering algorithms.
22abstract RenderingHints getRenderingHints()
Gets the preferences for the rendering algorithms.
23abstract Stroke getStroke()
Returns the current Stroke in the Graphics2D context.
24abstract AffineTransform getTransform()
Returns a copy of the current Transform in the Graphics2D context.
25abstract boolean hit(Rectangle rect, Shape s, boolean onStroke)
Checks whether or not the specified Shape intersects the specified Rectangle, which is in device space.
26abstract void rotate(double theta)
Concatenates the current Graphics2D Transform with a rotation transform.
27abstract void rotate(double theta, double x, double y)
Concatenates the current Graphics2D Transform with a translated rotation transform.
28abstract void scale(double sx, double sy)
Concatenates the current Graphics2D Transform with a scaling transformation Subsequent rendering is resized according to the specified scaling factors relative to the previous scaling.
29abstract void setBackground(Color color)
Sets the background color for the Graphics2D context.
30abstract void setComposite(Composite comp)
Sets the Composite for the Graphics2D context.
31abstract void setPaint(Paint paint)
Sets the Paint attribute for the Graphics2D context.
32abstract void setRenderingHint(RenderingHints.Key hintKey, Object hintValue)
Sets the value of a single preference for the rendering algorithms.
33abstract void setRenderingHints(Map hints)
Replaces the values of all preferences for the rendering algorithms with the specified hints.
34abstract void setStroke(Stroke s)
Sets the Stroke for the Graphics2D context.
35abstract void setTransform(AffineTransform Tx)
Overwrites the Transform in the Graphics2D context.
36abstract void shear(double shx, double shy)
Concatenates the current Graphics2D Transform with a shearing transform.
37abstract void transform(AffineTransform Tx)
Composes an AffineTransform object with the Transform in this Graphics2D according to the rule last-specified-first-applied.
38abstract void translate(double tx, double ty)
Concatenates the current Graphics2D Transform with a translation transform.
39abstract void translate(int x, int y)
Translates the origin of the Graphics2D context to the point (x, y) in the current coordinate system.

Methods inherited

This class inherits methods from the following classes:

  • java.lang.Object

Graphics2D Example

Create the following java program using any editor of your choice in say D:/ > AWT > com > tutorialspoint > gui >

AWTGraphicsDemo.java
package com.tutorialspoint.gui;

import java.awt.*;
import java.awt.event.*;
import java.awt.geom.*;

public class AWTGraphicsDemo extends Frame {
       
   public AWTGraphicsDemo(){
      super("Java AWT Examples");
      prepareGUI();
   }

   public static void main(String[] args){
      AWTGraphicsDemo  awtGraphicsDemo = new AWTGraphicsDemo();  
      awtGraphicsDemo.setVisible(true);
   }

   private void prepareGUI(){
      setSize(400,400);
      addWindowListener(new WindowAdapter() {
         public void windowClosing(WindowEvent windowEvent){
            System.exit(0);
         }        
      }); 
   }    

   @Override
   public void paint(Graphics g) {
      Graphics2D g2 = (Graphics2D)g;
      g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
         RenderingHints.VALUE_ANTIALIAS_ON);
      Font font = new Font("Serif", Font.PLAIN, 24);
      g2.setFont(font);
      g2.drawString("Welcome to TutorialsPoint", 50, 70); 
   }
}

Compile the program using command prompt. Go to D:/ > AWT and type the following command.

D:\AWT>javac com\tutorialspoint\gui\AWTGraphicsDemo.java

If no error comes that means compilation is successful. Run the program using following command.

D:\AWT>java com.tutorialspoint.gui.AWTGraphicsDemo

Verify the following output

AWT Graphics2D

AWT Arc2D Class

Introduction

The Arc2D class is the superclass for all objects that store a 2D arc defined by a framing rectangle, start angle, angular extent (length of the arc), and a closure type (OPEN, CHORD, or PIE).

Class declaration

Following is the declaration for java.awt.Arc2D class:

public abstract class Arc2D
   extends RectangularShape

Field

Following are the fields for java.awt.geom.Arc2D class:

  • static int CHORD -- The closure type for an arc closed by drawing a straight line segment from the start of the arc segment to the end of the arc segment.

  • static int OPEN -- The closure type for an open arc with no path segments connecting the two ends of the arc segment.

  • static int PIE -- The closure type for an arc closed by drawing straight line segments from the start of the arc segment to the center of the full ellipse and from that point to the end of the arc segment.

Class constructors

S.N.Constructor & Description
1protected Arc2D(int type)
This is an abstract class that cannot be instantiated directly.

Class methods

S.N.Method & Description
1boolean contains(double x, double y)
Determines whether or not the specified point is inside the boundary of the arc.
2boolean contains(double x, double y, double w, double h)
Determines whether or not the interior of the arc entirely contains the specified rectangle.
3boolean contains(Rectangle2D r)
Determines whether or not the interior of the arc entirely contains the specified rectangle.
4boolean containsAngle(double angle)
Determines whether or not the specified angle is within the angular extents of the arc.
5boolean equals(Object obj)
Determines whether or not the specified Object is equal to this Arc2D.
6abstract double getAngleExtent()
Returns the angular extent of the arc.
7abstract double getAngleStart()
Returns the starting angle of the arc.
8int getArcType()
Returns the arc closure type of the arc: OPEN, CHORD, or PIE.
9Rectangle2D getBounds2D()
Returns the high-precision framing rectangle of the arc.
10Point2D getEndPoint()
Returns the ending point of the arc.
11PathIterator getPathIterator(AffineTransform at)
Returns an iteration object that defines the boundary of the arc.
12Point2D getStartPoint()
Returns the starting point of the arc.
13int hashCode()
Returns the hashcode for this Arc2D.
14boolean intersects(double x, double y, double w, double h)
Determines whether or not the interior of the arc intersects the interior of the specified rectangle.
15protected abstract Rectangle2D makeBounds(double x, double y, double w, double h)
Constructs a Rectangle2D of the appropriate precision to hold the parameters calculated to be the framing rectangle of this arc.
16abstract void setAngleExtent(double angExt)
Sets the angular extent of this arc to the specified double value.
17void setAngles(double x1, double y1, double x2, double y2)
Sets the starting angle and angular extent of this arc using two sets of coordinates.
18void setAngles(Point2D p1, Point2D p2)
Sets the starting angle and angular extent of this arc using two points.
19abstract void setAngleStart(double angSt)
Sets the starting angle of this arc to the specified double value.
20void setAngleStart(Point2D p)
Sets the starting angle of this arc to the angle that the specified point defines relative to the center of this arc.
21void setArc(Arc2D a)
Sets this arc to be the same as the specified arc.
22abstract void setArc(double x, double y, double w, double h, double angSt, double angExt, int closure)
Sets the location, size, angular extents, and closure type of this arc to the specified double values.
23void setArc(Point2D loc, Dimension2D size, double angSt, double angExt, int closure)
Sets the location, size, angular extents, and closure type of this arc to the specified values.
24void setArc(Rectangle2D rect, double angSt, double angExt, int closure)
Sets the location, size, angular extents, and closure type of this arc to the specified values.
25void setArcByCenter(double x, double y, double radius, double angSt, double angExt, int closure)
Sets the position, bounds, angular extents, and closure type of this arc to the specified values.
26void setArcByTangent(Point2D p1, Point2D p2, Point2D p3, double radius)
Sets the position, bounds, and angular extents of this arc to the specified value.
27void setArcType(int type)
Sets the closure type of this arc to the specified value: OPEN, CHORD, or PIE.
28void setFrame(double x, double y, double w, double h)
Sets the location and size of the framing rectangle of this Shape to the specified rectangular values.

Methods inherited

This class inherits methods from the following classes:

  • java.awt.geom.RectangularShape

  • java.lang.Object

Arc2D Example

Create the following java program using any editor of your choice in say D:/ > AWT > com > tutorialspoint > gui >

AWTGraphicsDemo.java
package com.tutorialspoint.gui;

import java.awt.*;
import java.awt.event.*;
import java.awt.geom.*;

public class AWTGraphicsDemo extends Frame {
       
   public AWTGraphicsDemo(){
      super("Java AWT Examples");
      prepareGUI();
   }

   public static void main(String[] args){
      AWTGraphicsDemo  awtGraphicsDemo = new AWTGraphicsDemo();  
      awtGraphicsDemo.setVisible(true);
   }

   private void prepareGUI(){
      setSize(400,400);
      addWindowListener(new WindowAdapter() {
         public void windowClosing(WindowEvent windowEvent){
            System.exit(0);
         }        
      }); 
   }    

   @Override
   public void paint(Graphics g) {
      Arc2D.Float arc = new Arc2D.Float(Arc2D.PIE);
      arc.setFrame(70, 200, 150, 150);
      arc.setAngleStart(0);
      arc.setAngleExtent(145);
      Graphics2D g2 = (Graphics2D) g; 
      g2.setColor(Color.gray);
      g2.draw(arc);
      g2.setColor(Color.red);
      g2.fill(arc);
      g2.setColor(Color.black);
      Font font = new Font("Serif", Font.PLAIN, 24);
      g2.setFont(font);
      g.drawString("Welcome to TutorialsPoint", 50, 70);
      g2.drawString("Arc2D.PIE", 100, 120); 
   }
}

Compile the program using command prompt. Go to D:/ > AWT and type the following command.

D:\AWT>javac com\tutorialspoint\gui\AwtGraphicsDemo.java

If no error comes that means compilation is successful. Run the program using following command.

D:\AWT>java com.tutorialspoint.gui.AwtGraphicsDemo

Verify the following output

AWT Arc2D

AWT CubicCurve2D Class

Introduction

The CubicCurve2D class states a cubic parametric curve segment in (x,y) coordinate space.

Class declaration

Following is the declaration for java.awt.geom.CubicCurve2D class:

public abstract class CubicCurve2D
   extends Object
      implements Shape, Cloneable

Class constructors

S.N.Constructor & Description
1protected CubicCurve2D()
This is an abstract class that cannot be instantiated directly.

Class methods

S.N.Method & Description
1Object clone()
Creates a new object of the same class as this object.
2boolean contains(double x, double y)
Tests if the specified coordinates are inside the boundary of the Shape.
3boolean contains(double x, double y, double w, double h)
Tests if the interior of the Shape entirely contains the specified rectangular area.
4boolean contains(Point2D p)
Tests if a specified Point2D is inside the boundary of the Shape.
5boolean contains(Rectangle2D r)
Tests if the interior of the Shape entirely contains the specified Rectangle2D.
6Rectangle getBounds()
Returns an integer Rectangle that completely encloses the Shape.
7abstract Point2D getCtrlP1()
Returns the first control point.
8abstract Point2D getCtrlP2()
Returns the second control point.
9abstract double getCtrlX1()
Returns the X coordinate of the first control point in double precision.
10abstract double getCtrlX2()
Returns the X coordinate of the second control point in double precision.
11abstract double getCtrlY1()
Returns the Y coordinate of the first control point in double precision.
12abstract double getCtrlY2()
Returns the Y coordinate of the second control point in double precision.
13double getFlatness()
Returns the flatness of this curve.
14static double getFlatness(double[] coords, int offset)
Returns the flatness of the cubic curve specified by the control points stored in the indicated array at the indicated index.
15static double getFlatness(double x1, double y1, double ctrlx1, double ctrly1, double ctrlx2, double ctrly2, double x2, double y2)
Returns the flatness of the cubic curve specified by the indicated control points.
16double getFlatnessSq()
Returns the square of the flatness of this curve.
17static double getFlatnessSq(double[] coords, int offset)
Returns the square of the flatness of the cubic curve specified by the control points stored in the indicated array at the indicated index.
18static double getFlatnessSq(double x1, double y1, double ctrlx1, double ctrly1, double ctrlx2, double ctrly2, double x2, double y2)
Returns the square of the flatness of the cubic curve specified by the indicated control points.
19abstract Point2D getP1()
Returns the start point.
20abstract Point2D getP2()
Returns the end point.
21PathIterator getPathIterator(AffineTransform at)
Returns an iteration object that defines the boundary of the shape.
22PathIterator getPathIterator(AffineTransform at, double flatness)
Return an iteration object that defines the boundary of the flattened shape.
23abstract double getX1()
Returns the X coordinate of the start point in double precision.
24abstract double getX2()
Returns the X coordinate of the end point in double precision.
25abstract double getY1()
Returns the Y coordinate of the start point in double precision.
26abstract double getY2()
Returns the Y coordinate of the end point in double precision.
27boolean intersects(double x, double y, double w, double h)
Tests if the interior of the Shape intersects the interior of a specified rectangular area.
28boolean intersects(Rectangle2D r)
Tests if the interior of the Shape intersects the interior of a specified Rectangle2D.
29void setCurve(CubicCurve2D c)
Sets the location of the end points and control points of this curve to the same as those in the specified CubicCurve2D.
30void setCurve(double[] coords, int offset)
Sets the location of the end points and control points of this curve to the double coordinates at the specified offset in the specified array.
31abstract void setCurve(double x1, double y1, double ctrlx1, double ctrly1, double ctrlx2, double ctrly2, double x2, double y2)
Sets the location of the end points and control points of this curve to the specified double coordinates.
32void setCurve(Point2D[] pts, int offset)
Sets the location of the end points and control points of this curve to the coordinates of the Point2D objects at the specified offset in the specified array.
33void setCurve(Point2D p1, Point2D cp1, Point2D cp2, Point2D p2)
Sets the location of the end points and control points of this curve to the specified Point2D coordinates.
34static int solveCubic(double[] eqn)
Solves the cubic whose coefficients are in the eqn array and places the non-complex roots back into the same array, returning the number of roots.
35static int solveCubic(double[] eqn, double[] res)
Solve the cubic whose coefficients are in the eqn array and place the non-complex roots into the res array, returning the number of roots.
36void subdivide(CubicCurve2D left, CubicCurve2D right)
Subdivides this cubic curve and stores the resulting two subdivided curves into the left and right curve parameters.
37static void subdivide(CubicCurve2D src, CubicCurve2D left, CubicCurve2D right)
Subdivides the cubic curve specified by the src parameter and stores the resulting two subdivided curves into the left and right curve parameters.
38static void subdivide(double[] src, int srcoff, double[] left, int leftoff, double[] right, int rightoff)
Subdivides the cubic curve specified by the coordinates stored in the src array at indices srcoff through (srcoff + 7) and stores the resulting two subdivided curves into the two result arrays at the corresponding indices.

Methods inherited

This class inherits methods from the following classes:

  • java.lang.Object

CubicCurve2D Example

Create the following java program using any editor of your choice in say D:/ > AWT > com > tutorialspoint > gui >

AWTGraphicsDemo.java
package com.tutorialspoint.gui;

import java.awt.*;
import java.awt.event.*;
import java.awt.geom.*;

public class AWTGraphicsDemo extends Frame {
       
   public AWTGraphicsDemo(){
      super("Java AWT Examples");
      prepareGUI();
   }

   public static void main(String[] args){
      AWTGraphicsDemo  awtGraphicsDemo = new AWTGraphicsDemo();  
      awtGraphicsDemo.setVisible(true);
   }

   private void prepareGUI(){
      setSize(400,400);
      addWindowListener(new WindowAdapter() {
         public void windowClosing(WindowEvent windowEvent){
            System.exit(0);
         }        
      }); 
   }    

   @Override
   public void paint(Graphics g) {
      CubicCurve2D shape = new CubicCurve2D.Float();
      shape.setCurve(250F,250F,20F,90F,140F,100F,350F,330F);       
      Graphics2D g2 = (Graphics2D) g; 
      g2.draw (shape);
      Font font = new Font("Serif", Font.PLAIN, 24);
      g2.setFont(font);
      g.drawString("Welcome to TutorialsPoint", 50, 70);
      g2.drawString("CubicCurve2D.Curve", 100, 120);
   }
}

Compile the program using command prompt. Go to D:/ > AWT and type the following command.

D:\AWT>javac com\tutorialspoint\gui\AWTGraphicsDemo.java

If no error comes that means compilation is successful. Run the program using following command.

D:\AWT>java com.tutorialspoint.gui.AWTGraphicsDemo

Verify the following output

AWT CubicCurve2D

AWT Ellipse2D Class

Introduction

The Ellipse2D class states an ellipse that is defined by a framing rectangle.

Class declaration

Following is the declaration for java.awt.geom.Ellipse2D class:

public abstract class Ellipse2D
   extends RectangularShape

Class constructors

S.N.Constructor & Description
1protected Ellipse2D()
This is an abstract class that cannot be instantiated directly.

Class methods

S.N.Method & Description
1boolean contains(double x, double y)
Tests if the specified coordinates are inside the boundary of the Shape.
2boolean contains(double x, double y, double w, double h)
Tests if the interior of the Shape entirely contains the specified rectangular area.
3boolean equals(Object obj)
Determines whether or not the specified Object is equal to this Ellipse2D.
4PathIterator getPathIterator(AffineTransform at)
Returns an iteration object that defines the boundary of this Ellipse2D.
5int hashCode()
Returns the hashcode for this Ellipse2D.
6boolean intersects(double x, double y, double w, double h)
Tests if the interior of the Shape intersects the interior of a specified rectangular area.

Methods inherited

This class inherits methods from the following classes:

  • java.lang.Object

Ellipse2D Example

Create the following java program using any editor of your choice in say D:/ > AWT > com > tutorialspoint > gui >

AWTGraphicsDemo.java
package com.tutorialspoint.gui;

import java.awt.*;
import java.awt.event.*;
import java.awt.geom.*;

public class AWTGraphicsDemo extends Frame {
       
   public AWTGraphicsDemo(){
      super("Java AWT Examples");
      prepareGUI();
   }

   public static void main(String[] args){
      AWTGraphicsDemo  awtGraphicsDemo = new AWTGraphicsDemo();  
      awtGraphicsDemo.setVisible(true);
   }

   private void prepareGUI(){
      setSize(400,400);
      addWindowListener(new WindowAdapter() {
         public void windowClosing(WindowEvent windowEvent){
            System.exit(0);
         }        
      }); 
   }    

   @Override
   public void paint(Graphics g) {
      Ellipse2D shape = new Ellipse2D.Float();
      shape.setFrame(100, 150, 200,100);
      Graphics2D g2 = (Graphics2D) g; 
      g2.draw (shape);
      Font font = new Font("Serif", Font.PLAIN, 24);
      g2.setFont(font);
      g.drawString("Welcome to TutorialsPoint", 50, 70);
      g2.drawString("Ellipse2D.Oval", 100, 120); 
   }
}

Compile the program using command prompt. Go to D:/ > AWT and type the following command.

D:\AWT>javac com\tutorialspoint\gui\AWTGraphicsDemo.java

If no error comes that means compilation is successful. Run the program using following command.

D:\AWT>java com.tutorialspoint.gui.AWTGraphicsDemo

Verify the following output

AWT Ellipse2D

AWT Rectangle2D Class

Introduction

The Rectangle2D class states a rectangle defined by a location (x,y) and dimension (w x h).

Class declaration

Following is the declaration for java.awt.geom.Rectangle2D class:

public abstract class Rectangle2D
   extends RectangularShape

Field

Following are the fields for java.awt.geom.Arc2D class:

  • static int OUT_BOTTOM -- The bitmask that indicates that a point lies below this Rectangle2D.

  • static int OUT_LEFT -- The bitmask that indicates that a point lies to the left of this Rectangle2D.

  • static int OUT_RIGHT -- The bitmask that indicates that a point lies to the right of this Rectangle2D.

  • static int OUT_TOP -- The bitmask that indicates that a point lies above this Rectangle2D.

Class constructors

S.N.Constructor & Description
1protected Rectangle2D()
This is an abstract class that cannot be instantiated directly.

Class methods

S.N.Method & Description
1void add(double newx, double newy)
Adds a point, specified by the double precision arguments newx and newy, to this Rectangle2D.
2void add(Point2D pt)
Adds the Point2D object pt to this Rectangle2D.
3void add(Rectangle2D r)
Adds a Rectangle2D object to this Rectangle2D.
4boolean contains(double x, double y)
Tests if the specified coordinates are inside the boundary of the Shape.
5boolean contains(double x, double y, double w, double h)
Tests if the interior of the Shape entirely contains the specified rectangular area.
6abstract Rectangle2D createIntersection(Rectangle2D r)
Returns a new Rectangle2D object representing the intersection of this Rectangle2D with the specified Rectangle2D.
7abstract Rectangle2D createUnion(Rectangle2D r)
Returns a new Rectangle2D object representing the union of this Rectangle2D with the specified Rectangle2D.
8boolean equals(Object obj)
Determines whether or not the specified Object is equal to this Rectangle2D.
9Rectangle2D getBounds2D()
Returns a high precision and more accurate bounding box of the Shape than the getBounds method.
10PathIterator getPathIterator(AffineTransform at)
Returns an iteration object that defines the boundary of this Rectangle2D.
11PathIterator getPathIterator(AffineTransform at, double flatness)
Returns an iteration object that defines the boundary of the flattened Rectangle2D.
12int hashCode()
Returns the hashcode for this Rectangle2D.
13static void intersect(Rectangle2D src1, Rectangle2D src2, Rectangle2D dest)
Intersects the pair of specified source Rectangle2D objects and puts the result into the specified destination Rectangle2D object.
14boolean intersects(double x, double y, double w, double h)
Tests if the interior of the Shape intersects the interior of a specified rectangular area.
15boolean intersectsLine(double x1, double y1, double x2, double y2)
Tests if the specified line segment intersects the interior of this Rectangle2D.
16boolean intersectsLine(Line2D l)
Tests if the specified line segment intersects the interior of this Rectangle2D.
17abstract int outcode(double x, double y)
Determines where the specified coordinates lie with respect to this Rectangle2D.
18int outcode(Point2D p)
Determines where the specified Point2D lies with respect to this Rectangle2D.
19void setFrame(double x, double y, double w, double h)
Sets the location and size of the outer bounds of this Rectangle2D to the specified rectangular values.
20abstract void setRect(double x, double y, double w, double h)
Sets the location and size of this Rectangle2D to the specified double values.
21void setRect(Rectangle2D r)
Sets this Rectangle2D to be the same as the specified Rectangle2D.
22static void union(Rectangle2D src1, Rectangle2D src2, Rectangle2D dest)
Unions the pair of source Rectangle2D objects and puts the result into the specified destination Rectangle2D object.

Methods inherited

This class inherits methods from the following classes:

  • java.awt.geom.RectangularShape

  • java.lang.Object

Ellipse2D Example

Create the following java program using any editor of your choice in say D:/ > AWT > com > tutorialspoint > gui >

AWTGraphicsDemo.java
package com.tutorialspoint.gui;

import java.awt.*;
import java.awt.event.*;
import java.awt.geom.*;

public class AWTGraphicsDemo extends Frame {
       
   public AWTGraphicsDemo(){
      super("Java AWT Examples");
      prepareGUI();
   }

   public static void main(String[] args){
      AWTGraphicsDemo  awtGraphicsDemo = new AWTGraphicsDemo();  
      awtGraphicsDemo.setVisible(true);
   }

   private void prepareGUI(){
      setSize(400,400);
      addWindowListener(new WindowAdapter() {
         public void windowClosing(WindowEvent windowEvent){
            System.exit(0);
         }        
      }); 
   }    

   @Override
   public void paint(Graphics g) {
      Rectangle2D shape = new Rectangle2D.Float();
      shape.setFrame(100, 150, 200,100);
      Graphics2D g2 = (Graphics2D) g; 
      g2.draw (shape);
      Font font = new Font("Serif", Font.PLAIN, 24);
      g2.setFont(font);
      g.drawString("Welcome to TutorialsPoint", 50, 70);
      g2.drawString("Rectangle2D.Rectangle", 100, 120);
   }
}

Compile the program using command prompt. Go to D:/ > AWT and type the following command.

D:\AWT>javac com\tutorialspoint\gui\AWTGraphicsDemo.java

If no error comes that means compilation is successful. Run the program using following command.

D:\AWT>java com.tutorialspoint.gui.AWTGraphicsDemo

Verify the following output

AWT Rectangle2D

AWT QuadCurve2D Class

Introduction

The QuadCurve2D class states a quadratic parametric curve segment in (x,y) coordinate space.

Class declaration

Following is the declaration for java.awt.geom.QuadCurve2D class:

public abstract class QuadCurve2D
   extends Object
      implements Shape, Cloneable

Class constructors

S.N.Constructor & Description
1protected QuadCurve2D() ()
This is an abstract class that cannot be instantiated directly.

Class methods

S.N.Method & Description
1Object clone()
Creates a new object of the same class and with the same contents as this object.
2boolean contains(double x, double y)
Tests if the specified coordinates are inside the boundary of the Shape.
3boolean contains(double x, double y, double w, double h)
Tests if the interior of the Shape entirely contains the specified rectangular area.
4boolean contains(Point2D p)
Tests if a specified Point2D is inside the boundary of the Shape.
5boolean contains(Rectangle2D r)
Tests if the interior of the Shape entirely contains the specified Rectangle2D.
6Rectangle getBounds()
Returns an integer Rectangle that completely encloses the Shape.
7abstract Point2D getCtrlPt()
Returns the control point.
8abstract double getCtrlX()
Returns the X coordinate of the control point in double precision.
9abstract double getCtrlY()
Returns the Y coordinate of the control point in double precision.
10doublegetFlatness()
Returns the flatness, or maximum distance of a control point from the line connecting the end points, of this QuadCurve2D.
11static double getFlatness(double[] coords, int offset)
Returns the flatness, or maximum distance of a control point from the line connecting the end points, of the quadratic curve specified by the control points stored in the indicated array at the indicated index.
12static double getFlatness(double x1, double y1, double ctrlx, double ctrly, double x2, double y2)
Returns the flatness, or maximum distance of a control point from the line connecting the end points, of the quadratic curve specified by the indicated control points.
13double getFlatnessSq()
Returns the square of the flatness, or maximum distance of a control point from the line connecting the end points, of this QuadCurve2D.
14static double getFlatnessSq(double[] coords, int offset)
Returns the square of the flatness, or maximum distance of a control point from the line connecting the end points, of the quadratic curve specified by the control points stored in the indicated array at the indicated index.
15static double getFlatnessSq(double x1, double y1, double ctrlx, double ctrly, double x2, double y2)
Returns the square of the flatness, or maximum distance of a control point from the line connecting the end points, of the quadratic curve specified by the indicated control points.
16abstract Point2D getP1()
Returns the start point.
17abstract Point2D getP2()
Returns the end point.
18PathIterator getPathIterator(AffineTransform at)
Returns an iteration object that defines the boundary of the shape of this QuadCurve2D.
19PathIterator getPathIterator(AffineTransform at, double flatness)
Returns an iteration object that defines the boundary of the flattened shape of this QuadCurve2D.
20abstract double getX1()
Returns the X coordinate of the start point in double in precision.
21abstract double getX2()
Returns the X coordinate of the end point in double precision.
22abstract double getY1()
Returns the Y coordinate of the start point in double precision.
23abstract double getY2()
Returns the Y coordinate of the end point in double precision.
24boolean intersects(double x, double y, double w, double h)
Tests if the interior of the Shape intersects the interior of a specified rectangular area.
25boolean intersects(Rectangle2D r)
Tests if the interior of the Shape intersects the interior of a specified Rectangle2D.
26void setCurve(double[] coords, int offset)
Sets the location of the end points and control points of this QuadCurve2D to the double coordinates at the specified offset in the specified array.
27abstract void setCurve(double x1, double y1, double ctrlx, double ctrly, double x2, double y2)
Sets the location of the end points and control point of this curve to the specified double coordinates.
28void setCurve(Point2D[] pts, int offset)
Sets the location of the end points and control points of this QuadCurve2D to the coordinates of the Point2D objects at the specified offset in the specified array.
29void setCurve(Point2D p1, Point2D cp, Point2D p2)
Sets the location of the end points and control point of this QuadCurve2D to the specified Point2D coordinates.
30void setCurve(QuadCurve2D c)
Sets the location of the end points and control point of this QuadCurve2D to the same as those in the specified QuadCurve2D.
31static int solveQuadratic(double[] eqn)
Solves the quadratic whose coefficients are in the eqn array and places the non-complex roots back into the same array, returning the number of roots.
32static int solveQuadratic(double[] eqn, double[] res)
Solves the quadratic whose coefficients are in the eqn array and places the non-complex roots into the res array, returning the number of roots.
33static void subdivide(double[] src, int srcoff, double[] left, int leftoff, double[] right, int rightoff)
Subdivides the quadratic curve specified by the coordinates stored in the src array at indices srcoff through srcoff + 5 and stores the resulting two subdivided curves into the two result arrays at the corresponding indices.
34void subdivide(QuadCurve2D left, QuadCurve2D right)
Subdivides this QuadCurve2D and stores the resulting two subdivided curves into the left and right curve parameters.
35static void subdivide(QuadCurve2D src, QuadCurve2D left, QuadCurve2D right)
Subdivides the quadratic curve specified by the src parameter and stores the resulting two subdivided curves into the left and right curve parameters.

Methods inherited

This class inherits methods from the following classes:

  • java.lang.Object

QuadCurve2D Example

Create the following java program using any editor of your choice in say D:/ > AWT > com > tutorialspoint > gui >

AWTGraphicsDemo
package com.tutorialspoint.gui;

import java.awt.*;
import java.awt.event.*;
import java.awt.geom.*;

public class AWTGraphicsDemo extends Frame {
       
   public AWTGraphicsDemo(){
      super("Java AWT Examples");
      prepareGUI();
   }

   public static void main(String[] args){
      AWTGraphicsDemo  awtGraphicsDemo = new AWTGraphicsDemo();  
      awtGraphicsDemo.setVisible(true);
   }

   private void prepareGUI(){
      setSize(400,400);
      addWindowListener(new WindowAdapter() {
         public void windowClosing(WindowEvent windowEvent){
            System.exit(0);
         }        
      }); 
   }    

   @Override
   public void paint(Graphics g) {
      QuadCurve2D shape = new QuadCurve2D.Double();
      shape.setCurve(250D,250D,100D,100D,200D,150D);  
      Graphics2D g2 = (Graphics2D) g; 
      g2.draw (shape);
      Font font = new Font("Serif", Font.PLAIN, 24);
      g2.setFont(font);
      g.drawString("Welcome to TutorialsPoint", 50, 70);
      g2.drawString("QuadCurve2D.Curve", 100, 120);  
   }
}

Compile the program using command prompt. Go to D:/ > AWT and type the following command.

D:\AWT>javac com\tutorialspoint\gui\AWTGraphicsDemo.java

If no error comes that means compilation is successful. Run the program using following command.

D:\AWT>java com.tutorialspoint.gui.AWTGraphicsDemo

Verify the following output

AWT QuadCurve2D

AWT Line2D Class

Introduction

The Line2D class states a line segment in (x,y) coordinate space.

Class declaration

Following is the declaration for java.awt.geom.Line2D class:

public abstract class Line2D
   extends Object
      implements Shape, Cloneable

Class constructors

S.N.Constructor & Description
1protected Line2D() ()
This is an abstract class that cannot be instantiated directly.

Class methods

S.N.Method & Description
1Object clone()
Creates a new object of the same class as this object.
2boolean contains(double x, double y)
Tests if a specified coordinate is inside the boundary of this Line2D.
3boolean contains(double x, double y, double w, double h)
Tests if the interior of this Line2D entirely contains the specified set of rectangular coordinates.
4boolean contains(Point2D p)
Tests if a given Point2D is inside the boundary of this Line2D.
5boolean contains(Rectangle2D r)
Tests if the interior of this Line2D entirely contains the specified Rectangle2D.
6Rectangle getBounds()
Returns an integer Rectangle that completely encloses the Shape.
7abstract Point2D getP1()
Returns the start Point2D of this Line2D.
8abstract Point2D getP2()
Returns the end Point2D of this Line2D.
9PathIterator getPathIterator(AffineTransform at)
Returns an iteration object that defines the boundary of this Line2D.
10PathIterator getPathIterator(AffineTransform at, double flatness)
Returns an iteration object that defines the boundary of this flattened Line2D.
11abstract double getX1()
Returns the X coordinate of the start point in double precision.
12abstract double getX2()
Returns the X coordinate of the end point in double precision.
13abstract double getY1()
Returns the Y coordinate of the start point in double precision.
14abstract double getY2()
Returns the Y coordinate of the end point in double precision.
15boolean intersects(double x, double y, double w, double h)
Tests if the interior of the Shape intersects the interior of a specified rectangular area.
16boolean intersects(Rectangle2D r)
Tests if the interior of the Shape intersects the interior of a specified Rectangle2D.
17boolean intersectsLine(double x1, double y1, double x2, double y2)
Tests if the line segment from (x1,y1) to (x2,y2) intersects this line segment.
18boolean intersectsLine(Line2D l)
Tests if the specified line segment intersects this line segment.
19static boolean linesIntersect(double x1, double y1, double x2, double y2, double x3, double y3, double x4, double y4)
Tests if the line segment from (x1,y1) to (x2,y2) intersects the line segment from (x3,y3) to (x4,y4).
20double ptLineDist(double px, double py)
Returns the distance from a point to this line.
21static double ptLineDist(double x1, double y1, double x2, double y2, double px, double py)
Returns the distance from a point to a line.
22double ptLineDist(Point2D pt)
Returns the distance from a Point2D to this line.
23double ptLineDistSq(double px, double py)
Returns the square of the distance from a point to this line.
24static double ptLineDistSq(double x1, double y1, double x2, double y2, double px, double py)
Returns the square of the distance from a point to a line.
25double ptLineDistSq(Point2D pt)
Returns the square of the distance from a specified Point2D to this line.
26double ptSegDist(double px, double py)
Returns the distance from a point to this line segment.
27static double ptSegDist(double x1, double y1, double x2, double y2, double px, double py)
Returns the distance from a point to a line segment.
28double ptSegDist(Point2D pt)
Returns the distance from a Point2D to this line segment.
29double ptSegDistSq(double px, double py)
Returns the square of the distance from a point to this line segment.
30static double ptSegDistSq(double x1, double y1, double x2, double y2, double px, double py)
Returns the square of the distance from a point to a line segment.
31double ptSegDistSq(Point2D pt)
Returns the square of the distance from a Point2D to this line segment.
32int relativeCCW(double px, double py)
Returns an indicator of where the specified point (px,py) lies with respect to this line segment.
33static int relativeCCW(double x1, double y1, double x2, double y2, double px, double py)
Returns an indicator of where the specified point (px,py) lies with respect to the line segment from (x1,y1) to (x2,y2).
34int relativeCCW(Point2D p)
Returns an indicator of where the specified Point2D lies with respect to this line segment.
35abstract void setLine(double x1, double y1, double x2, double y2)
Sets the location of the end points of this Line2D to the specified double coordinates.
36void setLine(Line2D l)
Sets the location of the end points of this Line2D to the same as those end points of the specified Line2D.
37void setLine(Point2D p1, Point2D p2)
Sets the location of the end points of this Line2D to the specified Point2D coordinates.

Methods inherited

This class inherits methods from the following classes:

  • java.lang.Object

Line2D Example

Create the following java program using any editor of your choice in say D:/ > AWT > com > tutorialspoint > gui >

AWTGraphicsDemo.java
package com.tutorialspoint.gui;

import java.awt.*;
import java.awt.event.*;
import java.awt.geom.*;

public class AWTGraphicsDemo extends Frame {
       
   public AWTGraphicsDemo(){
      super("Java AWT Examples");
      prepareGUI();
   }

   public static void main(String[] args){
      AWTGraphicsDemo  awtGraphicsDemo = new AWTGraphicsDemo();  
      awtGraphicsDemo.setVisible(true);
   }

   private void prepareGUI(){
      setSize(400,400);
      addWindowListener(new WindowAdapter() {
         public void windowClosing(WindowEvent windowEvent){
            System.exit(0);
         }        
      }); 
   }    

   @Override
   public void paint(Graphics g) {
      Line2D shape = new Line2D.Double();
      shape.setLine(250D,250D,150D,150D);  
      Graphics2D g2 = (Graphics2D) g; 
      g2.draw (shape);
      Font font = new Font("Serif", Font.PLAIN, 24);
      g2.setFont(font);
      g.drawString("Welcome to TutorialsPoint", 50, 70);
      g2.drawString("Line2D.Line", 100, 120);  
   }
}

Compile the program using command prompt. Go to D:/ > AWT and type the following command.

D:\AWT>javac com\tutorialspoint\gui\AWTGraphicsDemo.java

If no error comes that means compilation is successful. Run the program using following command.

D:\AWT>java com.tutorialspoint.gui.AWTGraphicsDemo

Verify the following output

AWT Line2D

AWT Font Class

Introduction

The Font class states fonts, which are used to render text in a visible way.

Class declaration

Following is the declaration for java.awt.Font class:

public class Font
   extends Object
      implements Serializable

Field

Following are the fields for java.awt.geom.Arc2D class:

  • static int BOLD -- The bold style constant.

  • static int CENTER_BASELINE --The baseline used in ideographic scripts like Chinese, Japanese, and Korean when laying out text.

  • static String DIALOG --A String constant for the canonical family name of the logical font "Dialog".

  • static String DIALOG_INPUT --A String constant for the canonical family name of the logical font "DialogInput".

  • static int HANGING_BASELINE -- The baseline used in Devanigiri and similar scripts when laying out text.

  • static int ITALIC -- The italicized style constant.

  • static int LAYOUT_LEFT_TO_RIGHT -- A flag to layoutGlyphVector indicating that text is left-to-right as determined by Bidi analysis.

  • static int LAYOUT_NO_LIMIT_CONTEXT -- A flag to layoutGlyphVector indicating that text in the char array after the indicated limit should not be examined.

  • static int LAYOUT_NO_START_CONTEXT -- A flag to layoutGlyphVector indicating that text in the char array before the indicated start should not be examined.

  • static int LAYOUT_RIGHT_TO_LEFT -- A flag to layoutGlyphVector indicating that text is right-to-left as determined by Bidi analysis.

  • static String MONOSPACED -- A String constant for the canonical family name of the logical font "Monospaced".

  • protected String name -- The logical name of this Font, as passed to the constructor.

  • static int PLAIN --The plain style constant.

  • protected float pointSize -- The point size of this Font in float.

  • static int ROMAN_BASELINE --The baseline used in most Roman scripts when laying out text.

  • static String SANS_SERIF -- A String constant for the canonical family name of the logical font "SansSerif".

  • static String SERIF -- A String constant for the canonical family name of the logical font "Serif".

  • protected int size --The point size of this Font, rounded to integer.

  • protected int style -- The style of this Font, as passed to the constructor.

  • static int TRUETYPE_FONT -- Identify a font resource of type TRUETYPE.

  • static int TYPE1_FONT -- Identify a font resource of type TYPE1.

Class constructors

S.N.Constructor & Description
1protected Font() ()
Creates a new Font from the specified font.
2Font(Map<? extends AttributedCharacterIterator.Attribute,?> attributes)
Creates a new Font from the specified font.
3Font(String name, int style, int size)
Creates a new Font from the specified font.

Class methods

S.N.Method & Description
1boolean canDisplay(char c)
Checks if this Font has a glyph for the specified character.
2boolean canDisplay(int codePoint)
Checks if this Font has a glyph for the specified character.
3int canDisplayUpTo(char[] text, int start, int limit)
Indicates whether or not this Font can display the characters in the specified text starting at start and ending at limit.
4int canDisplayUpTo(CharacterIterator iter, int start, int limit)
Indicates whether or not this Font can display the text specified by the iter starting at start and ending at limit.
5int canDisplayUpTo(String str)
Indicates whether or not this Font can display a specified String.
6static Font createFont(int fontFormat, File fontFile)
Returns a new Font using the specified font type and the specified font file.
7static Font createFont(int fontFormat, InputStream fontStream)
Returns a new Font using the specified font type and input data.
8GlyphVector createGlyphVector(FontRenderContext frc, char[] chars)
Creates a GlyphVector by mapping characters to glyphs one-to-one based on the Unicode cmap in this Font.
9GlyphVector createGlyphVector(FontRenderContext frc, CharacterIterator ci)
Creates a GlyphVector by mapping the specified characters to glyphs one-to-one based on the Unicode cmap in this Font.
10GlyphVector createGlyphVector(FontRenderContext frc, int[] glyphCodes)
Creates a GlyphVector by mapping characters to glyphs one-to-one based on the Unicode cmap in this Font.
11GlyphVector createGlyphVector(FontRenderContext frc, String str)
Creates a GlyphVector by mapping characters to glyphs one-to-one based on the Unicode cmap in this Font.
12static Font decode(String str)
Returns the Font that the str argument describes.
13Font deriveFont(AffineTransform trans)
Creates a new Font object by replicating the current Font object and applying a new transform to it.
14Font deriveFont(float size)
Creates a new Font object by replicating the current Font object and applying a new size to it.
15Font deriveFont(int style)
Creates a new Font object by replicating the current Font object and applying a new style to it.
16Font deriveFont(int style, AffineTransform trans)
Creates a new Font object by replicating this Font object and applying a new style and transform.
17Font deriveFont(int style, float size)
Creates a new Font object by replicating this Font object and applying a new style and size.
18Font deriveFont(Map<? extends AttributedCharacterIterator.Attribute,?> attributes)
Creates a new Font object by replicating the current Font object and applying a new set of font attributes to it.
19boolean equals(Object obj)
Compares this Font object to the specified Object.
20protected void finalize()
Disposes the native Font object.
21Map<TextAttribute,?> getAttributes()
Returns a map of font attributes available in this Font.
22AttributedCharacterIterator.Attribute[] getAvailableAttributes()
Returns the keys of all the attributes supported by this Font.
23byte getBaselineFor(char c)
Returns the baseline appropriate for displaying this character.
24String getFamily()
Returns the family name of this Font.
25String getFamily(Locale l)
Returns the family name of this Font, localized for the specified locale.
26static Font getFont(Map<? extends AttributedCharacterIterator.Attribute,?> attributes)
Returns a Font appropriate to the attributes.
27static Font getFont(String nm)
Returns a Font object fom the system properties list.
28static Font getFont(String nm, Font font)
Gets the specified Font from the system properties list.
29String getFontName()
Returns the font face name of this Font.
30String getFontName(Locale l)
Returns the font face name of the Font, localized for the specified locale.
31float getItalicAngle()
Returns the italic angle of this Font.
32LineMetrics getLineMetrics(char[] chars, int beginIndex, int limit, FontRenderContext frc)
Returns a LineMetrics object created with the specified arguments.
33LineMetrics getLineMetrics(CharacterIterator ci, int beginIndex, int limit, FontRenderContext frc)
Returns a LineMetrics object created with the specified arguments.
34LineMetrics getLineMetrics(String str, FontRenderContext frc)
Returns a LineMetrics object created with the specified String and FontRenderContext.
35LineMetrics getLineMetrics(String str, int beginIndex, int limit, FontRenderContext frc)
Returns a LineMetrics object created with the specified arguments.
36Rectangle2D getMaxCharBounds(FontRenderContext frc)
Returns the bounds for the character with the maximum bounds as defined in the specified FontRenderContext.
37int getMissingGlyphCode()
Returns the glyphCode which is used when this Font does not have a glyph for a specified unicode code point.
38String getName()
Returns the logical name of this Font.
39int getNumGlyphs()
Returns the number of glyphs in this Font.
40java.awt.peer.FontPeer getPeer()
Deprecated. Font rendering is now platform independent.
41String getPSName()
Returns the postscript name of this Font.
42int getSize()
Returns the point size of this Font, rounded to an integer.
43float getSize2D()
Returns the point size of this Font in float value.
44Rectangle2D getStringBounds(char[] chars, int beginIndex, int limit, FontRenderContext frc)
Returns the logical bounds of the specified array of characters in the specified FontRenderContext.
45Rectangle2D getStringBounds(CharacterIterator ci, int beginIndex, int limit, FontRenderContext frc)
Returns the logical bounds of the characters indexed in the specified CharacterIterator in the specified FontRenderContext.
46Rectangle2D getStringBounds(String str, FontRenderContext frc)
Returns the logical bounds of the specified String in the specified FontRenderContext.
47Rectangle2D getStringBounds(String str, int beginIndex, int limit, FontRenderContext frc)
Returns the logical bounds of the specified String in the specified FontRenderContext.
48int getStyle()
Returns the style of this Font.
49AffineTransform getTransform()
Returns a copy of the transform associated with this Font.
50int hashCode()
Returns a hashcode for this Font.
51boolean hasLayoutAttributes()
Return true if this Font contains attributes that require extra layout processing.
52boolean hasUniformLineMetrics()
Checks whether or not this Font has uniform line metrics.
53boolean isBold()
Indicates whether or not this Font object's style is BOLD.
54boolean isItalic()
Indicates whether or not this Font object's style is ITALIC.
55boolean isPlain()
Indicates whether or not this Font object's style is PLAIN.
56boolean isTransformed()
Indicates whether or not this Font object has a transform that affects its size in addition to the Size attribute.
57GlyphVector layoutGlyphVector(FontRenderContext frc, char[] text, int start, int limit, int flags)
Returns a new GlyphVector object, performing full layout of the text if possible.
58String toString()
Converts this Font object to a String representation.

Methods inherited

This class inherits methods from the following classes:

  • java.lang.Object

Font Example

Create the following java program using any editor of your choice in say D:/ > AWT > com > tutorialspoint > gui >

AWTGraphicsDemo.java
package com.tutorialspoint.gui;

import java.awt.*;
import java.awt.event.*;
import java.awt.geom.*;

public class AWTGraphicsDemo extends Frame {
       
   public AWTGraphicsDemo(){
      super("Java AWT Examples");
      prepareGUI();
   }

   public static void main(String[] args){
      AWTGraphicsDemo  awtGraphicsDemo = new AWTGraphicsDemo();  
      awtGraphicsDemo.setVisible(true);
   }

   private void prepareGUI(){
      setSize(400,400);
      addWindowListener(new WindowAdapter() {
         public void windowClosing(WindowEvent windowEvent){
            System.exit(0);
         }        
      }); 
   }    

   @Override
   public void paint(Graphics g) {
      Graphics2D g2 = (Graphics2D)g;        
      Font plainFont = new Font("Serif", Font.PLAIN, 24);        
      g2.setFont(plainFont);
      g2.drawString("Welcome to TutorialsPoint", 50, 70); 
      Font italicFont = new Font("Serif", Font.ITALIC, 24);        
      g2.setFont(italicFont);
      g2.drawString("Welcome to TutorialsPoint", 50, 120); 
      Font boldFont = new Font("Serif", Font.BOLD, 24);        
      g2.setFont(boldFont);
      g2.drawString("Welcome to TutorialsPoint", 50, 170); 
      Font boldItalicFont = new Font("Serif", Font.BOLD+Font.ITALIC, 24);        
      g2.setFont(boldItalicFont);
      g2.drawString("Welcome to TutorialsPoint", 50, 220); 
   }
}

Compile the program using command prompt. Go to D:/ > AWT and type the following command.

D:\AWT>javac com\tutorialspoint\gui\AWTGraphicsDemo.java

If no error comes that means compilation is successful. Run the program using following command.

D:\AWT>java com.tutorialspoint.gui.AWTGraphicsDemo

Verify the following output

AWT Font

AWT Color Class

Introduction

The Color class states colors in the default sRGB color space or colors in arbitrary color spaces identified by a ColorSpace.

Class declaration

Following is the declaration for java.awt.Color class:

public class Color
   extends Object
      implements Paint, Serializable

Field

Following are the fields for java.awt.geom.Arc2D class:

  • static Color black -- The color black.

  • static Color BLACK -- The color black.

  • static Color blue -- The color blue.

  • static Color BLUE -- The color blue.

  • static Color cyan -- The color cyan.

  • static Color CYAN -- The color cyan.

  • static Color DARK_GRAY -- The color dark gray.

  • static Color darkGray -- The color dark gray.

  • static Color gray -- The color gray.

  • static Color GRAY -- The color gray.

  • static Color green -- The color green.

  • static Color GREEN -- The color green.

  • static Color LIGHT_GRAY -- The color light gray.

  • static Color lightGray -- The color light gray.

  • static Color magenta -- The color magenta.

  • static Color MAGENTA -- The color magenta.

  • static Color orange -- The color orange.

  • static Color ORANGE -- The color orange.

  • static Color pink -- The color pink.

  • static Color PINK -- The color pink.

  • static Color red -- The color red.

  • static Color RED -- The color red.

  • static Color white -- The color white.

  • static Color WHITE -- The color white.

  • static Color yellow -- The color yellow.

  • static Color YELLOW -- The color yellow.

Class constructors

S.N.Constructor & Description
1Color(ColorSpace cspace, float[] components, float alpha)
Creates a color in the specified ColorSpace with the color components specified in the float array and the specified alpha.
2Color(float r, float g, float b)
Creates an opaque sRGB color with the specified red, green, and blue values in the range (0.0 - 1.0).
3Color(float r, float g, float b, float a)
Creates an sRGB color with the specified red, green, blue, and alpha values in the range (0.0 - 1.0).
4Color(int rgb)
Creates an opaque sRGB color with the specified combined RGB value consisting of the red component in bits 16-23, the green component in bits 8-15, and the blue component in bits 0-7.
5Color(int rgba, boolean hasalpha)
Creates an sRGB color with the specified combined RGBA value consisting of the alpha component in bits 24-31, the red component in bits 16-23, the green component in bits 8-15, and the blue component in bits 0-7.
6Color(int r, int g, int b)
Creates an opaque sRGB color with the specified red, green, and blue values in the range (0 - 255).
7Color(int r, int g, int b, int a)
Creates an sRGB color with the specified red, green, blue, and alpha values in the range (0 - 255).

Class methods

S.N.Method & Description
1Color brighter()
Creates a new Color that is a brighter version of this Color.
2PaintContext createContext(ColorModel cm, Rectangle r, Rectangle2D r2d, AffineTransform xform, RenderingHints hints)
Creates and returns a PaintContext used to generate a solid color pattern.
3Color darker()
Creates a new Color that is a darker version of this Color.
4static Color decode(String nm)
Converts a String to an integer and returns the specified opaque Color.
5boolean equals(Object obj)
Determines whether another object is equal to this Color.
6int getAlpha()
Returns the alpha component in the range 0-255.
7int getBlue()
Returns the blue component in the range 0-255 in the default sRGB space.
8static Color getColor(String nm)
Finds a color in the system properties.
9static Color getColor(String nm, Color v)
Finds a color in the system properties.
10static Color getColor(String nm, int v)
Finds a color in the system properties.
11float[] getColorComponents(ColorSpace cspace, float[] compArray)
Returns a float array containing only the color components of the Color in the ColorSpace specified by the cspace parameter.
12float[] getColorComponents(float[] compArray)
Returns a float array containing only the color components of the Color, in the ColorSpace of the Color.
13ColorSpace getColorSpace()
Returns the ColorSpace of this Color.
14float[] getComponents(ColorSpace cspace, float[] compArray)
Returns a float array containing the color and alpha components of the Color, in the ColorSpace specified by the cspace parameter.
15float[] getComponents(float[] compArray)
Returns a float array containing the color and alpha components of the Color, in the ColorSpace of the Color.
16int getGreen()
Returns the green component in the range 0-255 in the default sRGB space.
17static Color getHSBColor(float h, float s, float b)
Creates a Color object based on the specified values for the HSB color model.
18int getRed()
Returns the red component in the range 0-255 in the default sRGB space.
19int getRGB()
Returns the RGB value representing the color in the default sRGB ColorModel.
20float[] getRGBColorComponents(float[] compArray)
Returns a float array containing only the color components of the Color, in the default sRGB color space.
21float[] getRGBComponents(float[] compArray)
Returns a float array containing the color and alpha components of the Color, as represented in the default sRGB color space.
22int getTransparency()
Returns the transparency mode for this Color.
23int hashCode()
Computes the hash code for this Color.
24static int HSBtoRGB(float hue, float saturation, float brightness)
Converts the components of a color, as specified by the HSB model, to an equivalent set of values for the default RGB model.
25static float[] RGBtoHSB(int r, int g, int b, float[] hsbvals)
Converts the components of a color, as specified by the default RGB model, to an equivalent set of values for hue, saturation, and brightness that are the three components of the HSB model.
26String toString()
Returns a string representation of this Color.

Methods inherited

This class inherits methods from the following classes:

  • java.lang.Object

Color Example

Create the following java program using any editor of your choice in say D:/ > AWT > com > tutorialspoint > gui >

AWTGraphicsDemo.java
package com.tutorialspoint.gui;

import java.awt.*;
import java.awt.event.*;
import java.awt.geom.*;

public class AWTGraphicsDemo extends Frame {
       
   public AWTGraphicsDemo(){
      super("Java AWT Examples");
      prepareGUI();
   }

   public static void main(String[] args){
      AWTGraphicsDemo  awtGraphicsDemo = new AWTGraphicsDemo();  
      awtGraphicsDemo.setVisible(true);
   }

   private void prepareGUI(){
      setSize(400,400);
      addWindowListener(new WindowAdapter() {
         public void windowClosing(WindowEvent windowEvent){
            System.exit(0);
         }        
      }); 
   }    

   @Override
   public void paint(Graphics g) {
      Graphics2D g2 = (Graphics2D)g;        
      Font plainFont = new Font("Serif", Font.PLAIN, 24);        
      g2.setFont(plainFont);
      g2.setColor(Color.red);
      g2.drawString("Welcome to TutorialsPoint", 50, 70); 
      g2.setColor(Color.GRAY);
      g2.drawString("Welcome to TutorialsPoint", 50, 120);  
   }
}

Compile the program using command prompt. Go to D:/ > AWT and type the following command.

D:\AWT>javac com\tutorialspoint\gui\AWTGraphicsDemo.java

If no error comes that means compilation is successful. Run the program using following command.

D:\AWT>java com.tutorialspoint.gui.AWTGraphicsDemo

Verify the following output

AWT Color

AWT BasicStroke Class

Introduction

The BasicStroke class states colors in the default sRGB color space or colors in arbitrary color spaces identified by a ColorSpace.

Class declaration

Following is the declaration for java.awt.BasicStroke class:

public class BasicStroke
   extends Object
      implements Stroke

Field

Following are the fields for java.awt.geom.Arc2D class:

  • static int CAP_BUTT -- Ends unclosed subpaths and dash segments with no added decoration.

  • static int CAP_ROUND -- Ends unclosed subpaths and dash segments with a round decoration that has a radius equal to half of the width of the pen.

  • static int CAP_SQUARE -- Ends unclosed subpaths and dash segments with a square projection that extends beyond the end of the segment to a distance equal to half of the line width.

  • static int JOIN_BEVEL -- Joins path segments by connecting the outer corners of their wide outlines with a straight segment.

  • static int JOIN_MITER -- Joins path segments by extending their outside edges until they meet.

  • static int JOIN_ROUND -- Joins path segments by rounding off the corner at a radius of half the line width.

Class constructors

S.N.Constructor & Description
1BasicStroke()
Constructs a new BasicStroke with defaults for all attributes.
2BasicStroke(float width)
Constructs a solid BasicStroke with the specified line width and with default values for the cap and join styles.
3BasicStroke(float width, int cap, int join)
Constructs a solid BasicStroke with the specified attributes.
4BasicStroke(float width, int cap, int join, float miterlimit)
Constructs a solid BasicStroke with the specified attributes.
5BasicStroke(float width, int cap, int join, float miterlimit, float[] dash, float dash_phase)
Constructs a new BasicStroke with the specified attributes.

Class methods

S.N.Method & Description
1Shape createStrokedShape(Shape s)
Returns a Shape whose interior defines the stroked outline of a specified Shape.
2boolean equals(Object obj)
Tests if a specified object is equal to this BasicStroke by first testing if it is a BasicStroke and then comparing its width, join, cap, miter limit, dash, and dash phase attributes with those of this BasicStroke.
3float[] getDashArray()
Returns the array representing the lengths of the dash segments.
4float getDashPhase()
Returns the current dash phase.
5int getEndCap()
Returns the end cap style.
6int getLineJoin()
Returns the line join style.
7float getLineWidth()
Returns the line width.
8float getMiterLimit()
Returns the limit of miter joins.
9int hashCode()
Returns the hashcode for this stroke.

Methods inherited

This class inherits methods from the following classes:

  • java.lang.Object

BasicStroke Example

Create the following java program using any editor of your choice in say D:/ > AWT > com > tutorialspoint > gui >

AWTGraphicsDemo.java
package com.tutorialspoint.gui;

import java.awt.*;
import java.awt.event.*;
import java.awt.geom.*;

public class AWTGraphicsDemo extends Frame {
       
   public AWTGraphicsDemo(){
      super("Java AWT Examples");
      prepareGUI();
   }

   public static void main(String[] args){
      AWTGraphicsDemo  awtGraphicsDemo = new AWTGraphicsDemo();  
      awtGraphicsDemo.setVisible(true);
   }

   private void prepareGUI(){
      setSize(400,400);
      addWindowListener(new WindowAdapter() {
         public void windowClosing(WindowEvent windowEvent){
            System.exit(0);
         }        
      }); 
   }    

   @Override
   public void paint(Graphics g) {
      Graphics2D g2 = (Graphics2D)g;        
      g2.setStroke(new BasicStroke(3.0f));
      g2.setPaint(Color.blue);

      Rectangle2D shape = new Rectangle2D.Float();
      shape.setFrame(100, 150, 200,100);
      g2.draw(shape);

      Rectangle2D shape1 = new Rectangle2D.Float();
      shape1.setFrame(110, 160, 180,80);
      g2.setStroke(new BasicStroke(1.0f));
   
      g2.draw(shape1);
      Font plainFont = new Font("Serif", Font.PLAIN, 24);        
      g2.setFont(plainFont);
      g2.setColor(Color.DARK_GRAY);
      g2.drawString("TutorialsPoint", 130, 200);
   }
}

Compile the program using command prompt. Go to D:/ > AWT and type the following command.

D:\AWT>javac com\tutorialspoint\gui\AwtGraphicsDemo.java

If no error comes that means compilation is successful. Run the program using following command.

D:\AWT>java com.tutorialspoint.gui.AwtGraphicsDemo

Verify the following output

AWT BasicStroke

Advertisements
Advertisements