Swing Quick Guide

Advertisements


Overview

Swing API is set of extensible GUI Components to ease developer's life to create JAVA based Front End/ GUI Applications. It is build upon top of AWT API and acts as replacement of AWT API as it has almost every control corresponding to AWT controls. Swing component follows a Model-View-Controller architecture to fulfill the following criterias.

  • A single API is to be sufficient to support multiple look and feel.

  • API is to model driven so that highest level API is not required to have the data.

  • API is to use the Java Bean model so that Builder Tools and IDE can provide better services to the developers to use it.

MVC Architecture

Swing API architecture follows loosely based MVC architecture in the following manner.

  • A Model represents component's data.

  • View represents visual representation of the component's data.

  • Controller takes the input from the user on the view and reflects the changes in Component's data.

  • Swing component have Model as a seperate element and View and Controller part are clubbed in User Interface elements. Using this way, Swing has pluggable look-and-feel architecture.

Swing features

  • Light Weight - Swing component are independent of native Operating System's API as Swing API controls are rendered mostly using pure JAVA code instead of underlying operating system calls.

  • Rich controls - Swing provides a rich set of advanced controls like Tree, TabbedPane, slider, colorpicker, table controls

  • Highly Customizable - Swing controls can be customized in very easy way as visual apperance is independent of internal representation.

  • Pluggable look-and-feel- SWING based GUI Application look and feel can be changed at run time based on available values.

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/.

Swing 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

Swing 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

Swing 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

Swing JComponent Class

Introduction

The class JComponent is the base class for all Swing components except top-level containers. To use a component that inherits from JComponent, you must place the component in a containment hierarchy whose root is a top-level Swing container.

Class declaration

Following is the declaration for javax.swing.JComponent class:

public abstract class JComponent
   extends Container
      implements Serializable

Field

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

  • protected AccessibleContext accessibleContext -- The AccessibleContext associated with this JComponent.

  • protected EventListenerList listenerList -- A list of event listeners for this component.

  • static String TOOL_TIP_TEXT_KEY -- The comment to display when the cursor is over the component, also known as a "value tip", "flyover help", or "flyover label".

  • protected ComponentUI ui -- The look and feel delegate for this component.

  • static int UNDEFINED_CONDITION -- Constant used by some of the APIs to mean that no condition is defined.

  • static int WHEN_ANCESTOR_OF_FOCUSED_COMPONENT -- Constant used for registerKeyboardAction that means that the command should be invoked when the receiving component is an ancestor of the focused component or is itself the focused component.

  • static int WHEN_FOCUSED -- Constant used for registerKeyboardAction that means that the command should be invoked when the component has the focus.

  • static int WHEN_IN_FOCUSED_WINDOW -- Constant used for registerKeyboardAction that means that the command should be invoked when the receiving component is in the window that has the focus or is itself the focused component.

Class constructors

S.N.Constructor & Description
1JComponent()
Default JComponent constructor.

Class methods

S.N.Method & Description
1void addAncestorListener(AncestorListener listener)
Registers listener so that it will receive AncestorEvents when it or any of its ancestors move or are made visible or invisible.
2void addNotify()
Notifies this component that it now has a parent component.
3void addVetoableChangeListener(VetoableChangeListener listener)
Adds a VetoableChangeListener to the listener list.
4void computeVisibleRect(Rectangle visibleRect)
Returns the Component's "visible rect rectangle" - the intersection of the visible rectangles for this component and all of its ancestors.
5boolean contains(int x, int y)
Gives the UI delegate an opportunity to define the precise shape of this component for the sake of mouse processing.
6JToolTip createToolTip()
Returns the instance of JToolTip that should be used to display the tooltip.
7void disable()
Deprecated.As of JDK version 1.1, replaced by java.awt.Component.setEnabled(boolean).
8void enable()
Deprecated. As of JDK version 1.1, replaced by java.awt.Component.setEnabled(boolean).
9void firePropertyChange(String propertyName, boolean oldValue, boolean newValue)
Support for reporting bound property changes for boolean properties.
10void firePropertyChange(String propertyName, char oldValue, char newValue)
Reports a bound property change.
11void firePropertyChange(String propertyName, int oldValue, int newValue)
Support for reporting bound property changes for integer properties.
12protected void fireVetoableChange(String propertyName, Object oldValue, Object newValue)
Supports reporting constrained property changes.
13AccessibleContext getAccessibleContext()
Returns the AccessibleContext associated with this JComponent.
14ActionListener getActionForKeyStroke(KeyStroke aKeyStroke)
Returns the object that will perform the action registered for a given keystroke.
15ActionMap getActionMap()
Returns the ActionMap used to determine what Action to fire for particular KeyStroke binding.
16float getAlignmentX()
Overrides Container.getAlignmentX to return the vertical alignment.
17float getAlignmentY()
Overrides Container.getAlignmentY to return the horizontal alignment.
18AncestorListener[] getAncestorListeners()
Returns an array of all the ancestor listeners registered on this component.
19boolean getAutoscrolls()
Gets the autoscrolls property.
20int getBaseline(int width, int height)
Returns the baseline.
21Component.BaselineResizeBehavior getBaselineResizeBehavior()
Returns an enum indicating how the baseline of the component changes as the size changes.
22Border getBorder()
Returns the border of this component or null if no border is currently set.
23Rectangle getBounds(Rectangle rv)
Stores the bounds of this component into "return value" rv and returns rv.
24Object getClientProperty(Object key)
Returns the value of the property with the specified key.
25protected Graphics getComponentGraphics(Graphics g)
Returns the graphics object used to paint this component.
26JPopupMenu getComponentPopupMenu()
Returns JPopupMenu that assigned for this component.
27int getConditionForKeyStroke(KeyStroke aKeyStroke)
Returns the condition that determines whether a registered action occurs in response to the specified keystroke.
28int getDebugGraphicsOptions()
Returns the state of graphics debugging.
29static Locale getDefaultLocale()
Returns the default locale used to initialize each JComponent's locale property upon creation.
30FontMetrics getFontMetrics(Font font)
Gets the FontMetrics for the specified Font.
31Graphics getGraphics()
Returns this component's graphics context, which lets you draw on a component.
32int getHeight()
Returns the current height of this component.
33boolean getInheritsPopupMenu()
Returns true if the JPopupMenu should be inherited from the parent.
34InputMap getInputMap()
Returns the InputMap that is used when the component has focus.
35InputMap getInputMap(int condition)
Returns the InputMap that is used during condition.
36InputVerifier getInputVerifier()
Returns the input verifier for this component.
37Insets getInsets()
If a border has been set on this component, returns the border's insets; otherwise calls super.getInsets.
38Insets getInsets(Insets insets)
Returns an Insets object containing this component's inset values.
39<T extends EventListener> T[] getListeners(Class<T> listenerType)
Returns an array of all the objects currently registered as FooListeners upon this JComponent.
40Point getLocation(Point rv)
Stores the x,y origin of this component into "return value" rv and returns rv.
41Dimension getMaximumSize()
If the maximum size has been set to a non-null value just returns it.
42Dimension getMinimumSize()
If the minimum size has been set to a non-null value just returns it.
43Component getNextFocusableComponent()
Deprecated. As of 1.4, replaced by FocusTraversalPolicy.
44Point getPopupLocation(MouseEvent event)
Returns the preferred location to display the popup menu in this component's coordinate system.
45Dimension getPreferredSize()
If the preferredSize has been set to a non-null value just returns it.
46KeyStroke[] getRegisteredKeyStrokes()
Returns the KeyStrokes that will initiate registered actions.
47JRootPane getRootPane()
Returns the JRootPane ancestor for this component.
48 Dimension getSize(Dimension rv)
Stores the width/height of this component into "return value" rv and returns rv.
49Point getToolTipLocation(MouseEvent event)
Returns the tooltip location in this component's coordinate system.
50String getToolTipText()
Returns the tooltip string that has been set with setToolTipText.
51String getToolTipText(MouseEvent event)
Returns the string to be used as the tooltip for event.
52Container getTopLevelAncestor()
Returns the top-level ancestor of this component (either the containing Window or Applet), or null if this component has not been added to any container.
53TransferHandler getTransferHandler()
Gets the transferHandler property.
54 String getUIClassID()
Returns the UIDefaults key used to look up the name of the swing.plaf.ComponentUI class that defines the look and feel for this component.
55boolean getVerifyInputWhenFocusTarget()
Returns the value that indicates whether the input verifier for the current focus owner will be called before this component requests focus.
56VetoableChangeListener[] getVetoableChangeListeners()
Returns an array of all the vetoable change listeners registered on this component.
57Rectangle getVisibleRect()
Returns the Component's "visible rectangle" - the intersection of this component's visible rectangle, new Rectangle(0, 0, getWidth(), getHeight()) , and all of its ancestors' visible rectangles.
58int getWidth()
Returns the current width of this component.
59int getX()
Returns the current x coordinate of the component's origin.
60int getY()
Returns the current y coordinate of the component's origin.
61void grabFocus()
Requests that this Component get the input focus, and that this Component's top-level ancestor become the focused Window.
62boolean isDoubleBuffered()
Returns whether this component should use a buffer to paint.
63static boolean isLightweightComponent(Component c)
Returns true if this component is lightweight, that is, if it doesn't have a native window system peer.
64boolean isManagingFocus()
Deprecated.As of 1.4, replaced by Component.setFocusTraversalKeys(int, Set) and Container.setFocusCycleRoot(boolean).
65boolean isOpaque()
Returns true if this component is completely opaque.
66boolean isOptimizedDrawingEnabled()
Returns true if this component tiles its children -- that is, if it can guarantee that the children will not overlap.
67boolean isPaintingForPrint()
Returns true if the current painting operation on this component is part of a print operation.
68boolean isPaintingTile()
Returns true if the component is currently painting a tile.
69boolean isRequestFocusEnabled()
Returns true if this JComponent should get focus; otherwise returns false.
70boolean isValidateRoot()
If this method returns true, revalidate calls by descendants of this component will cause the entire tree beginning with this root to be validated.
71void paint(Graphics g)
Invoked by Swing to draw components.
72protected void paintBorder(Graphics g)
Paints the component's border.
73protected void paintChildren(Graphics g)
Paints this component's children.
74protected void paintComponent(Graphics g)
Calls the UI delegate's paint method, if the UI delegate is non-null.
75void paintImmediately(int x, int y, int w, int h)
Paints the specified region in this component and all of its descendants that overlap the region, immediately.
76void paintImmediately(Rectangle r)
Paints the specified region now.
77protected String paramString()
Returns a string representation of this JComponent.
78void print(Graphics g)
Invoke this method to print the component to the specified Graphics.
79void printAll(Graphics g)
Invoke this method to print the component.
80protected void printBorder(Graphics g)
Prints the component's border.
81protected void printChildren(Graphics g)
Prints this component's children.
82protected void printComponent(Graphics g)
This is invoked during a printing operation.
82protected void processComponentKeyEvent(KeyEvent e)
Processes any key events that the component itself recognizes.
84protected boolean processKeyBinding(KeyStroke ks, KeyEvent e, int condition, boolean pressed)
Invoked to process the key bindings for ks as the result of the KeyEvent e.
85protected void processKeyEvent(KeyEvent e)
Overrides processKeyEvent to process events.
86protected void processMouseEvent(MouseEvent e)
Processes mouse events occurring on this component by dispatching them to any registered MouseListener objects, refer to Component.processMouseEvent(MouseEvent) for a complete description of this method.
87protected void processMouseMotionEvent(MouseEvent e)
Processes mouse motion events, such as MouseEvent.MOUSE_DRAGGED.
88void putClientProperty(Object key, Object value)
Adds an arbitrary key/value "client property" to this component.
89void registerKeyboardAction(ActionListener anAction, KeyStroke aKeyStroke, int aCondition)
This method is now obsolete, please use a combination of getActionMap()
and getInputMap()
for similiar behavior.
90void registerKeyboardAction(ActionListener anAction, String aCommand, KeyStroke aKeyStroke, int aCondition)
This method is now obsolete, please use a combination of getActionMap()
and getInputMap()
for similiar behavior.
91void removeAncestorListener(AncestorListener listener)
Unregisters listener so that it will no longer receive AncestorEvents.
92void removeNotify()
Notifies this component that it no longer has a parent component.
93void removeVetoableChangeListener(VetoableChangeListener listener)
Removes a VetoableChangeListener from the listener list.
94void repaint(long tm, int x, int y, int width, int height)
Adds the specified region to the dirty region list if the component is showing.
95void repaint(Rectangle r)
Adds the specified region to the dirty region list if the component is showing.
96boolean requestDefaultFocus()
Deprecated.As of 1.4, replaced by FocusTraversalPolicy.getDefaultComponent(Container).requestFocus()
97void requestFocus()
Requests that this Component gets the input focus.
98boolean requestFocus(boolean temporary)
Requests that this Component gets the input focus.
99boolean requestFocusInWindow()
Requests that this Component gets the input focus.
100protected boolean requestFocusInWindow(boolean temporary)
Requests that this Component gets the input focus.
101void resetKeyboardActions()
Unregisters all the bindings in the first tier InputMaps and ActionMap.
102void reshape(int x, int y, int w, int h)
Deprecated.As of JDK 5, replaced by Component.setBounds(int, int, int, int).Moves and resizes this component.
103void revalidate()
Supports deferred automatic layout.
104void scrollRectToVisible(Rectangle aRect)
Forwards the scrollRectToVisible()
message to the JComponent's parent.
105void setActionMap(ActionMap am)
Sets the ActionMap to am.
106void setAlignmentX(float alignmentX)
Sets the the vertical alignment.
107void setAlignmentY(float alignmentY)
Sets the the horizontal alignment.
108void setAutoscrolls(boolean autoscrolls)
Sets the autoscrolls property.
109void setBackground(Color bg)
Sets the background color of this component.
110void setBorder(Border border)
Sets the border of this component.
111void setComponentPopupMenu(JPopupMenu popup)
Sets the JPopupMenu for this JComponent.
112void setDebugGraphicsOptions(int debugOptions)
Enables or disables diagnostic information about every graphics operation performed within the component or one of its children.
113static void setDefaultLocale(Locale l)
Sets the default locale used to initialize each JComponent's locale property upon creation.
114void setDoubleBuffered(boolean aFlag)
Sets whether this component should use a buffer to paint.
115void setEnabled(boolean enabled)
Sets whether or not this component is enabled.
116void setFocusTraversalKeys(int id, Set<? extends AWTKeyStroke> keystrokes)
Sets the focus traversal keys for a given traversal operation for this Component.
117void setFont(Font font)
Sets the font for this component.
118void setForeground(Color fg)
Sets the foreground color of this component.
119void setInheritsPopupMenu(boolean value)
Sets whether or not getComponentPopupMenu should delegate to the parent if this component does not have a JPopupMenu assigned to it.
120void setInputMap(int condition, InputMap map)
Sets the InputMap to use under the condition condition to map.
121void setInputVerifier(InputVerifier inputVerifier)
Sets the input verifier for this component.
122void setMaximumSize(Dimension maximumSize)
Sets the maximum size of this component to a constant value.
123void setMinimumSize(Dimension minimumSize)
Sets the minimum size of this component to a constant value.
124void setNextFocusableComponent(Component aComponent)
Deprecated. As of 1.4, replaced by FocusTraversalPolicy
125void setOpaque(boolean isOpaque)
If true the component paints every pixel within its bounds.
126void setPreferredSize(Dimension preferredSize)
Sets the preferred size of this component.
127void setRequestFocusEnabled(boolean requestFocusEnabled)
Provides a hint as to whether or not this JComponent should get focus.
128void setToolTipText(String text)
Registers the text to display in a tool tip.
129void setTransferHandler(TransferHandler newHandler)
Sets the transferHandler property, which is null if the component does not support data transfer operations.
130protected void setUI(ComponentUI newUI)
Sets the look and feel delegate for this component.
131void setVerifyInputWhenFocusTarget(boolean verifyInputWhenFocusTarget)
Sets the value to indicate whether input verifier for the current focus owner will be called before this component requests focus.
132void setVisible(boolean aFlag)
Makes the component visible or invisible.
133void unregisterKeyboardAction(KeyStroke aKeyStroke)
This method is now obsolete.
134void update(Graphics g)
Calls paint.
135void updateUI()
Resets the UI property to a value from the current look and feel.

Methods inherited

This class inherits methods from the following classes:

  • java.awt.Container

  • java.awt.Component

  • java.lang.Object

Swing JLabel Class

Introduction

The class JLabel can display either text, an image, or both. Label's contents are aligned by setting the vertical and horizontal alignment in its display area. By default, labels are vertically centered in their display area. Text-only labels are leading edge aligned, by default; image-only labels are horizontally centered, by default.

Class declaration

Following is the declaration for javax.swing.JLabel class:

public class JLabel
   extends JComponent
      implements SwingConstants, Accessible

Field

Following are the fields for javax.swing.JLabel class:

  • protected Component labelFor

Class constructors

S.N.Constructor & Description
1JLabel()
Creates a JLabel instance with no image and with an empty string for the title.
2JLabel(Icon image)
Creates a JLabel instance with the specified image.
3JLabel(Icon image, int horizontalAlignment)
Creates a JLabel instance with the specified image and horizontal alignment.
4JLabel(String text)
Creates a JLabel instance with the specified text.
5JLabel(String text, Icon icon, int horizontalAlignment)
Creates a JLabel instance with the specified text, image, and horizontal alignment.
6JLabel(String text, int horizontalAlignment)
Creates a JLabel instance with the specified text and horizontal alignment.

Class methods

S.N.Method & Description
1protected int checkHorizontalKey(int key, String message)
Verify that key is a legal value for the horizontalAlignment properties.
2protected int checkVerticalKey(int key, String message)
Verify that key is a legal value for the verticalAlignment or verticalTextPosition properties.
3AccessibleContext getAccessibleContext()
Get the AccessibleContext of this object.
4Icon getDisabledIcon()
Returns the icon used by the label when it's disabled.
5int getDisplayedMnemonic()
Return the keycode that indicates a mnemonic key.
6int getDisplayedMnemonicIndex()
Returns the character, as an index, that the look and feel should provide decoration for as representing the mnemonic character.
7int getHorizontalAlignment()
Returns the alignment of the label's contents along the X axis.
8int getHorizontalTextPosition()
Returns the horizontal position of the label's text, relative to its image.
9Icon getIcon()
Returns the graphic image (glyph, icon) that the label displays.
10int getIconTextGap()
Returns the amount of space between the text and the icon displayed in this label.
11Component getLabelFor()
Get the component this is labelling.
12String getText()
Returns the text string that the label displays.
13LabelUI getUI()
Returns the L&F object that renders this component.
14String getUIClassID()
Returns a string that specifies the name of the l&f class that renders this component.
15int getVerticalAlignment()
Returns the alignment of the label's contents along the Y axis.
16int getVerticalTextPosition()
Returns the vertical position of the label's text, relative to its image.
17boolean imageUpdate(Image img, int infoflags, int x, int y, int w, int h)
This is overridden to return false if the current Icon's Image is not equal to the passed in Image img.
18protected String paramString()
Returns a string representation of this JLabel.
19void setDisabledIcon(Icon disabledIcon)
Set the icon to be displayed if this JLabel is "disabled" (JLabel.setEnabled(false)).
20void setDisplayedMnemonic(char aChar)
Specifies the displayedMnemonic as a char value.
21void setDisplayedMnemonic(int key)
Specify a keycode that indicates a mnemonic key.
22void setDisplayedMnemonicIndex(int index)
Provides a hint to the look and feel as to which character in the text should be decorated to represent the mnemonic.
23void setHorizontalAlignment(int alignment)
Sets the alignment of the label's contents along the X axis.
24void setHorizontalTextPosition(int textPosition)
Sets the horizontal position of the label's text, relative to its image.
25void setIcon(Icon icon)
Defines the icon this component will display.
26void setIconTextGap(int iconTextGap)
If both the icon and text properties are set, this property defines the space between them.
27void setLabelFor(Component c)
Set the component this is labelling.
28void setText(String text)
Defines the single line of text this component will display.
29void setUI(LabelUI ui)
Sets the L&F object that renders this component.
30void setVerticalAlignment(int alignment)
Sets the alignment of the label's contents along the Y axis.
31void setVerticalTextPosition(int textPosition)
Sets the vertical position of the label's text, relative to its image.
32void updateUI()
Resets the UI property to a value from the current look and feel.

Methods inherited

This class inherits methods from the following classes:

  • javax.swing.JComponent

  • java.awt.Container

  • java.awt.Component

  • java.lang.Object

JLabel Example

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

SwingControlDemo.java
package com.tutorialspoint.gui;
 
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
 
public class SwingControlDemo {
    
   private JFrame mainFrame;
   private JLabel headerLabel;
   private JLabel statusLabel;
   private JPanel controlPanel;

   public SwingControlDemo(){
      prepareGUI();
   }

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

   private void prepareGUI(){
      mainFrame = new JFrame("Java Swing 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 JLabel("", JLabel.CENTER);        
      statusLabel = new JLabel("",JLabel.CENTER);    

      statusLabel.setSize(350,100);

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

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

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

      JLabel label  = new JLabel("", JLabel.CENTER);        
      label.setText("Welcome to TutorialsPoint Swing Tutorial.");
      label.setOpaque(true);
      label.setBackground(Color.GRAY);
      label.setForeground(Color.WHITE);
      controlPanel.add(label);

      mainFrame.setVisible(true);  
   }
}

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

D:\SWING>javac com\tutorialspoint\gui\SwingControlDemo.java

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

D:\SWING>java com.tutorialspoint.gui.SwingControlDemo

Verify the following output

Swing JLabel

Swing JButton Class

Introduction

The class JButton is an implementation of a push button. This component has a label and generates an event when pressed. It can have Image also.

Class declaration

Following is the declaration for javax.swing.JButton class:

public class JButton
   extends AbstractButton
      implements Accessible

Class constructors

S.N.Constructor & Description
1JButton()
Creates a button with no set text or icon.
2JButton(Action a)
Creates a button where properties are taken from the Action supplied.
3JButton(Icon icon)
Creates a button with an icon.
4JButton(String text)
Creates a button with text.
5JButton(String text, Icon icon)
Creates a button with initial text and an icon.

Class methods

S.N.Method & Description
1AccessibleContext getAccessibleContext()
Gets the AccessibleContext associated with this JButton.
2String getUIClassID()
Returns a string that specifies the name of the L&F class that renders this component.
3boolean isDefaultButton()
Gets the value of the defaultButton property, which if true means that this button is the current default button for its JRootPane.
4boolean isDefaultCapable()
Gets the value of the defaultCapable property.
5protected String paramString()
Returns a string representation of this JButton.
6void removeNotify()
Overrides JComponent.removeNotify to check if this button is currently set as the default button on the RootPane, and if so, sets the RootPane's default button to null to ensure the RootPane doesn't hold onto an invalid button reference.
7void setDefaultCapable(boolean defaultCapable)
Sets the defaultCapable property, which determines whether this button can be made the default button for its root pane.
8void updateUI()
Resets the UI property to a value from the current look and feel.

Methods inherited

This class inherits methods from the following classes:

  • javax.swing.AbstractButton

  • javax.swing.JComponent

  • java.awt.Container

  • java.awt.Component

  • java.lang.Object

JButton Example

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

SwingControlDemo.java
package com.tutorialspoint.gui;
 
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
 
public class SwingControlDemo {
    
   private JFrame mainFrame;
   private JLabel headerLabel;
   private JLabel statusLabel;
   private JPanel controlPanel;

   public SwingControlDemo(){
      prepareGUI();
   }

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

   private void prepareGUI(){
      mainFrame = new JFrame("Java Swing 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 JLabel("", JLabel.CENTER);        
      statusLabel = new JLabel("",JLabel.CENTER);    

      statusLabel.setSize(350,100);

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

      mainFrame.add(headerLabel);
      mainFrame.add(controlPanel);
      mainFrame.add(statusLabel);
      mainFrame.setVisible(true);  
   }
    
   private static ImageIcon createImageIcon(String path, 
      String description) {
      java.net.URL imgURL = SwingControlDemo.class.getResource(path);
      if (imgURL != null) {
         return new ImageIcon(imgURL, description);
      } else {            
         System.err.println("Couldn't find file: " + path);
         return null;
      }
   }   

   private void showButtonDemo(){

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

      //resources folder should be inside SWING folder.
      ImageIcon icon = createImageIcon("/resources/java_icon.png","Java");

      JButton okButton = new JButton("OK");        
      JButton javaButton = new JButton("Submit", icon);
      JButton cancelButton = new JButton("Cancel", icon);
      cancelButton.setHorizontalTextPosition(SwingConstants.LEFT);   

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

      javaButton.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(javaButton);
      controlPanel.add(cancelButton);       

      mainFrame.setVisible(true);  
   }
}

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

D:\SWING>javac com\tutorialspoint\gui\SwingControlDemo.java

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

D:\SWING>java com.tutorialspoint.gui.SwingControlDemo

Verify the following output

Swing JButton

Swing JColorChooser Class

Introduction

The class JColorChooser provides a pane of controls designed to allow a user to manipulate and select a color.

Class declaration

Following is the declaration for javax.swing.JColorChooser class:

public class JColorChooser
   extends JComponent
      implements Accessible

Field

Following are the fields for javax.swing.JLabel class:

  • protected AccessibleContext accessibleContext

  • static String CHOOSER_PANELS_PROPERTY -- The chooserPanel array property name.

  • static String PREVIEW_PANEL_PROPERTY -- The preview panel property name.

  • static String SELECTION_MODEL_PROPERTY -- The selection model property name

Class constructors

S.N.Constructor & Description
1JColorChooser()
Creates a color chooser pane with an initial color of white.
2JColorChooser(Color initialColor)
Creates a color chooser pane with the specified initial color.
3JColorChooser(ColorSelectionModel model)
Creates a color chooser pane with the specified ColorSelectionModel.

Class methods

S.N.Method & Description
1void addChooserPanel(AbstractColorChooserPanel panel)
Adds a color chooser panel to the color chooser.
2static JDialog createDialog(Component c, String title, boolean modal, JColorChooser chooserPane, ActionListener okListener, ActionListener cancelListener)
Creates and returns a new dialog containing the specified ColorChooser pane along with "OK", "Cancel", and "Reset" buttons.
3AccessibleContext getAccessibleContext()
Gets the AccessibleContext associated with this JColorChooser.
4AbstractColorChooserPanel[] getChooserPanels()
Returns the specified color panels.
5Color getColor()
Gets the current color value from the color chooser.
6boolean getDragEnabled()
Gets the value of the dragEnabled property.
7JComponent getPreviewPanel()
Returns the preview panel that shows a chosen color.
8ColorSelectionModel getSelectionModel()
Returns the data model that handles color selections.
9ColorChooserUI getUI()
Returns the L&F object that renders this component.
10String getUIClassID()
Returns the name of the L&F class that renders this component.
11protected String paramString()
Returns a string representation of this JColorChooser.
12AbstractColorChooserPanel removeChooserPanel(AbstractColorChooserPanel panel)
Removes the Color Panel specified.
13void setChooserPanels(AbstractColorChooserPanel[] panels)
Specifies the Color Panels used to choose a color value.
14void setColor(Color color)
Sets the current color of the color chooser to the specified color.
15void setColor(int c)
Sets the current color of the color chooser to the specified color.
16void setColor(int r, int g, int b)
Sets the current color of the color chooser to the specified RGB color.
17void setDragEnabled(boolean b)
Sets the dragEnabled property, which must be true to enable automatic drag handling (the first part of drag and drop) on this component.
18void setPreviewPanel(JComponent preview)
Sets the current preview panel.
19void setSelectionModel(ColorSelectionModel newModel)
Sets the model containing the selected color.
20void setUI(ColorChooserUI ui)
Sets the L&F object that renders this component.
21static Color showDialog(Component component, String title, Color initialColor)
Shows a modal color-chooser dialog and blocks until the dialog is hidden.
22void updateUI()
Notification from the UIManager that the L&F has changed.

Methods inherited

This class inherits methods from the following classes:

  • javax.swing.JComponent

  • java.awt.Container

  • java.awt.Component

  • java.lang.Object

JColorChooser Example

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

SwingControlDemo.java
package com.tutorialspoint.gui;
 
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
 
public class SwingControlDemo {
    
   private JFrame mainFrame;
   private JLabel headerLabel;
   private JLabel statusLabel;
   private JPanel controlPanel;

   public SwingControlDemo(){
      prepareGUI();
   }

   public static void main(String[] args){
      SwingControlDemo  swingControlDemo = new SwingControlDemo();      
      swingControlDemo.showColorChooserDemo();
   }

   private void prepareGUI(){
      mainFrame = new JFrame("Java Swing 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 JLabel("", JLabel.CENTER);        
      statusLabel = new JLabel("",JLabel.CENTER);    

      statusLabel.setSize(350,100);

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

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

   private void showColorChooserDemo(){
      headerLabel.setText("Control in action: JColorChooser"); 

      JButton chooseButton = new JButton("Choose Background");        
      chooseButton.addActionListener(new ActionListener() {
         public void actionPerformed(ActionEvent e) {
            Color backgroundColor = JColorChooser.showDialog(mainFrame,
               "Choose background color", Color.white);
            if(backgroundColor != null){
               controlPanel.setBackground(backgroundColor);
               mainFrame.getContentPane().setBackground(backgroundColor);
            }
         }
      });

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

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

D:\SWING>javac com\tutorialspoint\gui\SwingControlDemo.java

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

D:\SWING>java com.tutorialspoint.gui.SwingControlDemo

Verify the following output

Swing JColorChooser

Swing JCheckBox Class

Introduction

The class JCheckBox is an implementation of a check box - an item that can be selected or deselected, and which displays its state to the user.

Class declaration

Following is the declaration for javax.swing.JCheckBox class:

public class JCheckBox
   extends JToggleButton
      implements Accessible

Field

Following are the fields for javax.swing.JCheckBox class:

  • static String BORDER_PAINTED_FLAT_CHANGED_PROPERTY -- Identifies a change to the flat property.

Class constructors

S.N.Constructor & Description
1JCheckBox()
Creates an initially unselected check box button with no text, no icon.
2JCheckBox(Action a)
Creates a check box where properties are taken from the Action supplied.
3JCheckBox(Icon icon)
Creates an initially unselected check box with an icon.
4JCheckBox(Icon icon, boolean selected)
Creates a check box with an icon and specifies whether or not it is initially selected.
5JCheckBox(String text)
Creates an initially unselected check box with text.
6JCheckBox(String text, boolean selected)
Creates a check box with text and specifies whether or not it is initially selected.
7JCheckBox(String text, Icon icon)
Creates an initially unselected check box with the specified text and icon.
8JCheckBox(String text, Icon icon, boolean selected)
Creates a check box with text and icon, and specifies whether or not it is initially selected.

Class methods

S.N.Method & Description
1AccessibleContext getAccessibleContext()
Gets the AccessibleContext associated with this JCheckBox.
2String getUIClassID()
Returns a string that specifies the name of the L&F class that renders this component.
3boolean isBorderPaintedFlat()
Gets the value of the borderPaintedFlat property.
4protected String paramString()
Returns a string representation of this JCheckBox.
5void setBorderPaintedFlat(boolean b)
Sets the borderPaintedFlat property, which gives a hint to the look and feel as to the appearance of the check box border.
6void updateUI()
Resets the UI property to a value from the current look and feel.

Methods inherited

This class inherits methods from the following classes:

  • javax.swing.AbstractButton

  • javax.swing.JToggleButton

  • javax.swing.JComponent

  • java.awt.Container

  • java.awt.Component

  • java.lang.Object

JCheckBox Example

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

SwingControlDemo.java
package com.tutorialspoint.gui;
 
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
 
public class SwingControlDemo {
    
   private JFrame mainFrame;
   private JLabel headerLabel;
   private JLabel statusLabel;
   private JPanel controlPanel;

   public SwingControlDemo(){
      prepareGUI();
   }

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

   private void prepareGUI(){
      mainFrame = new JFrame("Java Swing 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 JLabel("", JLabel.CENTER);        
      statusLabel = new JLabel("",JLabel.CENTER);    

      statusLabel.setSize(350,100);

      controlPanel = new JPanel();
      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"); 

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

      chkApple.setMnemonic(KeyEvent.VK_C);
      chkMango.setMnemonic(KeyEvent.VK_M);
      chkPeer.setMnemonic(KeyEvent.VK_P);

      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:/ > SWING and type the following command.

D:\SWING>javac com\tutorialspoint\gui\SwingControlDemo.java

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

D:\SWING>java com.tutorialspoint.gui.SwingControlDemo

Verify the following output

Swing JCheckBox

Swing JRadioButton Class

Introduction

The class JRadioButton is an implementation of a radio button - an item that can be selected or deselected, and which displays its state to the user.

Class declaration

Following is the declaration for javax.swing.JRadioButton class:

public class JRadioButton
   extends JToggleButton
      implements Accessible

Class constructors

Creates an unselected radio button with the specified text.
S.N.Constructor & Description
1JRadioButton()
Creates an initially unselected radio button with no set text.
2JRadioButton(Action a)
Creates a radiobutton where properties are taken from the Action supplied.
3JRadioButton(Icon icon)
Creates an initially unselected radio button with the specified image but no text.
4JRadioButton(Icon icon, boolean selected)
Creates a radio button with the specified image and selection state, but no text.
5JRadioButton(String text, boolean selected)
Creates a radio button with the specified text and selection state.
6JRadioButton(String text, Icon icon)
Creates a radio button that has the specified text and image, and that is initially unselected.
7JRadioButton(String text, Icon icon, boolean selected)
Creates a radio button that has the specified text, image, and selection state.

Class methods

S.N.Method & Description
1AccessibleContext getAccessibleContext()
Gets the AccessibleContext associated with this JRadioButton.
2String getUIClassID()
Returns the name of the L&F class that renders this component.
3protected String paramString()
Returns a string representation of this JRadioButton.
4void updateUI()
Resets the UI property to a value from the current look and feel.

Methods inherited

This class inherits methods from the following classes:

  • javax.swing.AbstractButton

  • javax.swing.JToggleButton

  • javax.swing.JComponent

  • java.awt.Container

  • java.awt.Component

  • java.lang.Object

JRadioButton Example

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

SwingControlDemo.java
package com.tutorialspoint.gui;
 
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
 
public class SwingControlDemo {
    
   private JFrame mainFrame;
   private JLabel headerLabel;
   private JLabel statusLabel;
   private JPanel controlPanel;

   public SwingControlDemo(){
      prepareGUI();
   }

   public static void main(String[] args){
      SwingControlDemo  swingControlDemo = new SwingControlDemo();      
      swingControlDemo.showRadioButtonDemo();
   }

   private void prepareGUI(){
      mainFrame = new JFrame("Java Swing 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 JLabel("", JLabel.CENTER);        
      statusLabel = new JLabel("",JLabel.CENTER);    

      statusLabel.setSize(350,100);

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

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

   private void showRadioButtonDemo(){
      headerLabel.setText("Control in action: RadioButton"); 

      final JRadioButton radApple = new JRadioButton("Apple", true);
      final JRadioButton radMango = new JRadioButton("Mango");
      final JRadioButton radPeer = new JRadioButton("Peer");

      radApple.setMnemonic(KeyEvent.VK_C);
      radMango.setMnemonic(KeyEvent.VK_M);
      radPeer.setMnemonic(KeyEvent.VK_P);

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

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

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

      //Group the radio buttons.
      ButtonGroup group = new ButtonGroup();
      group.add(radApple);
      group.add(radMango);
      group.add(radPeer);

      controlPanel.add(radApple);
      controlPanel.add(radMango);
      controlPanel.add(radPeer);       

      mainFrame.setVisible(true);  
   }
}

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

D:\SWING>javac com\tutorialspoint\gui\SwingControlDemo.java

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

D:\SWING>java com.tutorialspoint.gui.SwingControlDemo

Verify the following output

Swing JRadioButton

Swing JList Class

Introduction

The class JList is a component which displays a list of objects and allows the user to select one or more items. A separate model, ListModel, maintains the contents of the list.

Class declaration

Following is the declaration for javax.swing.JList class:

public class JList
   extends JComponent
      implements Scrollable, Accessible

Field

Following are the fields for javax.swing.JList class:

  • static int HORIZONTAL_WRAP --Indicates a "newspaper style" layout with cells flowing horizontally then vertically.

  • static int VERTICAL -- Indicates a vertical layout of cells, in a single column; the default layout.

  • static int VERTICAL_WRAP -- Indicates a "newspaper style" layout with cells flowing vertically then horizontally.

Class constructors

S.N.Constructor & Description
1JList()
Constructs a JList with an empty, read-only, model.
2JList(ListModel dataModel)
Constructs a JList that displays elements from the specified, non-null, model.
3JList(Object[] listData)
Constructs a JList that displays the elements in the specified array.
4JList(Vector<?> listData)
Constructs a JList that displays the elements in the specified Vector.

Class methods

S.N.Method & Description
1void addListSelectionListener(ListSelectionListener listener)
Adds a listener to the list, to be notified each time a change to the selection occurs; the preferred way of listening for selection state changes.
2void addSelectionInterval(int anchor, int lead)
Sets the selection to be the union of the specified interval with current selection.
3void clearSelection()
Clears the selection; after calling this method, isSelectionEmpty will return true.
4protected ListSelectionModel createSelectionModel()
Returns an instance of DefaultListSelectionModel; called during construction to initialize the list's selection model property.
5void ensureIndexIsVisible(int index)
Scrolls the list within an enclosing viewport to make the specified cell completely visible.
6protected void fireSelectionValueChanged(int firstIndex, int lastIndex, boolean isAdjusting)
Notifies ListSelectionListeners added directly to the list of selection changes made to the selection model.
7AccessibleContext getAccessibleContext()
Gets the AccessibleContext associated with this JList.
8int getAnchorSelectionIndex()
Returns the anchor selection index.
9Rectangle getCellBounds(int index0, int index1)
Returns the bounding rectangle, in the list's coordinate system, for the range of cells specified by the two indices.
10ListCellRenderer getCellRenderer()
Returns the object responsible for painting list items.
11boolean getDragEnabled()
Returns whether or not automatic drag handling is enabled.
12JList.DropLocation getDropLocation()
Returns the location that this component should visually indicate as the drop location during a DnD operation over the component, or null if no location is to currently be shown.
13DropMode getDropMode()
Returns the drop mode for this component.
14int getFirstVisibleIndex()
Returns the smallest list index that is currently visible.
15int getFixedCellHeight()
Returns the value of the fixedCellHeight property.
16int getFixedCellWidth()
Returns the value of the fixedCellWidth property.
17int getLastVisibleIndex()
Returns the largest list index that is currently visible.
18int getLayoutOrientation()
Returns the layout orientation property for the list: VERTICAL if the layout is a single column of cells, VERTICAL_WRAP if the layout is "newspaper style" with the content flowing vertically then horizontally, or HORIZONTAL_WRAP if the layout is "newspaper style" with the content flowing horizontally then vertically.
19int getLeadSelectionIndex()
Returns the lead selection index.
20ListSelectionListener[] getListSelectionListeners()
Returns an array of all the ListSelectionListeners added to this JList by way of addListSelectionListener.
21int getMaxSelectionIndex()
Returns the largest selected cell index, or -1 if the selection is empty.
22int getMinSelectionIndex()
Returns the smallest selected cell index, or -1 if the selection is empty.
23ListModel getModel()
Returns the data model that holds the list of items displayed by the JList component.
24int getNextMatch(String prefix, int startIndex, Position.Bias bias)
Returns the next list element whose toString value starts with the given prefix.
25Dimension getPreferredScrollableViewportSize()
Computes the size of viewport needed to display visibleRowCount rows.
26Object getPrototypeCellValue()
Returns the "prototypical" cell value -- a value used to calculate a fixed width and height for cells.
27int getScrollableBlockIncrement(Rectangle visibleRect, int orientation, int direction)
Returns the distance to scroll to expose the next or previous block.
28boolean getScrollableTracksViewportHeight()
Returns true if this JList is displayed in a JViewport and the viewport is taller than the list's preferred height, or if the layout orientation is VERTICAL_WRAP and visibleRowCount <= 0; otherwise returns false.
29boolean getScrollableTracksViewportWidth()
Returns true if this JList is displayed in a JViewport and the viewport is wider than the list's preferred width, or if the layout orientation is HORIZONTAL_WRAP and visibleRowCount <= 0; otherwise returns false.
30int getScrollableUnitIncrement(Rectangle visibleRect, int orientation, int direction)
Returns the distance to scroll to expose the next or previous row (for vertical scrolling) or column (for horizontal scrolling).
31int getSelectedIndex()
Returns the smallest selected cell index; the selection when only a single item is selected in the list.
32int[] getSelectedIndices()
Returns an array of all of the selected indices, in increasing order.
33Object getSelectedValue()
Returns the value for the smallest selected cell index; the selected value when only a single item is selected in the list.
34Object[] getSelectedValues()
Returns an array of all the selected values, in increasing order based on their indices in the list.
35Color getSelectionBackground()
Returns the color used to draw the background of selected items.
36Color getSelectionForeground()
Returns the color used to draw the foreground of selected items.
37int getSelectionMode()
Returns the current selection mode for the list.
38ListSelectionModel getSelectionModel()
Returns the current selection model.
39String getToolTipText(MouseEvent event)
Returns the tooltip text to be used for the given event.
40ListUI getUI()
Returns the ListUI, the look and feel object that renders this component.
41String getUIClassID()
Returns "ListUI", the UIDefaults key used to look up the name of the javax.swing.plaf.ListUI class that defines the look and feel for this component.
42boolean getValueIsAdjusting()
Returns the value of the selection model's isAdjusting property.
43int getVisibleRowCount()
Returns the value of the visibleRowCount property.
44Point indexToLocation(int index)
Returns the origin of the specified item in the list's coordinate system.
45boolean isSelectedIndex(int index)
Returns true if the specified index is selected, else false.
46boolean isSelectionEmpty()
Returns true if nothing is selected, else false.
47int locationToIndex(Point location)
Returns the cell index closest to the given location in the list's coordinate system.
48protected String paramString()
Returns a String representation of this JList.
49void removeListSelectionListener(ListSelectionListener listener)
Removes a selection listener from the list.
50void removeSelectionInterval(int index0, int index1)
Sets the selection to be the set difference of the specified interval and the current selection.
51void setCellRenderer(ListCellRenderer cellRenderer)
Sets the delegate that is used to paint each cell in the list.
52void setDragEnabled(boolean b)
Turns on or off automatic drag handling.
53void setDropMode(DropMode dropMode)
Sets the drop mode for this component.
54void setFixedCellHeight(int height)
Sets a fixed value to be used for the height of every cell in the list.
55void setFixedCellWidth(int width)
Sets a fixed value to be used for the width of every cell in the list.
56void setLayoutOrientation(int layoutOrientation)
Defines the way list cells are layed out.
57void setListData(Object[] listData)
Constructs a read-only ListModel from an array of objects, and calls setModel with this model.
58void setListData(Vector<?> listData)
Constructs a read-only ListModel from a Vector and calls setModel with this model.
59void setModel(ListModel model)
Sets the model that represents the contents or "value" of the list, notifies property change listeners, and then clears the list's selection.
60void setPrototypeCellValue(Object prototypeCellValue)
Sets the prototypeCellValue property, and then (if the new value is non-null), computes the fixedCellWidth and fixedCellHeight properties by requesting the cell renderer component for the given value (and index 0) from the cell renderer, and using that component's preferred size.
61void setSelectedIndex(int index)
Selects a single cell.
62void setSelectedIndices(int[] indices)
Changes the selection to be the set of indices specified by the given array.
63void setSelectedValue(Object anObject, boolean shouldScroll)
Selects the specified object from the list.
64void setSelectionBackground(Color selectionBackground)
Sets the color used to draw the background of selected items, which cell renderers can use fill selected cells.
65void setSelectionForeground(Color selectionForeground)
Sets the color used to draw the foreground of selected items, which cell renderers can use to render text and graphics.
66void setSelectionInterval(int anchor, int lead)
Selects the specified interval.
67void setSelectionMode(int selectionMode)
Sets the selection mode for the list.
68void setSelectionModel(ListSelectionModel selectionModel)
Sets the selectionModel for the list to a non-null ListSelectionModel implementation.
69void setUI(ListUI ui)
Sets the ListUI, the look and feel object that renders this component.
70void setValueIsAdjusting(boolean b)
Sets the selection model's valueIsAdjusting property.
71void setVisibleRowCount(int visibleRowCount)
Sets the visibleRowCount property, which has different meanings depending on the layout orientation: For a VERTICAL layout orientation, this sets the preferred number of rows to display without requiring scrolling; for other orientations, it affects the wrapping of cells.
72void updateUI()
Resets the ListUI property by setting it to the value provided by the current look and feel.

Methods inherited

This class inherits methods from the following classes:

  • javax.swing.JComponent

  • java.awt.Container

  • java.awt.Component

  • java.lang.Object

JList Example

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

SwingControlDemo.java
package com.tutorialspoint.gui;
 
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
 
public class SwingControlDemo {
    
   private JFrame mainFrame;
   private JLabel headerLabel;
   private JLabel statusLabel;
   private JPanel controlPanel;

   public SwingControlDemo(){
      prepareGUI();
   }

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

   private void prepareGUI(){
      mainFrame = new JFrame("Java Swing 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 JLabel("", JLabel.CENTER);        
      statusLabel = new JLabel("",JLabel.CENTER);    

      statusLabel.setSize(350,100);

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

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

   private void showListDemo(){                                       

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

      final DefaultListModel fruitsName = new DefaultListModel();

      fruitsName.addElement("Apple");
      fruitsName.addElement("Grapes");
      fruitsName.addElement("Mango");
      fruitsName.addElement("Peer");

      final JList fruitList = new JList(fruitsName);
      fruitList.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
      fruitList.setSelectedIndex(0);
      fruitList.setVisibleRowCount(3);        

      JScrollPane fruitListScrollPane = new JScrollPane(fruitList);    

      final DefaultListModel vegName = new DefaultListModel();

      vegName.addElement("Lady Finger");
      vegName.addElement("Onion");
      vegName.addElement("Potato");
      vegName.addElement("Tomato");

      final JList vegList = new JList(vegName);
      vegList.setSelectionMode(
         ListSelectionModel.MULTIPLE_INTERVAL_SELECTION);
      vegList.setSelectedIndex(0);
      vegList.setVisibleRowCount(3);        

      JScrollPane vegListScrollPane = new JScrollPane(vegList);       

      JButton showButton = new JButton("Show");

      showButton.addActionListener(new ActionListener() {
         public void actionPerformed(ActionEvent e) { 
            String data = "";
            if (fruitList.getSelectedIndex() != -1) {                     
               data = "Fruits Selected: " + fruitList.getSelectedValue(); 
               statusLabel.setText(data);
            }
            if(vegList.getSelectedIndex() != -1){
               data += " Vegetables selected: ";
               for(Object vegetable:vegList.getSelectedValues()){
                  data += vegetable + " ";
               }
            }
            statusLabel.setText(data);
         }
      }); 

      controlPanel.add(fruitListScrollPane);    
      controlPanel.add(vegListScrollPane);    
      controlPanel.add(showButton);    
	  
      mainFrame.setVisible(true);             
   }
}

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

D:\SWING>javac com\tutorialspoint\gui\SwingControlDemo.java

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

D:\SWING>java com.tutorialspoint.gui.SwingControlDemo

Verify the following output

Swing JList

Swing JComboBox Class

Introduction

The class JComboBox is a component which combines a button or editable field and a drop-down list.

Class declaration

Following is the declaration for javax.swing.JComboBox class:

public class JComboBox
   extends JComponent
      implements ItemSelectable, ListDataListener, 
         ActionListener, Accessible

Field

Following are the fields for javax.swing.JList class:

  • protected String actionCommand -- This protected field is implementation specific.

  • protected ComboBoxModel dataModel -- This protected field is implementation specific.

  • protected ComboBoxEditor editor -- This protected field is implementation specific.

  • protected boolean isEditable -- This protected field is implementation specific.

  • protected JComboBox.KeySelectionManager keySelectionManager -- This protected field is implementation specific.

  • protected boolean lightWeightPopupEnabled -- This protected field is implementation specific.

  • protected int maximumRowCount -- This protected field is implementation specific.

  • protected ListCellRenderer renderer -- This protected field is implementation specific.

  • protected Object selectedItemReminder -- This protected field is implementation specific.

Class constructors

S.N.Constructor & Description
1JComboBox()
Creates a JComboBox with a default data model.
2JComboBox(ComboBoxModel aModel)
Creates a JComboBox that takes its items from an existing ComboBoxModel.
3JComboBox(Object[] items)
Creates a JComboBox that contains the elements in the specified array.
4JComboBox(Vector<?> items)
Creates a JComboBox that contains the elements in the specified Vector.

Class methods

S.N.Method & Description
1void actionPerformed(ActionEvent e)
This method is public as an implementation side effect.
2protected void actionPropertyChanged(Action action, String propertyName)
Updates the combobox's state in response to property changes in associated action.
3void addActionListener(ActionListener l)
Adds an ActionListener.
4void addItem(Object anObject)
Adds an item to the item list.
5void addItemListener(ItemListener aListener)
Adds an ItemListener.
6void addPopupMenuListener(PopupMenuListener l)
Adds a PopupMenu listener which will listen to notification messages from the popup portion of the combo box.
7void configureEditor(ComboBoxEditor anEditor, Object anItem)
Initializes the editor with the specified item.
8protected void configurePropertiesFromAction(Action a)
Sets the properties on this combobox to match those in the specified Action.
9void contentsChanged(ListDataEvent e)
This method is public as an implementation side effect.
10protected PropertyChangeListener createActionPropertyChangeListener(Action a)
Creates and returns a PropertyChangeListener that is responsible for listening for changes from the specified Action and updating the appropriate properties.
11protected JComboBox.KeySelectionManager createDefaultKeySelectionManager()
Returns an instance of the default key-selection manager.
12protected void fireActionEvent()
Notifies all listeners that have registered interest for notification on this event type.
13protected void fireItemStateChanged(ItemEvent e)
Notifies all listeners that have registered interest for notification on this event type.
14void firePopupMenuCanceled()
Notifies PopupMenuListeners that the popup portion of the combo box has been canceled.
15void firePopupMenuWillBecomeInvisible()
Notifies PopupMenuListeners that the popup portion of the combo box has become invisible.
16void firePopupMenuWillBecomeVisible()
Notifies PopupMenuListeners that the popup portion of the combo box will become visible.
17AccessibleContext getAccessibleContext()
Gets the AccessibleContext associated with this JComboBox.
18Action getAction()
Returns the currently set Action for this ActionEvent source, or null if no Action is set.
19String getActionCommand()
Returns the action command that is included in the event sent to action listeners.
20ActionListener[] getActionListeners()
Returns an array of all the ActionListeners added to this JComboBox with addActionListener().
21ComboBoxEditor getEditor()
Returns the editor used to paint and edit the selected item in the JComboBox field.
22Object getItemAt(int index)
Returns the list item at the specified index.
23int getItemCount()
Returns the number of items in the list.
24ItemListener[] getItemListeners()
Returns an array of all the ItemListeners added to this JComboBox with addItemListener().
25JComboBox.KeySelectionManager getKeySelectionManager()
Returns the list's key-selection manager.
26int getMaximumRowCount()
Returns the maximum number of items the combo box can display without a scrollbar.
27ComboBoxModel getModel()
Returns the data model currently used by the JComboBox.
28PopupMenuListener[] getPopupMenuListeners()
Returns an array of all the PopupMenuListeners added to this JComboBox with addPopupMenuListener().
29Object getPrototypeDisplayValue()
Returns the "prototypical display" value - an Object used for the calculation of the display height and width.
30ListCellRenderer getRenderer()
Returns the renderer used to display the selected item in the JComboBox field.
31int getSelectedIndex()
Returns the first item in the list that matches the given item.
32Object getSelectedItem()
Returns the current selected item.
33Object[] getSelectedObjects()
Returns an array containing the selected item.
34ComboBoxUI getUI()
Returns the L&F object that renders this component.
35String getUIClassID()
Returns the name of the L&F class that renders this component.
36void hidePopup()
Causes the combo box to close its popup window.
37void insertItemAt(Object anObject, int index)
Inserts an item into the item list at a given index.
38protected void installAncestorListener()
39void intervalAdded(ListDataEvent e)
This method is public as an implementation side effect.
40void intervalRemoved(ListDataEvent e)
This method is public as an implementation side effect.
41boolean isEditable()
Returns true if the JComboBox is editable.
42boolean isLightWeightPopupEnabled()
Gets the value of the lightWeightPopupEnabled property.
43boolean isPopupVisible()
Determines the visibility of the popup.
44protected String paramString()
Returns a string representation of this JComboBox.
45void processKeyEvent(KeyEvent e)
Handles KeyEvents, looking for the Tab key.
46void removeActionListener(ActionListener l)
Removes an ActionListener.
47void removeAllItems()
Removes all items from the item list.
48void removeItem(Object anObject)
Removes an item from the item list.
49void removeItemAt(int anIndex)
Removes the item at anIndex This method works only if the JComboBox uses a mutable data model.
50void removeItemListener(ItemListener aListener)
Removes an ItemListener.
51void removePopupMenuListener(PopupMenuListener l)
Removes a PopupMenuListener.
52protected void selectedItemChanged()
This protected method is implementation specific.
53boolean selectWithKeyChar(char keyChar)
Selects the list item that corresponds to the specified keyboard character and returns true, if there is an item corresponding to that character.
54void setAction(Action a)
Sets the Action for the ActionEvent source.
55void setActionCommand(String aCommand)
Sets the action command that should be included in the event sent to action listeners.
56void setEditable(boolean aFlag)
Determines whether the JComboBox field is editable.
57void setEditor(ComboBoxEditor anEditor)
Sets the editor used to paint and edit the selected item in the JComboBox field.
58void setEnabled(boolean b)
Enables the combo box so that items can be selected.
59void setKeySelectionManager(JComboBox.KeySelectionManager aManager)
Sets the object that translates a keyboard character into a list selection.
60void setLightWeightPopupEnabled(boolean aFlag)
Sets the lightWeightPopupEnabled property, which provides a hint as to whether or not a lightweight Component should be used to contain the JComboBox, versus a heavyweight Component such as a Panel or a Window.
61void setMaximumRowCount(int count)
Sets the maximum number of rows the JComboBox displays.
62void setModel(ComboBoxModel aModel)
Sets the data model that the JComboBox uses to obtain the list of items.
63void setPopupVisible(boolean v)
Sets the visibility of the popup.
64void setPrototypeDisplayValue(Object prototypeDisplayValue)
Sets the prototype display value used to calculate the size of the display for the UI portion.
65void setRenderer(ListCellRenderer aRenderer)
Sets the renderer that paints the list items and the item selected from the list in the JComboBox field.
66void setSelectedIndex(int anIndex)
Selects the item at index anIndex.
67void setSelectedItem(Object anObject)
Sets the selected item in the combo box display area to the object in the argument.
68void setUI(ComboBoxUI ui)
Sets the L&F object that renders this component.
69void showPopup()
Causes the combo box to display its popup window.
70void updateUI()
Resets the UI property to a value from the current look and feel.

Methods inherited

This class inherits methods from the following classes:

  • javax.swing.JComponent

  • java.awt.Container

  • java.awt.Component

  • java.lang.Object

JComboBox Example

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

SwingControlDemo.java
package com.tutorialspoint.gui;
 
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
 
public class SwingControlDemo {
    
   private JFrame mainFrame;
   private JLabel headerLabel;
   private JLabel statusLabel;
   private JPanel controlPanel;

   public SwingControlDemo(){
      prepareGUI();
   }

   public static void main(String[] args){
      SwingControlDemo  swingControlDemo = new SwingControlDemo();      
      swingControlDemo.showComboboxDemo();
   }

   private void prepareGUI(){
      mainFrame = new JFrame("Java Swing 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 JLabel("", JLabel.CENTER);        
      statusLabel = new JLabel("",JLabel.CENTER);    

      statusLabel.setSize(350,100);

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

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

   private void showComboboxDemo(){                                    
      headerLabel.setText("Control in action: JComboBox"); 

      final DefaultComboBoxModel fruitsName = new DefaultComboBoxModel();

      fruitsName.addElement("Apple");
      fruitsName.addElement("Grapes");
      fruitsName.addElement("Mango");
      fruitsName.addElement("Peer");

      final JComboBox fruitCombo = new JComboBox(fruitsName);    
      fruitCombo.setSelectedIndex(0);

      JScrollPane fruitListScrollPane = new JScrollPane(fruitCombo);    

      JButton showButton = new JButton("Show");

      showButton.addActionListener(new ActionListener() {
         public void actionPerformed(ActionEvent e) { 
            String data = "";
            if (fruitCombo.getSelectedIndex() != -1) {                     
               data = "Fruits Selected: " 
                  + fruitCombo.getItemAt
                    (fruitCombo.getSelectedIndex());             
            }              
            statusLabel.setText(data);
         }
      }); 
      controlPanel.add(fruitListScrollPane);          
      controlPanel.add(showButton);    
      mainFrame.setVisible(true);             
   }
}

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

D:\SWING>javac com\tutorialspoint\gui\SwingControlDemo.java

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

D:\SWING>java com.tutorialspoint.gui.SwingControlDemo

Verify the following output

Swing JComboBox

Swing JTextField Class

Introduction

The class JTextField is a component which allows the editing of a single line of text.

Class declaration

Following is the declaration for javax.swing.JTextField class:

public class JTextField
   extends JTextComponent
      implements SwingConstants

Field

Following are the fields for javax.swing.JList class:

  • static String notifyAction -- Name of the action to send notification that the contents of the field have been accepted.

Class constructors

S.N.Constructor & Description
1JTextField()
Constructs a new TextField.
2JTextField(Document doc, String text, int columns)
Constructs a new JTextField that uses the given text storage model and the given number of columns.
3JTextField(int columns)
Constructs a new empty TextField with the specified number of columns.
4JTextField(String text)
Constructs a new TextField initialized with the specified text.
5JTextField(String text, int columns)
Constructs a new TextField initialized with the specified text and columns.

Class methods

S.N.Method & Description
1protected void actionPropertyChanged(Action action, String propertyName)
Updates the textfield's state in response to property changes in associated action.
2void addActionListener(ActionListener l)
Adds the specified action listener to receive action events from this textfield.
3protected void configurePropertiesFromAction(Action a)
Sets the properties on this textfield to match those in the specified Action.
4protected PropertyChangeListener createActionPropertyChangeListener(Action a)
Creates and returns a PropertyChangeListener that is responsible for listening for changes from the specified Action and updating the appropriate properties.
5protected Document createDefaultModel()
Creates the default implementation of the model to be used at construction if one isn't explicitly given.
6protected void fireActionPerformed()
Notifies all listeners that have registered interest for notification on this event type.
7AccessibleContext getAccessibleContext()
Gets the AccessibleContext associated with this JTextField.
8Action getAction()
Returns the currently set Action for this ActionEvent source, or null if no Action is set.
9ActionListener[] getActionListeners()
Returns an array of all the ActionListeners added to this JTextField with addActionListener().
10Action[] getActions()
Fetches the command list for the editor.
11int getColumns()
Returns the number of columns in this TextField.
12protected int getColumnWidth()
Returns the column width.
13int getHorizontalAlignment()
Returns the horizontal alignment of the text.
14BoundedRangeModel getHorizontalVisibility()
Gets the visibility of the text field.
15Dimension getPreferredSize()
Returns the preferred size Dimensions needed for this TextField.
16int getScrollOffset()
Gets the scroll offset, in pixels.
17String getUIClassID()
Gets the class ID for a UI.
18boolean isValidateRoot()
Calls to revalidate that come from within the textfield itself will be handled by validating the textfield, unless the textfield is contained within a JViewport, in which case this returns false.
19protected String paramString()
Returns a string representation of this JTextField.
20void postActionEvent()
Processes action events occurring on this textfield by dispatching them to any registered ActionListener objects.
21void removeActionListener(ActionListener l)
Removes the specified action listener so that it no longer receives action events from this textfield.
22void scrollRectToVisible(Rectangle r)
Scrolls the field left or right.
23void setAction(Action a)
Sets the Action for the ActionEvent source.
24void setActionCommand(String command)
Sets the command string used for action events.
25void setColumns(int columns)
Sets the number of columns in this TextField, and then invalidate the layout.
26void setDocument(Document doc)
Associates the editor with a text document.
27void setFont(Font f)
Sets the current font.
28void setHorizontalAlignment(int alignment)
Sets the horizontal alignment of the text.
29void setScrollOffset(int scrollOffset)
Sets the scroll offset, in pixels.

Methods inherited

This class inherits methods from the following classes:

  • javax.swing.text.JTextComponent

  • javax.swing.JComponent

  • java.awt.Container

  • java.awt.Component

  • java.lang.Object

JTextField Example

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

SwingControlDemo.java
package com.tutorialspoint.gui;
 
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
 
public class SwingControlDemo {
    
   private JFrame mainFrame;
   private JLabel headerLabel;
   private JLabel statusLabel;
   private JPanel controlPanel;

   public SwingControlDemo(){
      prepareGUI();
   }

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

   private void prepareGUI(){
      mainFrame = new JFrame("Java Swing 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 JLabel("", JLabel.CENTER);        
      statusLabel = new JLabel("",JLabel.CENTER);    

      statusLabel.setSize(350,100);

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

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

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

      JLabel  namelabel= new JLabel("User ID: ", JLabel.RIGHT);
      JLabel  passwordLabel = new JLabel("Password: ", JLabel.CENTER);
      final JTextField userText = new JTextField(6);
      final JPasswordField passwordText = new JPasswordField(6);      

      JButton loginButton = new JButton("Login");
      loginButton.addActionListener(new ActionListener() {
         public void actionPerformed(ActionEvent e) {     
            String data = "Username " + userText.getText();
            data += ", Password: " 
            + new String(passwordText.getPassword()); 
            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:/ > SWING and type the following command.

D:\SWING>javac com\tutorialspoint\gui\SwingControlDemo.java

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

D:\SWING>java com.tutorialspoint.gui.SwingControlDemo

Verify the following output

Swing JTextField

Swing JPasswordField Class

Introduction

The class JPasswordField is a component which is specialized to handle password functionality and allows the editing of a single line of text.

Class declaration

Following is the declaration for javax.swing.JPasswordField class:

public class JPasswordField
   extends JTextField

Field

Class constructors

S.N.Constructor & Description
1JPasswordField()
Constructs a new JPasswordField, with a default document, null starting text string, and 0 column width.
2JPasswordField(Document doc, String txt, int columns)
Constructs a new JPasswordField that uses the given text storage model and the given number of columns.
3JPasswordField(int columns)
Constructs a new empty JPasswordField with the specified number of columns.
4JPasswordField(String text)
Constructs a new JPasswordField initialized with the specified text.
5JPasswordField(String text, int columns)
Constructs a new JPasswordField initialized with the specified text and columns.

Class methods

S.N.Method & Description
1void copy()
Invokes provideErrorFeedback on the current look and feel, which typically initiates an error beep.
2void cut()
Invokes provideErrorFeedback on the current look and feel, which typically initiates an error beep.
3boolean echoCharIsSet()
Returns true if this JPasswordField has a character set for echoing.
4AccessibleContext getAccessibleContext()
Returns the AccessibleContext associated with this JPasswordField.
5char getEchoChar()
Returns the character to be used for echoing.
6char[] getPassword()
Returns the text contained in this TextComponent.
7String getText()
Deprecated. As of Java 2 platform v1.2, replaced by getPassword.
8String getText(int offs, int len)
Deprecated. As of Java 2 platform v1.2, replaced by getPassword.
9String getUIClassID()
Returns the name of the L&F class that renders this component.
10protected String paramString()
Returns a string representation of this JPasswordField.
11void setEchoChar(char c)
Sets the echo character for this JPasswordField.
12void updateUI()
Reloads the pluggable UI.

Methods inherited

This class inherits methods from the following classes:

  • javax.swing.JTextField

  • javax.swing.text.JTextComponent

  • javax.swing.JComponent

  • java.awt.Container

  • java.awt.Component

  • java.lang.Object

JPasswordField Example

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

SwingControlDemo.java
package com.tutorialspoint.gui;
 
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
 
public class SwingControlDemo {
    
   private JFrame mainFrame;
   private JLabel headerLabel;
   private JLabel statusLabel;
   private JPanel controlPanel;

   public SwingControlDemo(){
      prepareGUI();
   }

   public static void main(String[] args){
      SwingControlDemo  swingControlDemo = new SwingControlDemo();      
      swingControlDemo.showPasswordFieldDemo();
   }

   private void prepareGUI(){
      mainFrame = new JFrame("Java Swing 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 JLabel("", JLabel.CENTER);        
      statusLabel = new JLabel("",JLabel.CENTER);    

      statusLabel.setSize(350,100);

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

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

   private void showPasswordFieldDemo(){
      headerLabel.setText("Control in action: JPasswordField"); 

      JLabel  namelabel= new JLabel("User ID: ", JLabel.RIGHT);
      JLabel  passwordLabel = new JLabel("Password: ", JLabel.CENTER);
      final JTextField userText = new JTextField(6);
      final JPasswordField passwordText = new JPasswordField(6);      
      passwordText.setEchoChar('~');
	  
      JButton loginButton = new JButton("Login");
      loginButton.addActionListener(new ActionListener() {
         public void actionPerformed(ActionEvent e) {     
            String data = "Username " + userText.getText();
            data += ", Password: " 
            + new String(passwordText.getPassword()); 
            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:/ > SWING and type the following command.

D:\SWING>javac com\tutorialspoint\gui\SwingControlDemo.java

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

D:\SWING>java com.tutorialspoint.gui.SwingControlDemo

Verify the following output

Swing JPasswordField

Swing JTextArea Class

Introduction

The class JTextArea is a multi-line area to display plain text.

Class declaration

Following is the declaration for javax.swing.JTextArea class:

public class JTextArea
   extends JTextComponent

Class constructors

S.N.Constructor & Description
1JTextArea()
Constructs a new TextArea.
2JTextArea(Document doc)
Constructs a new JTextArea with the given document model, and defaults for all of the other arguments (null, 0, 0).
3JTextArea(Document doc, String text, int rows, int columns)
Constructs a new JTextArea with the specified number of rows and columns, and the given model.
4JTextArea(int rows, int columns)
Constructs a new empty TextArea with the specified number of rows and columns.
5JTextArea(String text)
Constructs a new TextArea with the specified text displayed.
6JTextArea(String text, int rows, int columns)
Constructs a new TextArea with the specified text and number of rows and columns.

Class methods

S.N.Method & Description
1void append(String str)
Appends the given text to the end of the document.
2protected Document createDefaultModel()
Creates the default implementation of the model to be used at construction if one isn't explicitly given.
3AccessibleContext getAccessibleContext()
Gets the AccessibleContext associated with this JTextArea.
4int getColumns()
Returns the number of columns in the TextArea.
5protected int getColumnWidth()
Gets column width.
6int getLineCount()
Determines the number of lines contained in the area.
7int getLineEndOffset(int line)
Determines the offset of the end of the given line.
8int getLineOfOffset(int offset)
Translates an offset into the components text to a line number.
9int getLineStartOffset(int line)
Determines the offset of the start of the given line.
10boolean getLineWrap()
Gets the line-wrapping policy of the text area.
11Dimension getPreferredScrollableViewportSize()
Returns the preferred size of the viewport if this component is embedded in a JScrollPane.
12Dimension getPreferredSize()
Returns the preferred size of the TextArea.
13protected int getRowHeight()
Defines the meaning of the height of a row.
14int getRows()
Returns the number of rows in the TextArea.
15boolean getScrollableTracksViewportWidth()
Returns true if a viewport should always force the width of this Scrollable to match the width of the viewport.
16int getScrollableUnitIncrement(Rectangle visibleRect, int orientation, int direction)
Components that display logical rows or columns should compute the scroll increment that will completely expose one new row or column, depending on the value of orientation.
17int getTabSize()
Gets the number of characters used to expand tabs.
18String getUIClassID()
Returns the class ID for the UI.
19boolean getWrapStyleWord()
Gets the style of wrapping used if the text area is wrapping lines.
20void insert(String str, int pos)
Inserts the specified text at the specified position.
21protected String paramString()
Returns a string representation of this JTextArea.
22void replaceRange(String str, int start, int end)
Replaces text from the indicated start to end position with the new text specified.
23void setColumns(int columns)
Sets the number of columns for this TextArea.
24void setFont(Font f)
Sets the current font.
25void setLineWrap(boolean wrap)
Sets the line-wrapping policy of the text area.
26void setRows(int rows)
Sets the number of rows for this TextArea.
27void setTabSize(int size)
Sets the number of characters to expand tabs to.
28void setWrapStyleWord(boolean word)
Sets the style of wrapping used if the text area is wrapping lines.

Methods inherited

This class inherits methods from the following classes:

  • javax.swing.text.JTextComponent

  • javax.swing.JComponent

  • java.awt.Container

  • java.awt.Component

  • java.lang.Object

JTextArea Example

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

SwingControlDemo.java
package com.tutorialspoint.gui;
 
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
 
public class SwingControlDemo {
    
   private JFrame mainFrame;
   private JLabel headerLabel;
   private JLabel statusLabel;
   private JPanel controlPanel;

   public SwingControlDemo(){
      prepareGUI();
   }

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

   private void prepareGUI(){
      mainFrame = new JFrame("Java Swing 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 JLabel("", JLabel.CENTER);        
      statusLabel = new JLabel("",JLabel.CENTER);    

      statusLabel.setSize(350,100);

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

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

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

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

      final JTextArea commentTextArea = 
         new JTextArea("This is a Swing tutorial "
         +"to make GUI application in Java.",5,20);

      JScrollPane scrollPane = new JScrollPane(commentTextArea);    

      JButton showButton = new JButton("Show");

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

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

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

D:\SWING>javac com\tutorialspoint\gui\SwingControlDemo.java

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

D:\SWING>java com.tutorialspoint.gui.SwingControlDemo

Verify the following output

Swing JTextArea

Swing ImageIcon Class

Introduction

The class ImageIcon is an implementation of the Icon interface that paints Icons from Images.

Class declaration

Following is the declaration for javax.swing.ImageIcon class:

public class ImageIcon
   extends Object
      implements Icon, Serializable, Accessible

Field

Following are the fields for javax.swing.ImageIcon class:

  • protected static Component component

  • protected static MediaTracker tracker

Class constructors

S.N.Constructor & Description
1ImageIcon()
Creates an uninitialized image icon.
2ImageIcon(byte[] imageData)
Creates an ImageIcon from an array of bytes which were read from an image file containing a supported image format, such as GIF, JPEG, or (as of 1.3) PNG.
3ImageIcon(byte[] imageData, String description)
Creates an ImageIcon from an array of bytes which were read from an image file containing a supported image format, such as GIF, JPEG, or (as of 1.3) PNG.
4ImageIcon(Image image)
Creates an ImageIcon from an image object.
5ImageIcon(Image image, String description)
Creates an ImageIcon from the image.
6ImageIcon(String filename)
Creates an ImageIcon from the specified file.
7ImageIcon(String filename, String description)
Creates an ImageIcon from the specified file.
8ImageIcon(URL location)
Creates an ImageIcon from the specified URL.
9ImageIcon(URL location, String description)
Creates an ImageIcon from the specified URL.

Class methods

S.N.Method & Description
1AccessibleContext getAccessibleContext()
Gets the AccessibleContext associated with this ImageIcon.
2String getDescription()
Gets the description of the image.
3int getIconHeight()
Gets the height of the icon.
4int getIconWidth()
Gets the width of the icon.
5Image getImage()
Returns this icon's Image.
6int getImageLoadStatus()
Returns the status of the image loading operation.
7ImageObserver getImageObserver()
Returns the image observer for the image.
8protected void loadImage(Image image)
Loads the image, returning only when the image is loaded.
9void paintIcon(Component c, Graphics g, int x, int y)
Paints the icon.
10void setDescription(String description)
Sets the description of the image.
11void setImage(Image image)
Sets the image displayed by this icon.
12void setImageObserver(ImageObserver observer)
Sets the image observer for the image.
13String toString()
Returns a string representation of this image.

Methods inherited

This class inherits methods from the following classes:

  • java.lang.Object

ImageIcon Example

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

SwingControlDemo.java
package com.tutorialspoint.gui;
 
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
 
public class SwingControlDemo {
    
   private JFrame mainFrame;
   private JLabel headerLabel;
   private JLabel statusLabel;
   private JPanel controlPanel;

   public SwingControlDemo(){
      prepareGUI();
   }

   public static void main(String[] args){
      SwingControlDemo  swingControlDemo = new SwingControlDemo();      
      swingControlDemo.showImageIconDemo();
   }

   private void prepareGUI(){
      mainFrame = new JFrame("Java Swing 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 JLabel("", JLabel.CENTER);        
      statusLabel = new JLabel("",JLabel.CENTER);    

      statusLabel.setSize(350,100);

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

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

   // Returns an ImageIcon, or null if the path was invalid. 
   private static ImageIcon createImageIcon(String path,
      String description) {
      java.net.URL imgURL = SwingControlDemo.class.getResource(path);
      if (imgURL != null) {
         return new ImageIcon(imgURL, description);
      } else {            
         System.err.println("Couldn't find file: " + path);
         return null;
      }
   }


   private void showImageIconDemo(){
      headerLabel.setText("Control in action: ImageIcon"); 
	  
      ImageIcon icon = createImageIcon("/resources/java_icon.png","Java");

      JLabel commentlabel = new JLabel("", icon,JLabel.CENTER);

      controlPanel.add(commentlabel);

      mainFrame.setVisible(true);  
   }
}

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

D:\SWING>javac com\tutorialspoint\gui\SwingControlDemo.java

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

D:\SWING>java com.tutorialspoint.gui.SwingControlDemo

Verify the following output

Swing ImageIcon

Swing JScrollBar Class

Introduction

The class JScrollBar is an implementation of scrollbar.

Class declaration

Following is the declaration for javax.swing.JScrollBar class:

public class JScrollBar
   extends JComponent
      implements Adjustable, Accessible

Field

Following are the fields for javax.swing.ImageIcon class:

  • protected int blockIncrement

  • protected BoundedRangeModel model -- The model that represents the scrollbar's minimum, maximum, extent (aka "visibleAmount") and current value.

  • protected int orientation

  • protected int unitIncrement

Class constructors

S.N.Constructor & Description
1JScrollBar()
Creates a vertical scrollbar with the initial values.
2JScrollBar(int orientation)
Creates a scrollbar with the specified orientation and the initial values.
3JScrollBar(int orientation, int value, int extent, int min, int max)
Creates a scrollbar with the specified orientation, value, extent, minimum, and maximum.

Class methods

S.N.Method & Description
1void addAdjustmentListener(AdjustmentListener l)
Adds an AdjustmentListener.
2protected void fireAdjustmentValueChanged(int id, int type, int value)
Notify listeners that the scrollbar's model has changed.
3AccessibleContext getAccessibleContext()
Gets the AccessibleContext associated with this JScrollBar.
4AdjustmentListener[] getAdjustmentListeners()
Returns an array of all the AdjustmentListeners added to this JScrollBar with addAdjustmentListener().
5int getBlockIncrement()
For backwards compatibility with java.awt.Scrollbar.
6int getBlockIncrement(int direction)
Returns the amount to change the scrollbar's value by, given a block (usually "page") up/down request.
7int getMaximum()
The maximum value of the scrollbar is maximum - extent.
8Dimension getMaximumSize()
The scrollbar is flexible along it's scrolling axis and rigid along the other axis.
9int getMinimum()
Returns the minimum value supported by the scrollbar (usually zero).
10Dimension getMinimumSize()
The scrollbar is flexible along it's scrolling axis and rigid along the other axis.
11BoundedRangeModel getModel()
Returns data model that handles the scrollbar's four fundamental properties: minimum, maximum, value, extent.
12int getOrientation()
Returns the component's orientation (horizontal or vertical).
13ScrollBarUI getUI()
Returns the delegate that implements the look and feel for this component.
14String getUIClassID()
Returns the name of the LookAndFeel class for this component.
15int getUnitIncrement()
For backwards compatibility with java.awt.Scrollbar.
16int getUnitIncrement(int direction)
Returns the amount to change the scrollbar's value by, given a unit up/down request.
17int getValue()
Returns the scrollbar's value.
18boolean getValueIsAdjusting()
True if the scrollbar knob is being dragged.
19int getVisibleAmount()
Returns the scrollbar's extent, aka its "visibleAmount".
20protected String paramString()
Returns a string representation of this JScrollBar.
21void removeAdjustmentListener(AdjustmentListener l)
Removes an AdjustmentEvent listener.
22void setBlockIncrement(int blockIncrement)
Sets the blockIncrement property.
23void setEnabled(boolean x)
Enables the component so that the knob position can be changed.
24void setMaximum(int maximum)
Sets the model's maximum property.
25void setMinimum(int minimum)
Sets the model's minimum property.
26void setModel(BoundedRangeModel newModel)
Sets the model that handles the scrollbar's four fundamental properties: minimum, maximum, value, extent.
27void setOrientation(int orientation)
Set the scrollbar's orientation to either VERTICAL or HORIZONTAL.
28void setUI(ScrollBarUI ui)
Sets the L&F object that renders this component.
29void setUnitIncrement(int unitIncrement)
Sets the unitIncrement property.
30void setValue(int value)
Sets the scrollbar's value.
31void setValueIsAdjusting(boolean b)
Sets the model's valueIsAdjusting property.
32void setValues(int newValue, int newExtent, int newMin, int newMax)
Sets the four BoundedRangeModel properties after forcing the arguments to obey the usual constraints.
33void setVisibleAmount(int extent)
Set the model's extent property.
34void updateUI()
Overrides JComponent.updateUI.

Methods inherited

This class inherits methods from the following classes:

  • java.lang.Object

JScrollBar Example

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

SwingControlDemo.java
package com.tutorialspoint.gui;
 
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
 
public class SwingControlDemo {
    
   private JFrame mainFrame;
   private JLabel headerLabel;
   private JLabel statusLabel;
   private JPanel controlPanel;

   public SwingControlDemo(){
      prepareGUI();
   }

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

   private void prepareGUI(){
      mainFrame = new JFrame("Java Swing 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 JLabel("", JLabel.CENTER);        
      statusLabel = new JLabel("",JLabel.CENTER);    

      statusLabel.setSize(350,100);

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

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

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

      final JScrollBar horizontalScroller = 
         new JScrollBar(JScrollBar.HORIZONTAL);
      final JScrollBar verticalScroller = new JScrollBar();
      verticalScroller.setOrientation(JScrollBar.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:/ > SWING and type the following command.

D:\SWING>javac com\tutorialspoint\gui\SwingControlDemo.java

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

D:\SWING>java com.tutorialspoint.gui.SwingControlDemo

Verify the following output

Swing JScrollbar

Swing JOptionPane Class

Introduction

The class JOptionPane is a component which provides standard methods to pop up a standard dialog box for a value or informs user of something.

Class declaration

Following is the declaration for javax.swing.JOptionPane class:

public class JOptionPane
   extends JComponent
      implements Accessible

Field

Following are the fields for javax.swing.JOptionPane class:

  • static int CANCEL_OPTION --Return value from class method if CANCEL is chosen.

  • static int CLOSED_OPTION --Return value from class method if user closes window without selecting anything, more than likely this should be treated as either a CANCEL_OPTION or NO_OPTION.

  • static int DEFAULT_OPTION --Type meaning Look and Feel should not supply any options -- only use the options from the JOptionPane.

  • static int ERROR_MESSAGE --Used for error messages.

  • protected Icon icon --Icon used in pane.

  • static string ICON_PROPERTY --Bound property name for icon.

  • static int INFORMATION_MESSAGE --Used for information messages.

  • static string INITIAL_SELECTION_VALUE_PROPERTY --Bound property name for initialSelectionValue.

  • static string INITIAL_VALUE_PROPERTY --Bound property name for initialValue.

  • protected Object initialSelectionValue --Initial value to select in selectionValues.

  • protected Object initialValue --Value that should be initially selected in options.

  • static string INPUT_VALUE_PROPERTY --Bound property name for inputValue.

  • protected Object inputValue --Value the user has input.

  • protected Object message --Message to display.

  • static string MESSAGE_PROPERTY --Bound property name for message.

  • static string MESSAGE_TYPE_PROPERTY --Bound property name for type.

  • protected int messageType --Message type.

  • static int NO_OPTION --Return value from class method if NO is chosen.

  • static int OK_CANCEL_OPTION --Type used for showConfirmDialog.

  • static int OK_OPTION --Return value form class method if OK is chosen.

  • static string OPTION_TYPE_PROPERTY --Bound property name for optionType.

  • protected Object[] options --Options to display to the user.

  • static string OPTIONS_PROPERTY --Bound property name for option.

  • protected int optionType --Option type, one of DEFAULT_OPTION, YES_NO_OPTION, YES_NO_CANCEL_OPTION or OK_CANCEL_OPTION.

  • static int PLAIN_MESSAGE --No icon is used.

  • static int QUESTION_MESSAGE --Used for questions.

  • static string SELECTION_VALUES_PROPERTY --Bound property name for selectionValues.

  • protected Object[] selectionValues --Array of values the user can choose from.

  • static Object UNINITIALIZED_VALUE --Indicates that the user has not yet selected a value.

  • protected Object value --Currently selected value, will be a valid option, or UNINITIALIZED_VALUE or null.

  • static string VALUE_PROPERTY --Bound property name for value.

  • static string WANTS_INPUT_PROPERTY --Bound property name for wantsInput.

  • protected boolean wantsInput --If true, a UI widget will be provided to the user to get input.

  • static int WARNING_MESSAGE --Used for warning messages.

  • static int YES_NO_CANCEL_OPTION --Type used for showConfirmDialog.

  • static int YES_NO_OPTION --Type used for showConfirmDialog.

  • static int YES_OPTION --Return value from class method if YES is chosen.

Class constructors

S.N.Constructor & Description
1JOptionPane()
Creates a JOptionPane with a test message.
2JOptionPane(Object message)
Creates a instance of JOptionPane to display a message using the plain-message message type and the default options delivered by the UI.
3JOptionPane(Object message, int messageType)
Creates an instance of JOptionPane to display a message with the specified message type and the default options
4JOptionPane(Object message, int messageType, int optionType)
Creates an instance of JOptionPane to display a message with the specified message type and options.
5JOptionPane(Object message, int messageType, int optionType, Icon icon)
Creates an instance of JOptionPane to display a message with the specified message type, options, and icon.
6JOptionPane(Object message, int messageType, int optionType, Icon icon, Object[] options)
Creates an instance of JOptionPane to display a message with the specified message type, icon, and options.
7JOptionPane(Object message, int messageType, int optionType, Icon icon, Object[] options, Object initialValue)
Creates an instance of JOptionPane to display a message with the specified message type, icon, and options, with the initially-selected option specified.

Class methods

S.N.Method & Description
1JDialog createDialog(Component parentComponent, String title)
Creates and returns a new JDialog wrapping this centered on the parentComponent in the parentComponent's frame.
2JDialog createDialog(String title)
Creates and returns a new parentless JDialog with the specified title.
3JInternalFrame createInternalFrame(Component parentComponent, String title)
Creates and returns an instance of JInternalFrame.
4AccessibleContext getAccessibleContext()
Returns the AccessibleContext associated with this JOptionPane.
5static JDesktopPane getDesktopPaneForComponent(Component parentComponent)
Returns the specified component's desktop pane.
6static Frame getFrameForComponent(Component parentComponent)
Returns the specified component's Frame.
7Icon getIcon()
Returns the icon this pane displays.
8Object getInitialSelectionValue()
Returns the input value that is displayed as initially selected to the user.
9Object getInitialValue()
Returns the initial value.
10Object getInputValue()
Returns the value the user has input, if wantsInput is true.
11int getMaxCharactersPerLineCount()
Returns the maximum number of characters to place on a line in a message.
12Object getMessage()
Returns the message-object this pane displays.
13int getMessageType()
Returns the message type.
14Object[] getOptions()
Returns the choices the user can make.
15int getOptionType()
Returns the type of options that are displayed.
16static Frame getRootFrame()
Returns the Frame to use for the class methods in which a frame is not provided.
17Object[] getSelectionValues()
Returns the input selection values.
18OptionPaneUI getUI()
Returns the UI object which implements the L&F for this component.
19String getUIClassID()
Returns the name of the UI class that implements the L&F for this component.
20Object getValue()
Returns the value the user has selected.
21boolean getWantsInput()
Returns the value of the wantsInput property.
22protected String paramString()
Returns a string representation of this JOptionPane.
23void selectInitialValue()
Requests that the initial value be selected, which will set focus to the initial value.
24void setIcon(Icon newIcon)
Sets the icon to display.
25void setInitialSelectionValue(Object newValue)
Sets the input value that is initially displayed as selected to the user.
26void setInitialValue(Object newInitialValue)
Sets the initial value that is to be enabled -- the Component that has the focus when the pane is initially displayed.
27void setInputValue(Object newValue)
Sets the input value that was selected or input by the user.
28void setMessage(Object newMessage)
Sets the option pane's message-object.
29void setMessageType(int newType)
Sets the option pane's message type.
30void setOptions(Object[] newOptions)
Sets the options this pane displays.
31void setOptionType(int newType)
Sets the options to display.
32static voidsetRootFrame(Frame newRootFrame)
Sets the frame to use for class methods in which a frame is not provided.
33void setSelectionValues(Object[] newValues)
Sets the input selection values for a pane that provides the user with a list of items to choose from.
34void setUI(OptionPaneUI ui)
Sets the UI object which implements the L&F for this component.
35void setValue(Object newValue)
Sets the value the user has chosen.
36void setWantsInput(boolean newValue)
Sets the wantsInput property.
37static int showConfirmDialog(Component parentComponent, Object message)
Brings up a dialog with the options Yes, No and Cancel; with the title, Select an Option.
38static int showConfirmDialog(Component parentComponent, Object message, String title, int optionType)
Brings up a dialog where the number of choices is determined by the optionType parameter.
39static int showConfirmDialog(Component parentComponent, Object message, String title, int optionType, int messageType)
Brings up a dialog where the number of choices is determined by the optionType parameter, where the messageType parameter determines the icon to display.
40static int showConfirmDialog(Component parentComponent, Object message, String title, int optionType, int messageType, Icon icon)
Brings up a dialog with a specified icon, where the number of choices is determined by the optionType parameter.
41static String showInputDialog(Component parentComponent, Object message)
Shows a question-message dialog requesting input from the user parented to parentComponent.
42static String showInputDialog(Component parentComponent, Object message, Object initialSelectionValue)
Shows a question-message dialog requesting input from the user and parented to parentComponent.
43static String showInputDialog(Component parentComponent, Object message, String title, int messageType)
Shows a dialog requesting input from the user parented to parentComponent with the dialog having the title title and message type messageType.
44static Object showInputDialog(Component parentComponent, Object message, String title, int messageType, Icon icon, Object[] selectionValues, Object initialSelectionValue)
Prompts the user for input in a blocking dialog where the initial selection, possible selections, and all other options can be specified.
45static String showInputDialog(Object message)
Shows a question-message dialog requesting input from the user.
46static String showInputDialog(Object message, Object initialSelectionValue)
Shows a question-message dialog requesting input from the user, with the input value initialized to initialSelectionValue.
47static int showInternalConfirmDialog(Component parentComponent, Object message)
Brings up an internal dialog panel with the options Yes, No and Cancel; with the title, Select an Option.
48static int showInternalConfirmDialog(Component parentComponent, Object message, String title, int optionType)
Brings up a internal dialog panel where the number of choices is determined by the optionType parameter.
49static int showInternalConfirmDialog(Component parentComponent, Object message, String title, int optionType, int messageType)
Brings up an internal dialog panel where the number of choices is determined by the optionType parameter, where the messageType parameter determines the icon to display.
50static int showInternalConfirmDialog(Component parentComponent, Object message, String title, int optionType, int messageType, Icon icon)
Brings up an internal dialog panel with a specified icon, where the number of choices is determined by the optionType parameter.
51static String showInternalInputDialog(Component parentComponent, Object message)
Shows an internal question-message dialog requesting input from the user parented to parentComponent.
52static String showInternalInputDialog(Component parentComponent, Object message, String title, int messageType)
Shows an internal dialog requesting input from the user parented to parentComponent with the dialog having the title title and message type messageType.
53static Object showInternalInputDialog(Component parentComponent, Object message, String title, int messageType, Icon icon, Object[] selectionValues, Object initialSelectionValue)
Prompts the user for input in a blocking internal dialog where the initial selection, possible selections, and all other options can be specified.
54static voidshowInternalMessageDialog(Component parentComponent, Object message)
Brings up an internal confirmation dialog panel.
55static voidshowInternalMessageDialog(Component parentComponent, Object message, String title, int messageType)
Brings up an internal dialog panel that displays a message using a default icon determined by the messageType parameter.
56static voidshowInternalMessageDialog(Component parentComponent, Object message, String title, int messageType, Icon icon)
Brings up an internal dialog panel displaying a message, specifying all parameters.
57static voidshowMessageDialog(Component parentComponent, Object message)
Brings up an information-message dialog titled "Message".
58static voidshowMessageDialog(Component parentComponent, Object message, String title, int messageType)
Brings up a dialog that displays a message using a default icon determined by the messageType parameter.
59static voidshowMessageDialog(Component parentComponent, Object message, String title, int messageType, Icon icon)
Brings up a dialog displaying a message, specifying all parameters.
60static int showOptionDialog(Component parentComponent, Object message, String title, int optionType, int messageType, Icon icon, Object[] options, Object initialValue)
Brings up a dialog with a specified icon, where the initial choice is determined by the initialValue parameter and the number of choices is determined by the optionType parameter.
61void updateUI()
Notification from the UIManager that the L&F has changed.
62static int showInternalOptionDialog(Component parentComponent, Object message, String title, int optionType, int messageType, Icon icon, Object[] options, Object initialValue)
Brings up an internal dialog panel with a specified icon, where the initial choice is determined by the initialValue parameter and the number of choices is determined by the optionType parameter.

Methods inherited

This class inherits methods from the following classes:

  • javax.swing.JComponent

  • java.awt.Container

  • java.awt.Component

  • java.lang.Object

JOptionPane Example

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

SwingControlDemo.java
package com.tutorialspoint.gui;
 
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
 
public class SwingControlDemo {
    
   private JFrame mainFrame;
   private JLabel headerLabel;
   private JLabel statusLabel;
   private JPanel controlPanel;

   public SwingControlDemo(){
      prepareGUI();
   }

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

   private void prepareGUI(){
      mainFrame = new JFrame("Java Swing 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 JLabel("", JLabel.CENTER);        
      statusLabel = new JLabel("",JLabel.CENTER);    

      statusLabel.setSize(350,100);

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

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

   private void showDialogDemo(){                                       
      headerLabel.setText("Control in action: JOptionPane"); 

      JButton okButton = new JButton("OK");        
      JButton javaButton = new JButton("Yes/No");
      JButton cancelButton = new JButton("Yes/No/Cancel");

      okButton.addActionListener(new ActionListener() {
         public void actionPerformed(ActionEvent e) {
            JOptionPane.showMessageDialog(
            mainFrame, "Welcome to TutorialsPoint.com");
         }          
      });

      javaButton.addActionListener(new ActionListener() {
         public void actionPerformed(ActionEvent e) {
            int output = JOptionPane.showConfirmDialog(mainFrame
               , "Click any button"
               ,"TutorialsPoint.com"
               ,JOptionPane.YES_NO_OPTION);

            if(output == JOptionPane.YES_OPTION){
               statusLabel.setText("Yes selected.");
            }else if(output == JOptionPane.NO_OPTION){
               statusLabel.setText("No selected.");
            }
         }
      });

      cancelButton.addActionListener(new ActionListener() {
         public void actionPerformed(ActionEvent e) {                
            int output = JOptionPane.showConfirmDialog(mainFrame
               , "Click any button"
               ,"TutorialsPoint.com"
               ,JOptionPane.YES_NO_CANCEL_OPTION,
               JOptionPane.INFORMATION_MESSAGE);

            if(output == JOptionPane.YES_OPTION){
               statusLabel.setText("Yes selected.");
            }else if(output == JOptionPane.NO_OPTION){
               statusLabel.setText("No selected.");
            }else if(output == JOptionPane.CANCEL_OPTION){
               statusLabel.setText("Cancel selected.");
            }
         }
      });

      controlPanel.add(okButton);
      controlPanel.add(javaButton);
      controlPanel.add(cancelButton);       
      mainFrame.setVisible(true);  
   }
}

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

D:\SWING>javac com\tutorialspoint\gui\SwingControlDemo.java

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

D:\SWING>java com.tutorialspoint.gui.SwingControlDemo

Verify the following output

Swing JOptionPane

Swing JFileChooser Class

Introduction

The class JFileChooser is a component which provides a simple mechanism for the user to choose a file.

Class declaration

Following is the declaration for javax.swing.JFileChooser class:

public class JFileChooser
   extends JComponent
      implements Accessible

Field

Following are the fields for javax.swing.JFileChooser class:

  • static String ACCEPT_ALL_FILE_FILTER_USED_CHANGED_PROPERTY --Identifies whether a the AcceptAllFileFilter is used or not.

  • protected AccessibleContext accessibleContext

  • static String ACCESSORY_CHANGED_PROPERTY --Says that a different accessory component is in use (for example, to preview files).

  • static String APPROVE_BUTTON_MNEMONIC_CHANGED_PROPERTY --Identifies change in the mnemonic for the approve (yes, ok) button.

  • static String APPROVE_BUTTON_TEXT_CHANGED_PROPERTY --Identifies change in the text on the approve (yes, ok) button.

  • static String APPROVE_BUTTON_TOOL_TIP_TEXT_CHANGED_PROPERTY --Identifies change in the tooltip text for the approve (yes, ok) button.

  • static int APPROVE_OPTION --Return value if approve (yes, ok) is chosen.

  • static String APPROVE_SELECTION --Instruction to approve the current selection (same as pressing yes or ok).

  • static int CANCEL_OPTION --Return value if cancel is chosen.

  • static String CANCEL_SELECTION --Instruction to cancel the current selection.

  • static String CHOOSABLE_FILE_FILTER_CHANGED_PROPERTY --Identifies a change in the list of predefined file filters the user can choose from.

  • static String CONTROL_BUTTONS_ARE_SHOWN_CHANGED_PROPERTY --Instruction to display the control buttons.

  • static int CUSTOM_DIALOG --Type value indicating that the JFileChooser supports a developer-specified file operation.

  • static String DIALOG_TITLE_CHANGED_PROPERTY --Identifies a change in the dialog title.

  • static String DIALOG_TYPE_CHANGED_PROPERTY --Identifies a change in the type of files displayed (files only, directories only, or both files and directories).

  • static int DIRECTORIES_ONLY --Instruction to display only directories.

  • static String DIRECTORY_CHANGED_PROPERTY --Identifies user's directory change.

  • static int ERROR_OPTION --Return value if an error occured.

  • static String FILE_FILTER_CHANGED_PROPERTY --User changed the kind of files to display.

  • static String FILE_HIDING_CHANGED_PROPERTY --Identifies a change in the display-hidden-files property.

  • static String FILE_SELECTION_MODE_CHANGED_PROPERTY --Identifies a change in the kind of selection (single, multiple, etc.).

  • static String FILE_SYSTEM_VIEW_CHANGED_PROPERTY --Says that a different object is being used to find available drives on the system.

  • static String FILE_VIEW_CHANGED_PROPERTY --Says that a different object is being used to retrieve file information.

  • static int FILES_AND_DIRECTORIES --Instruction to display both files and directories.

  • static int FILES_ONLY --Instruction to display only files.

  • static String MULTI_SELECTION_ENABLED_CHANGED_PROPERTY --Enables multiple-file selections.

  • static int OPEN_DIALOG --Type value indicating that the JFileChooser supports an "Open" file operation.

  • static int SAVE_DIALOG --Type value indicating that the JFileChooser supports a "Save" file operation.

  • static String SELECTED_FILE_CHANGED_PROPERTY --Identifies change in user's single-file selection.

  • static String SELECTED_FILES_CHANGED_PROPERTY --Identifies change in user's multiple-file selection.

Class constructors

S.N.Constructor & Description
1JFileChooser()
Constructs a JFileChooser pointing to the user's default directory.
2JFileChooser(File currentDirectory)
Constructs a JFileChooser using the given File as the path.
3JFileChooser(File currentDirectory, FileSystemView fsv)
Constructs a JFileChooser using the given current directory and FileSystemView.
4JFileChooser(FileSystemView fsv)
Constructs a JFileChooser using the given FileSystemView.
5JFileChooser(String currentDirectoryPath)
Constructs a JFileChooser using the given path.
6JFileChooser(String currentDirectoryPath, FileSystemView fsv)
Constructs a JFileChooser using the given current directory path and FileSystemView.

Class methods

S.N.Method & Description
1boolean accept(File f)
Returns true if the file should be displayed.
2void addActionListener(ActionListener l)
Adds an ActionListener to the file chooser.
3void addChoosableFileFilter(FileFilter filter)
Adds a filter to the list of user choosable file filters.
4void approveSelection()
Called by the UI when the user hits the Approve button (labeled "Open" or "Save", by default).
5void cancelSelection()
Called by the UI when the user chooses the Cancel button.
6void changeToParentDirectory()
Changes the directory to be set to the parent of the current directory.
7protected JDialog createDialog(Component parent)
Creates and returns a new JDialog wrapping this centered on the parent in the parent's frame.
8void ensureFileIsVisible(File f)
Makes sure that the specified file is viewable, and not hidden.
9protected void fireActionPerformed(String command)
Notifies all listeners that have registered interest for notification on this event type.
10FileFilter getAcceptAllFileFilter()
Returns the AcceptAll file filter.
11AccessibleContext getAccessibleContext()
Gets the AccessibleContext associated with this JFileChooser.
12JComponent getAccessory()
Returns the accessory component.
13ActionListener[] getActionListeners()
Returns an array of all the action listeners registered on this file chooser.
14int getApproveButtonMnemonic()
Returns the approve button's mnemonic.
15String getApproveButtonText()
Returns the text used in the ApproveButton in the FileChooserUI.
16String getApproveButtonToolTipText()
Returns the tooltip text used in the ApproveButton.
17FileFilter[] getChoosableFileFilters()
Gets the list of user choosable file filters.
18boolean getControlButtonsAreShown()
Returns the value of the controlButtonsAreShown property.
19File getCurrentDirectory()
Returns the current directory.
20String getDescription(File f)
Returns the file description.
21String getDialogTitle()
Gets the string that goes in the JFileChooser's titlebar.
22int getDialogType()
Returns the type of this dialog.
23boolean getDragEnabled()
Gets the value of the dragEnabled property.
24FileFilter getFileFilter()
Returns the currently selected file filter.
25int getFileSelectionMode()
Returns the current file-selection mode.
26FileSystemView getFileSystemView()
Returns the file system view.
27FileView getFileView()
Returns the current file view.
28Icon getIcon(File f)
Returns the icon for this file or type of file, depending on the system.
29String getName(File f)
Returns the filename.
30File getSelectedFile()
Returns the selected file.
31File[] getSelectedFiles()
Returns a list of selected files if the file chooser is set to allow multiple selection.
32String getTypeDescription(File f)
Returns the file type.
33FileChooserUI getUI()
Gets the UI object which implements the L&F for this component.
34String getUIClassID()
Returns a string that specifies the name of the L&F class that renders this component.
35boolean isAcceptAllFileFilterUsed()
Returns whether the AcceptAll FileFilter is used.
36boolean isDirectorySelectionEnabled()
Convenience call that determines if directories are selectable based on the current file selection mode.
37boolean isFileHidingEnabled()
Returns true if hidden files are not shown in the file chooser; otherwise, returns false.
38boolean isFileSelectionEnabled()
Convenience call that determines if files are selectable based on the current file selection mode.
39boolean isMultiSelectionEnabled()
Returns true if multiple files can be selected.
40boolean isTraversable(File f)
Returns true if the file (directory) can be visited.
41protected String paramString()
Returns a string representation of this JFileChooser.
42void removeActionListener(ActionListener l)
Removes an ActionListener from the file chooser.
43boolean removeChoosableFileFilter(FileFilter f)
Removes a filter from the list of user choosable file filters.
44void rescanCurrentDirectory()
Tells the UI to rescan its files list from the current directory.
45void resetChoosableFileFilters()
Resets the choosable file filter list to its starting state.
46void setAcceptAllFileFilterUsed(boolean b)
Determines whether the AcceptAll FileFilter is used as an available choice in the choosable filter list.
47void setAccessory(JComponent newAccessory)
Sets the accessory component.
48void setApproveButtonMnemonic(char mnemonic)
Sets the approve button's mnemonic using a character.
49void setApproveButtonMnemonic(int mnemonic)
Sets the approve button's mnemonic using a numeric keycode.
50void setApproveButtonText(String approveButtonText)
Sets the text used in the ApproveButton in the FileChooserUI.
51void setApproveButtonToolTipText(String toolTipText)
Sets the tooltip text used in the ApproveButton.
52void setControlButtonsAreShown(boolean b)
Sets the property that indicates whether the approve and cancel buttons are shown in the file chooser.
53void setCurrentDirectory(File dir)
Sets the current directory.
54void setDialogTitle(String dialogTitle)
Sets the string that goes in the JFileChooser window's title bar.
55void setDialogType(int dialogType)
Sets the type of this dialog.
56void setDragEnabled(boolean b)
Sets the dragEnabled property, which must be true to enable automatic drag handling (the first part of drag and drop) on this component.
57void setFileFilter(FileFilter filter)
Sets the current file filter.
58void setFileHidingEnabled(boolean b)
Sets file hiding on or off.
59void setFileSelectionMode(int mode)
Sets the JFileChooser to allow the user to just select files, just select directories, or select both files and directories.
60void setFileSystemView(FileSystemView fsv)
Sets the file system view that the JFileChooser uses for accessing and creating file system resources, such as finding the floppy drive and getting a list of root drives.
61void setFileView(FileView fileView)
Sets the file view to used to retrieve UI information, such as the icon that represents a file or the type description of a file.
62void setMultiSelectionEnabled(boolean b)
Sets the file chooser to allow multiple file selections.
63void setSelectedFile(File file)
Sets the selected file.
64void setSelectedFiles(File[] selectedFiles)
Sets the list of selected files if the file chooser is set to allow multiple selection.
65protected void setup(FileSystemView view)
Performs common constructor initialization and setup.
66int showDialog(Component parent, String approveButtonText)
Pops a custom file chooser dialog with a custom approve button.
67int showOpenDialog(Component parent)
Pops up an "Open File" file chooser dialog.
68int showSaveDialog(Component parent)
Pops up a "Save File" file chooser dialog.
69void updateUI()
Resets the UI property to a value from the current look and feel.

Methods inherited

This class inherits methods from the following classes:

  • javax.swing.JComponent

  • java.awt.Container

  • java.awt.Component

  • java.lang.Object

JFileChooser Example

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

SwingControlDemo.java
package com.tutorialspoint.gui;
 
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
 
public class SwingControlDemo {
    
   private JFrame mainFrame;
   private JLabel headerLabel;
   private JLabel statusLabel;
   private JPanel controlPanel;

   public SwingControlDemo(){
      prepareGUI();
   }

   public static void main(String[] args){
      SwingControlDemo  swingControlDemo = new SwingControlDemo();      
      swingControlDemo.showFileChooserDemo();
   }

   private void prepareGUI(){
      mainFrame = new JFrame("Java Swing 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 JLabel("", JLabel.CENTER);        
      statusLabel = new JLabel("",JLabel.CENTER);    

      statusLabel.setSize(350,100);

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

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

   private void showFileChooserDemo(){
      headerLabel.setText("Control in action: JFileChooser"); 

      final JFileChooser  fileDialog = new JFileChooser();
      JButton showFileDialogButton = new JButton("Open File");
      showFileDialogButton.addActionListener(new ActionListener() {
         @Override
         public void actionPerformed(ActionEvent e) {
            int returnVal = fileDialog.showOpenDialog(mainFrame);
            if (returnVal == JFileChooser.APPROVE_OPTION) {
               java.io.File file = fileDialog.getSelectedFile();
               statusLabel.setText("File Selected :" 
               + file.getName());
            }
            else{
               statusLabel.setText("Open command cancelled by user." );           
            }      
         }
      });
      controlPanel.add(showFileDialogButton);
      mainFrame.setVisible(true);  
   }
}

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

D:\SWING>javac com\tutorialspoint\gui\SwingControlDemo.java

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

D:\SWING>java com.tutorialspoint.gui.SwingControlDemo

Verify the following output

Swing JFileChooser

Swing JProgressBar Class

Introduction

The class JProgressBar is a component which visually displays the progress of some task.

Class declaration

Following is the declaration for javax.swing.JProgressBar class:

public class JProgressBar
   extends JComponent
      implements SwingConstants, Accessible

Field

Following are the fields for javax.swing.JProgressBar class:

  • protected ChangeEvent changeEvent --Only one ChangeEvent is needed per instance since the event's only interesting property is the immutable source, which is the progress bar.

  • protected ChangeListener changeListener --Listens for change events sent by the progress bar's model, redispatching them to change-event listeners registered upon this progress bar.

  • protected BoundedRangeModel model --The object that holds the data for the progress bar.

  • protected int orientation --Whether the progress bar is horizontal or vertical.

  • protected boolean paintBorder --Whether to display a border around the progress bar.

  • protected boolean paintString --Whether to display a string of text on the progress bar.

  • protected String progressString --An optional string that can be displayed on the progress bar.

Class constructors

S.N.Constructor & Description
1JProgressBar()
Creates a horizontal progress bar that displays a border but no progress string.
2JProgressBar(BoundedRangeModel newModel)
Creates a horizontal progress bar that uses the specified model to hold the progress bar's data.
3JProgressBar(int orient)
Creates a progress bar with the specified orientation, which can be either SwingConstants.VERTICAL or SwingConstants.HORIZONTAL.
4JProgressBar(int min, int max)
Creates a horizontal progress bar with the specified minimum and maximum.
5JProgressBar(int orient, int min, int max)
Creates a progress bar using the specified orientation, minimum, and maximum.

Class methods

S.N.Method & Description
1void addChangeListener(ChangeListener l)
Adds the specified ChangeListener to the progress bar.
2protected ChangeListener createChangeListener()
Subclasses that want to handle change events from the model differently can override this to return an instance of a custom ChangeListener implementation.
3protected void fireStateChanged()
Send a ChangeEvent, whose source is this JProgressBar, to all ChangeListeners that have registered interest in ChangeEvents.
4AccessibleContext getAccessibleContext()
Gets the AccessibleContext associated with this JProgressBar.
5ChangeListener[] getChangeListeners()
Returns an array of all the ChangeListeners added to this progress bar with addChangeListener.
6int getMaximum()
Returns the progress bar's maximum value from the BoundedRangeModel.
7int getMinimum()
Returns the progress bar's minimum value from the BoundedRangeModel.
8BoundedRangeModel getModel()
Returns the data model used by this progress bar.
9int getOrientation()
Returns SwingConstants.VERTICAL or SwingConstants.HORIZONTAL, depending on the orientation of the progress bar.
10double getPercentComplete()
Returns the percent complete for the progress bar.
11String getString()
Returns a String representation of the current progress.
12ProgressBarUI getUI()
Returns the look-and-feel object that renders this component.
13String getUIClassID()
Returns the name of the look-and-feel class that renders this component.
14int getValue()
Returns the progress bar's current value from the BoundedRangeModel.
15boolean isBorderPainted()
Returns the borderPainted property.
16boolean isIndeterminate()
Returns the value of the indeterminate property.
17boolean isStringPainted()
Returns the value of the stringPainted property.
18protected void paintBorder(Graphics g)
Paints the progress bar's border if the borderPainted property is true.
19protected String paramString()
Returns a string representation of this JProgressBar.
20void removeChangeListener(ChangeListener l)
Removes a ChangeListener from the progress bar.
21void setBorderPainted(boolean b)
Sets the borderPainted property, which is true if the progress bar should paint its border.
22void setIndeterminate(boolean newValue)
Sets the indeterminate property of the progress bar, which determines whether the progress bar is in determinate or indeterminate mode.
23void setMaximum(int n)
Sets the progress bar's maximum value (stored in the progress bar's data model) to n.
24void setMinimum(int n)
Sets the progress bar's minimum value (stored in the progress bar's data model) to n.
25void setModel(BoundedRangeModel newModel)
Sets the data model used by the JProgressBar.
26void setOrientation(int newOrientation)
Sets the progress bar's orientation to newOrientation, which must be SwingConstants.VERTICAL or SwingConstants.HORIZONTAL.
27void setString(String s)
Sets the value of the progress string.
28void setStringPainted(boolean b)
Sets the value of the stringPainted property, which determines whether the progress bar should render a progress string.
29void setUI(ProgressBarUI ui)
Sets the look-and-feel object that renders this component.
30void setValue(int n)
Sets the progress bar's current value to n.
31void updateUI()
Resets the UI property to a value from the current look and feel.

Methods inherited

This class inherits methods from the following classes:

  • javax.swing.JComponent

  • java.awt.Container

  • java.awt.Component

  • java.lang.Object

JProgressBar Example

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

SwingControlDemo.java
package com.tutorialspoint.gui;
 
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
 
public class SwingControlDemo {
    
   private JFrame mainFrame;
   private JLabel headerLabel;
   private JLabel statusLabel;
   private JPanel controlPanel;

   public SwingControlDemo(){
      prepareGUI();
   }

   public static void main(String[] args){
      SwingControlDemo  swingControlDemo = new SwingControlDemo();      
      swingControlDemo.showProgressBarDemo();
   }

   private void prepareGUI(){
      mainFrame = new JFrame("Java Swing 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 JLabel("", JLabel.CENTER);        
      statusLabel = new JLabel("",JLabel.CENTER);    

      statusLabel.setSize(350,100);

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

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

   private JProgressBar progressBar;
   private Task task;
   private JButton startButton;
   private JTextArea outputTextArea;
   
   private void showProgressBarDemo(){
      headerLabel.setText("Control in action: JProgressBar"); 

      progressBar = new JProgressBar(0, 100);
      progressBar.setValue(0);
      progressBar.setStringPainted(true);
      startButton = new JButton("Start");

      outputTextArea = new JTextArea("",5,20);

      JScrollPane scrollPane = new JScrollPane(outputTextArea);    
         startButton.addActionListener(new ActionListener() {
         @Override
         public void actionPerformed(ActionEvent e) {
            task = new Task();                
            task.start();
         }});

      controlPanel.add(startButton);
      controlPanel.add(progressBar);
      controlPanel.add(scrollPane);
      mainFrame.setVisible(true);  
   }

   private class Task extends Thread {    
      public Task(){
      }

      public void run(){
         for(int i =0; i<= 100; i+=10){
            final int progress = i;
            SwingUtilities.invokeLater(new Runnable() {
               public void run() {
                  progressBar.setValue(progress);
                  outputTextArea.setText(outputTextArea.getText() 
                  + String.format("Completed %d%% of task.\n", progress));
               }
            });
            try {
               Thread.sleep(100);
            } catch (InterruptedException e) {}
         }
      }
   }   
}

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

D:\SWING>javac com\tutorialspoint\gui\SwingControlDemo.java

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

D:\SWING>java com.tutorialspoint.gui.SwingControlDemo

Verify the following output

Swing JProgressBar

Swing JSlider Class

Introduction

The class JSlider is a component which lets the user graphically select a value by sliding a knob within a bounded interval.

Class declaration

Following is the declaration for javax.swing.JSlider class:

public class JSlider
   extends JComponent
      implements SwingConstants, Accessible

Field

Following are the fields for javax.swing.JSlider class:

  • protected ChangeEvent changeEvent --Only one ChangeEvent is needed per slider instance since the event's only (read-only) state is the source property.

  • protected ChangeListener changeListener --The changeListener (no suffix) is the listener we add to the slider's model.

  • protected int majorTickSpacing --The number of values between the major tick marks -- the larger marks that break up the minor tick marks.

  • protected int minorTickSpacing --The number of values between the minor tick marks -- the smaller marks that occur between the major tick marks.

  • protected int orientation --Whether the slider is horizontal or vertical The default is horizontal.

  • protected BoundedRangeModel sliderModel -- The data model that handles the numeric maximum value, minimum value, and current-position value for the slider.

  • protected boolean snapToTicks --If true, the knob (and the data value it represents) resolve to the closest tick mark next to where the user positioned the knob.

Class constructors

S.N.Constructor & Description
1JSlider()
Creates a horizontal slider with the range 0 to 100 and an initial value of 50.
2JSlider(BoundedRangeModel brm)
Creates a horizontal slider using the specified BoundedRangeModel.
3JSlider(int orientation)
Creates a slider using the specified orientation with the range 0 to 100 and an initial value of 50.
4JSlider(int min, int max)
Creates a horizontal slider using the specified min and max with an initial value equal to the average of the min plus max.
5JSlider(int min, int max, int value)
Creates a horizontal slider using the specified min, max and value.
6JSlider(int orientation, int min, int max, int value)
Creates a slider with the specified orientation and the specified minimum, maximum, and initial values.

Class methods

S.N.Method & Description
1void addChangeListener(ChangeListener l)
Adds a ChangeListener to the slider.
2protected ChangeListener createChangeListener()
Subclasses that want to handle ChangeEvents from the model differently can override this to return an instance of a custom ChangeListener implementation.
3Hashtable createStandardLabels(int increment)
Creates a Hashtable of numerical text labels, starting at the slider minimum, and using the increment specified.
4Hashtable createStandardLabels(int increment, int start)
Creates a Hashtable of numerical text labels, starting at the starting point specified, and using the increment specified.
5protected void fireStateChanged()
Send a ChangeEvent, whose source is this JSlider, to all ChangeListeners that have registered interest in ChangeEvents.
6AccessibleContext getAccessibleContext()
Gets the AccessibleContext associated with this JSlider.
7ChangeListener[] getChangeListeners()
Returns an array of all the ChangeListeners added to this JSlider with addChangeListener().
8int getExtent()
Returns the "extent" from the BoundedRangeModel.
9boolean getInverted()
Returns true if the value-range shown for the slider is reversed.
10Dictionary getLabelTable()
Returns the dictionary of what labels to draw at which values.
11int getMajorTickSpacing()
This method returns the major tick spacing.
12int getMaximum()
Returns the maximum value supported by the slider from the BoundedRangeModel.
13int getMinimum()
Returns the minimum value supported by the slider from the BoundedRangeModel.
14int getMinorTickSpacing()
This method returns the minor tick spacing.
15BoundedRangeModel getModel()
Returns the BoundedRangeModel that handles the slider's three fundamental properties: minimum, maximum, value.
16int getOrientation()
Return this slider's vertical or horizontal orientation.
17boolean getPaintLabels()
Tells if labels are to be painted.
18boolean getPaintTicks()
Tells if tick marks are to be painted.
19boolean getPaintTrack()
Tells if the track (area the slider slides in) is to be painted.
20boolean getSnapToTicks()
Returns true if the knob (and the data value it represents) resolve to the closest tick mark next to where the user positioned the knob.
21SliderUI getUI()
Gets the UI object which implements the L&F for this component.
22String getUIClassID()
Returns the name of the L&F class that renders this component.
23int getValue()
Returns the slider's current value from the BoundedRangeModel.
24boolean getValueIsAdjusting()
Returns the valueIsAdjusting property from the model.
25protected String paramString()
Returns a string representation of this JSlider.
26void removeChangeListener(ChangeListener l)
Removes a ChangeListener from the slider.
27void setExtent(int extent)
Sets the size of the range "covered" by the knob.
28void setFont(Font font)
Sets the font for this component.
29void setInverted(boolean b)
Specify true to reverse the value-range shown for the slider and false to put the value range in the normal order.
30void setLabelTable(Dictionary labels)
Used to specify what label will be drawn at any given value.
31void setMajorTickSpacing(int n)
This method sets the major tick spacing.
32void setMaximum(int maximum)
Sets the slider's maximum value to maximum.
33void setMinimum(int minimum)
Sets the slider's minimum value to minimum.
34void setMinorTickSpacing(int n)
This method sets the minor tick spacing.
35void setModel(BoundedRangeModel newModel)
Sets the BoundedRangeModel that handles the slider's three fundamental properties: minimum, maximum, value.
36void setOrientation(int orientation)
Set the slider's orientation to either SwingConstants.VERTICAL or SwingConstants.HORIZONTAL.
37void setPaintLabels(boolean b)
Determines whether labels are painted on the slider.
38void setPaintTicks(boolean b)
Determines whether tick marks are painted on the slider.
39void setPaintTrack(boolean b)
Determines whether the track is painted on the slider.
40void setSnapToTicks(boolean b)
Specifying true makes the knob (and the data value it represents) resolve to the closest tick mark next to where the user positioned the knob.
41void setUI(SliderUI ui)
Sets the UI object which implements the L&F for this component.
42void setValue(int n) Sets the slider's current value to n.
43void setValueIsAdjusting(boolean b)
Sets the model's valueIsAdjusting property.
44protected void updateLabelUIs()
Updates the UIs for the labels in the label table by calling updateUI on each label.
45void updateUI()
Resets the UI property to a value from the current look and feel.

Methods inherited

This class inherits methods from the following classes:

  • javax.swing.JComponent

  • java.awt.Container

  • java.awt.Component

  • java.lang.Object

JSlider Example

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

SwingControlDemo.java
package com.tutorialspoint.gui;
 
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.event.*;

public class SwingControlDemo {
    
   private JFrame mainFrame;
   private JLabel headerLabel;
   private JLabel statusLabel;
   private JPanel controlPanel;

   public SwingControlDemo(){
      prepareGUI();
   }

   public static void main(String[] args){
      SwingControlDemo  swingControlDemo = new SwingControlDemo();      
      swingControlDemo.showSliderDemo();
   }

   private void prepareGUI(){
      mainFrame = new JFrame("Java Swing 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 JLabel("", JLabel.CENTER);        
      statusLabel = new JLabel("",JLabel.CENTER);    

      statusLabel.setSize(350,100);

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

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

   private void showSliderDemo(){
      headerLabel.setText("Control in action: JSlider"); 
      JSlider slider= new JSlider(JSlider.HORIZONTAL,0,100,10);
      slider.addChangeListener(new ChangeListener() {
         public void stateChanged(ChangeEvent e) {
            statusLabel.setText("Value : " 
            + ((JSlider)e.getSource()).getValue());
         }
      });
      controlPanel.add(slider);      
      mainFrame.setVisible(true);     
   } 
}

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

D:\SWING>javac com\tutorialspoint\gui\SwingControlDemo.java

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

D:\SWING>java com.tutorialspoint.gui.SwingControlDemo

Verify the following output

Swing JSlider

Swing JSpinner Class

Introduction

The class JSpinner is a component which lets the user select a number or an object value from an ordered sequence using an input field.

Class declaration

Following is the declaration for javax.swing.JSpinner class:

public class JSpinner
   extends JComponent
      implements Accessible

Class constructors

S.N.Constructor & Description
1JSpinner()
Constructs a spinner with an Integer SpinnerNumberModel with initial value 0 and no minimum or maximum limits.
2JSpinner(SpinnerModel model)
Constructs a complete spinner with pair of next/previous buttons and an editor for the SpinnerModel.

Class methods

S.N.Method & Description
1void addChangeListener(ChangeListener listener)
Adds a listener to the list that is notified each time a change to the model occurs.
2void commitEdit()
Commits the currently edited value to the SpinnerModel.
3protected JComponent createEditor(SpinnerModel model)
This method is called by the constructors to create the JComponent that displays the current value of the sequence.
4protected void fireStateChanged()
Sends a ChangeEvent, whose source is this JSpinner, to each ChangeListener.
5AccessibleContext getAccessibleContext()
Gets the AccessibleContext for the JSpinner
6ChangeListener[] getChangeListeners()
Returns an array of all the ChangeListeners added to this JSpinner with addChangeListener().
7JComponent getEditor()
Returns the component that displays and potentially changes the model's value.
8SpinnerModel getModel()
Returns the SpinnerModel that defines this spinners sequence of values.
9Object getNextValue()
Returns the object in the sequence that comes after the object returned by getValue().
10Object getPreviousValue()
Returns the object in the sequence that comes before the object returned by getValue().
11SpinnerUI getUI()
Returns the look and feel (L&F) object that renders this component.
12String getUIClassID()
Returns the suffix used to construct the name of the look and feel (L&F) class used to render this component.
13Object getValue()
Returns the current value of the model, typically this value is displayed by the editor.
14void removeChangeListener(ChangeListener listener)
Removes a ChangeListener from this spinner.
15void setEditor(JComponent editor)
Changes the JComponent that displays the current value of the SpinnerModel.
16void setModel(SpinnerModel model)
Changes the model that represents the value of this spinner.
17void setUI(SpinnerUI ui)
Sets the look and feel (L&F) object that renders this component.
18void setValue(Object value)
Changes current value of the model, typically this value is displayed by the editor.
19void updateUI()
Resets the UI property with the value from the current look and feel.

Methods inherited

This class inherits methods from the following classes:

  • javax.swing.JComponent

  • java.awt.Container

  • java.awt.Component

  • java.lang.Object

JSpinner Example

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

SwingControlDemo.java
package com.tutorialspoint.gui;
 
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.event.*;
 
public class SwingControlDemo {
    
   private JFrame mainFrame;
   private JLabel headerLabel;
   private JLabel statusLabel;
   private JPanel controlPanel;

   public SwingControlDemo(){
      prepareGUI();
   }

   public static void main(String[] args){
      SwingControlDemo  swingControlDemo = new SwingControlDemo();      
      swingControlDemo.showSpinnerDemo();
   }

   private void prepareGUI(){
      mainFrame = new JFrame("Java Swing 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 JLabel("", JLabel.CENTER);        
      statusLabel = new JLabel("",JLabel.CENTER);    

      statusLabel.setSize(350,100);

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

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

   private void showSpinnerDemo(){
      headerLabel.setText("Control in action: JSpinner"); 
      SpinnerModel spinnerModel =
         new SpinnerNumberModel(10, //initial value
            0, //min
            100, //max
            1);//step
      JSpinner spinner = new JSpinner(spinnerModel);
      spinner.addChangeListener(new ChangeListener() {
         public void stateChanged(ChangeEvent e) {
            statusLabel.setText("Value : " 
            + ((JSpinner)e.getSource()).getValue());
         }
      });
      controlPanel.add(spinner);
      mainFrame.setVisible(true);  
   } 
}

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

D:\SWING>javac com\tutorialspoint\gui\SwingControlDemo.java

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

D:\SWING>java com.tutorialspoint.gui.SwingControlDemo

Verify the following output

Swing JSpinner

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:/ > SWING > com > tutorialspoint > gui >

SwingControlDemo.java
package com.tutorialspoint.gui;

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;

public class SwingControlDemo {

   private JFrame mainFrame;
   private JLabel headerLabel;
   private JLabel statusLabel;
   private JPanel controlPanel;

   public SwingLayoutDemo(){
      prepareGUI();
   }

   public static void main(String[] args){
      SwingControlDemo swingControlDemo = new swingLayoutDemo();  
      swingControlDemo.showEventDemo();       
   }
      
   private void prepareGUI(){
      mainFrame = new JFrame("Java SWING Examples");
      mainFrame.setSize(400,400);
      mainFrame.setLayout(new GridLayout(3, 1));

      headerLabel = new JLabel("",JLabel.CENTER );
      statusLabel = new JLabel("",JLabel.CENTER);        

      statusLabel.setSize(350,100);
      mainFrame.addWindowListener(new WindowAdapter() {
         public void windowClosing(WindowEvent windowEvent){
	        System.exit(0);
         }        
      });    
      controlPanel = new JPanel();
      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"); 

      JButton okButton = new JButton("OK");
      JButton submitButton = new JButton("Submit");
      JButton cancelButton = new JButton("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:/ > SWING and type the following command.

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

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

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

Verify the following output

SWING  Event Handling

SWING 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

SWING AWTEvent Class

It is the root event class for all AWTEvent 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 SWING 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

SWING 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

SWING 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

SWING 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

SWING 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

SWING 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

SWING 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

SWING 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

SWING 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

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

Class methods

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

SWING 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

SWING 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

SWING 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

SWING 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:/ > SWING > com > tutorialspoint > gui >

SwingListenerDemo.java
package com.tutorialspoint.gui;

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;

public class SwingListenerDemo {
   private JFrame mainFrame;
   private JLabel headerLabel;
   private JLabel statusLabel;
   private JPanel controlPanel;

   public SwingListenerDemo(){
      prepareGUI();
   }

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

   private void prepareGUI(){
      mainFrame = new JFrame("Java SWING Examples");
      mainFrame.setSize(400,400);
      mainFrame.setLayout(new GridLayout(3, 1));

      headerLabel = new JLabel("",JLabel.CENTER );
      statusLabel = new JLabel("",JLabel.CENTER);        

      statusLabel.setSize(350,100);
      mainFrame.addWindowListener(new WindowAdapter() {
         public void windowClosing(WindowEvent windowEvent){
	        System.exit(0);
         }        
      });    
      controlPanel = new JPanel();
      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");      

      JPanel panel = new JPanel();      
      panel.setBackground(Color.magenta);            
		
      JButton okButton = new JButton("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:/ > SWING and type the following command.

D:\SWING>javac com\tutorialspoint\gui\SwingListenerDemo.java

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

D:\SWING>java com.tutorialspoint.gui.SwingListenerDemo

Verify the following output

SWING ActionListener

SWING 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:/ > SWING > com > tutorialspoint > gui >

SwingListenerDemo.java
package com.tutorialspoint.gui;

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;

public class SwingListenerDemo {
   private JFrame mainFrame;
   private JLabel headerLabel;
   private JLabel statusLabel;
   private JPanel controlPanel;

   public SwingListenerDemo(){
      prepareGUI();
   }

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

   private void prepareGUI(){
      mainFrame = new JFrame("Java SWING Examples");
      mainFrame.setSize(400,400);
      mainFrame.setLayout(new GridLayout(3, 1));

      headerLabel = new JLabel("",JLabel.CENTER );
      statusLabel = new JLabel("",JLabel.CENTER);        

      statusLabel.setSize(350,100);
      mainFrame.addWindowListener(new WindowAdapter() {
         public void windowClosing(WindowEvent windowEvent){
	        System.exit(0);
         }        
      });    
      controlPanel = new JPanel();
      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");      
   
      JPanel panel = new JPanel();      
      panel.setBackground(Color.magenta);            

      JLabel msglabel = 
      new JLabel("Welcome to TutorialsPoint SWING Tutorial."
         ,JLabel.CENTER);        
      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:/ > SWING and type the following command.

D:\SWING>javac com\tutorialspoint\gui\SwingListenerDemo.java

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

D:\SWING>java com.tutorialspoint.gui.SwingListenerDemo

Verify the following output

SWING ComponentListener

SWING 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:/ > SWING > com > tutorialspoint > gui >

SwingListenerDemo.java
package com.tutorialspoint.gui;

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;

public class SwingListenerDemo {
   private JFrame mainFrame;
   private JLabel headerLabel;
   private JLabel statusLabel;
   private JPanel controlPanel;

   public SwingListenerDemo(){
      prepareGUI();
   }

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

   private void prepareGUI(){
      mainFrame = new JFrame("Java SWING Examples");
      mainFrame.setSize(400,400);
      mainFrame.setLayout(new GridLayout(3, 1));

      headerLabel = new JLabel("",JLabel.CENTER );
      statusLabel = new JLabel("",JLabel.CENTER);        

      statusLabel.setSize(350,100);
      mainFrame.addWindowListener(new WindowAdapter() {
         public void windowClosing(WindowEvent windowEvent){
	        System.exit(0);
         }        
      });    
      controlPanel = new JPanel();
      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");      
      JCheckBox chkApple = new JCheckBox("Apple");
      JCheckBox chkMango = new JCheckBox("Mango");
      JCheckBox chkPeer = new JCheckBox("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(((JCheckBox)e.getItem()).getText()
         +" Checkbox: " 
         + (e.getStateChange()==1?"checked":"unchecked"));
      }    
   }
}

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

D:\SWING>javac com\tutorialspoint\gui\SwingListenerDemo.java

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

D:\SWING>java com.tutorialspoint.gui.SwingListenerDemo

Verify the following output

SWING ItemListener

SWING 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:/ > SWING > com > tutorialspoint > gui >

SwingListenerDemo.java
package com.tutorialspoint.gui;

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;

public class SwingListenerDemo {
   private JFrame mainFrame;
   private JLabel headerLabel;
   private JLabel statusLabel;
   private JPanel controlPanel;

   public SwingListenerDemo(){
      prepareGUI();
   }

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

   private void prepareGUI(){
      mainFrame = new JFrame("Java SWING Examples");
      mainFrame.setSize(400,400);
      mainFrame.setLayout(new GridLayout(3, 1));

      headerLabel = new JLabel("",JLabel.CENTER );
      statusLabel = new JLabel("",JLabel.CENTER);        

      statusLabel.setSize(350,100);
      mainFrame.addWindowListener(new WindowAdapter() {
         public void windowClosing(WindowEvent windowEvent){
	        System.exit(0);
         }        
      });    
      controlPanel = new JPanel();
      controlPanel.setLayout(new FlowLayout());

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

   private JTextField textField;
   private void showKeyListenerDemo(){
      headerLabel.setText("Listener in action: KeyListener");      
      textField  = new JTextField(10);

      textField.addKeyListener(new CustomKeyListener());
      JButton okButton = new JButton("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:/ > SWING and type the following command.

D:\SWING>javac com\tutorialspoint\gui\SwingListenerDemo.java

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

D:\SWING>java com.tutorialspoint.gui.SwingListenerDemo

Verify the following output

SWING KeyListener

SWING 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:/ > SWING > com > tutorialspoint > gui >

SwingListenerDemo.java
package com.tutorialspoint.gui;

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;

public class SwingListenerDemo {
   private JFrame mainFrame;
   private JLabel headerLabel;
   private JLabel statusLabel;
   private JPanel controlPanel;

   public SwingListenerDemo(){
      prepareGUI();
   }

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

   private void prepareGUI(){
      mainFrame = new JFrame("Java SWING Examples");
      mainFrame.setSize(400,400);
      mainFrame.setLayout(new GridLayout(3, 1));

      headerLabel = new JLabel("",JLabel.CENTER );
      statusLabel = new JLabel("",JLabel.CENTER);        

      statusLabel.setSize(350,100);
      mainFrame.addWindowListener(new WindowAdapter() {
         public void windowClosing(WindowEvent windowEvent){
	        System.exit(0);
         }        
      });    
      controlPanel = new JPanel();
      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");      

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

      JLabel msglabel = 
      new JLabel("Welcome to TutorialsPoint SWING Tutorial."
      ,JLabel.CENTER);        
      panel.add(msglabel);

      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:/ > SWING and type the following command.

D:\SWING>javac com\tutorialspoint\gui\SwingListenerDemo.java

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

D:\SWING>java com.tutorialspoint.gui.SwingListenerDemo

Verify the following output

SWING MouseListener

SWING 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:/ > SWING > com > tutorialspoint > gui >

SwingListenerDemo.java
package com.tutorialspoint.gui;

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;

public class SwingListenerDemo {
   private JFrame mainFrame;
   private JLabel headerLabel;
   private JLabel statusLabel;
   private JPanel controlPanel;

   public SwingListenerDemo(){
      prepareGUI();
   }

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

   private void prepareGUI(){
      mainFrame = new JFrame("Java SWING Examples");
      mainFrame.setSize(400,400);
      mainFrame.setLayout(new GridLayout(3, 1));

      headerLabel = new JLabel("",JLabel.CENTER );
      statusLabel = new JLabel("",JLabel.CENTER);        

      statusLabel.setSize(350,100);
      mainFrame.addWindowListener(new WindowAdapter() {
         public void windowClosing(WindowEvent windowEvent){
	        System.exit(0);
         }        
      });    
      controlPanel = new JPanel();
      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");      

      JButton okButton = new JButton("OK");

      aboutFrame = new JFrame();
      aboutFrame.setSize(300,200);;
      aboutFrame.setTitle("WindowListener Demo");
      aboutFrame.addWindowListener(new CustomWindowListener());
      
      JPanel panel = new JPanel();      
      panel.setBackground(Color.white);            
      JLabel msglabel 
      = new JLabel("Welcome to TutorialsPoint SWING Tutorial."
      ,JLabel.CENTER);        
      panel.add(msglabel);
      aboutFrame.add(panel);
      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:/ > SWING and type the following command.

D:\SWING>javac com\tutorialspoint\gui\SwingListenerDemo.java

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

D:\SWING>java com.tutorialspoint.gui.SwingListenerDemo

Verify the following output

SWING WindowListener

SWING 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:/ > SWING > com > tutorialspoint > gui >

SwingListenerDemo.java
package com.tutorialspoint.gui;

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;

public class SwingListenerDemo {
   private JFrame mainFrame;
   private JLabel headerLabel;
   private JLabel statusLabel;
   private JPanel controlPanel;

   public SwingListenerDemo(){
      prepareGUI();
   }

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

   private void prepareGUI(){
      mainFrame = new JFrame("Java SWING Examples");
      mainFrame.setSize(400,400);
      mainFrame.setLayout(new GridLayout(3, 1));

      headerLabel = new JLabel("",JLabel.CENTER );
      statusLabel = new JLabel("",JLabel.CENTER);        

      statusLabel.setSize(350,100);
      mainFrame.addWindowListener(new WindowAdapter() {
         public void windowClosing(WindowEvent windowEvent){
	        System.exit(0);
         }        
      });    
      controlPanel = new JPanel();
      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");      

      JPanel panel = new JPanel();
      JScrollBar scrollbar = new JScrollBar();
      scrollbar.addAdjustmentListener(new CustomAdjustmentListener());

      panel.add(scrollbar);
      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:/ > SWING and type the following command.

D:\SWING>javac com\tutorialspoint\gui\SwingListenerDemo.java

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

D:\SWING>java com.tutorialspoint.gui.SwingListenerDemo

Verify the following output

SWING AdjustmentListener

SWING 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

ContainerListener Example

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

SwingListenerDemo.java
package com.tutorialspoint.gui;

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;

public class SwingListenerDemo {
   private JFrame mainFrame;
   private JLabel headerLabel;
   private JLabel statusLabel;
   private JPanel controlPanel;

   public SwingListenerDemo(){
      prepareGUI();
   }

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

   private void prepareGUI(){
      mainFrame = new JFrame("Java SWING Examples");
      mainFrame.setSize(400,400);
      mainFrame.setLayout(new GridLayout(3, 1));

      headerLabel = new JLabel("",JLabel.CENTER );
      statusLabel = new JLabel("",JLabel.CENTER);        

      statusLabel.setSize(350,100);
      mainFrame.addWindowListener(new WindowAdapter() {
         public void windowClosing(WindowEvent windowEvent){
	        System.exit(0);
         }        
      });    
      controlPanel = new JPanel();
      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");      

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

      JLabel msglabel 
      = new JLabel("Welcome to TutorialsPoint SWING Tutorial."
      ,JLabel.CENTER);        
      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:/ > SWING and type the following command.

D:\SWING>javac com\tutorialspoint\gui\SwingListenerDemo.java

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

D:\SWING>java com.tutorialspoint.gui.SwingListenerDemo

Verify the following output

SWING ContainerListener

SWING 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:/ > SWING > com > tutorialspoint > gui >

SwingListenerDemo.java
package com.tutorialspoint.gui;

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;

public class SwingListenerDemo {
   private JFrame mainFrame;
   private JLabel headerLabel;
   private JLabel statusLabel;
   private JPanel controlPanel;

   public SwingListenerDemo(){
      prepareGUI();
   }

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

   private void prepareGUI(){
      mainFrame = new JFrame("Java SWING Examples");
      mainFrame.setSize(400,400);
      mainFrame.setLayout(new GridLayout(3, 1));

      headerLabel = new JLabel("",JLabel.CENTER );
      statusLabel = new JLabel("",JLabel.CENTER);        

      statusLabel.setSize(350,100);
      mainFrame.addWindowListener(new WindowAdapter() {
         public void windowClosing(WindowEvent windowEvent){
	        System.exit(0);
         }        
      });    
      controlPanel = new JPanel();
      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");      

      JPanel panel = new JPanel();      
      panel.setBackground(Color.magenta);
      panel.setLayout(new FlowLayout());        
      panel.addMouseMotionListener(new CustomMouseMotionListener());
      
      JLabel msglabel 
      = new JLabel("Welcome to TutorialsPoint SWING Tutorial."
      ,JLabel.CENTER);        
      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:/ > SWING and type the following command.

D:\SWING>javac com\tutorialspoint\gui\SwingListenerDemo.java

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

D:\SWING>java com.tutorialspoint.gui.SwingListenerDemo

Verify the following output

SWING MouseMotionListener

SWING 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:/ > SWING > com > tutorialspoint > gui >

SwingListenerDemo.java
package com.tutorialspoint.gui;

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;

public class SwingListenerDemo {
   private JFrame mainFrame;
   private JLabel headerLabel;
   private JLabel statusLabel;
   private JPanel controlPanel;

   public SwingListenerDemo(){
      prepareGUI();
   }

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

   private void prepareGUI(){
      mainFrame = new JFrame("Java SWING Examples");
      mainFrame.setSize(400,400);
      mainFrame.setLayout(new GridLayout(3, 1));

      headerLabel = new JLabel("",JLabel.CENTER );
      statusLabel = new JLabel("",JLabel.CENTER);        

      statusLabel.setSize(350,100);
      mainFrame.addWindowListener(new WindowAdapter() {
         public void windowClosing(WindowEvent windowEvent){
	        System.exit(0);
         }        
      });    
      controlPanel = new JPanel();
      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");      
      JButton okButton = new JButton("OK");
      JButton cancelButton = new JButton("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:/ > SWING and type the following command.

D:\SWING>javac com\tutorialspoint\gui\SwingListenerDemo.java

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

D:\SWING>java com.tutorialspoint.gui.SwingListenerDemo

Verify the following output

SWING focusListener

SWING 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.

SWING 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:/ > SWING > com > tutorialspoint > gui >

SwingAdapterDemo.java
package com.tutorialspoint.gui;

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;

public class SwingAdapterDemo {
   private JFrame mainFrame;
   private JLabel headerLabel;
   private JLabel statusLabel;
   private JPanel controlPanel;

   public SwingAdapterDemo(){
      prepareGUI();
   }

   public static void main(String[] args){
      SwingAdapterDemo  swingAdapterDemo = new SwingAdapterDemo();        
      swingAdapterDemo.showFocusAdapterDemo();
   }

   private void prepareGUI(){
      mainFrame = new JFrame("Java SWING Examples");
      mainFrame.setSize(400,400);
      mainFrame.setLayout(new GridLayout(3, 1));

      headerLabel = new JLabel("",JLabel.CENTER );
      statusLabel = new JLabel("",JLabel.CENTER);        

      statusLabel.setSize(350,100);
      mainFrame.addWindowListener(new WindowAdapter() {
         public void windowClosing(WindowEvent windowEvent){
	        System.exit(0);
         }        
      });    
      controlPanel = new JPanel();
      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");      

      JButton okButton = new JButton("OK");
      JButton cancelButton = new JButton("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:/ > SWING and type the following command.

D:\SWING>javac com\tutorialspoint\gui\SwingAdapterDemo.java

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

D:\SWING>java com.tutorialspoint.gui.SwingAdapterDemo

Verify the following output

SWING FocusAdapter

SWING 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:/ > SWING > com > tutorialspoint > gui >

SwingAdapterDemo.java
package com.tutorialspoint.gui;

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

public class SwingAdapterDemo {
   private JFrame mainFrame;
   private JLabel headerLabel;
   private JLabel statusLabel;
   private JPanel controlPanel;

   public SwingAdapterDemo(){
      prepareGUI();
   }

   public static void main(String[] args){
      SwingAdapterDemo  swingAdapterDemo = new SwingAdapterDemo();        
      swingAdapterDemo.showKeyAdapterDemo();
   }

   private void prepareGUI(){
      mainFrame = new JFrame("Java SWING Examples");
      mainFrame.setSize(400,400);
      mainFrame.setLayout(new GridLayout(3, 1));

      headerLabel = new JLabel("",JLabel.CENTER );
      statusLabel = new JLabel("",JLabel.CENTER);        

      statusLabel.setSize(350,100);
      mainFrame.addWindowListener(new WindowAdapter() {
         public void windowClosing(WindowEvent windowEvent){
	        System.exit(0);
         }        
      });    
      controlPanel = new JPanel();
      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 JTextField textField = new JTextField(10);

      textField.addKeyListener(new KeyAdapter() {
         public void keyPressed(KeyEvent e) {                
            if(e.getKeyCode() == KeyEvent.VK_ENTER){
               statusLabel.setText("Entered text: " 
               + textField.getText());
            }
         }        
      });
      JButton okButton = new JButton("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:/ > SWING and type the following command.

D:\SWING>javac com\tutorialspoint\gui\SwingAdapterDemo.java

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

D:\SWING>java com.tutorialspoint.gui.SwingAdapterDemo

Verify the following output

SWING KeyAdapter

SWING 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:/ > SWING > com > tutorialspoint > gui >

SwingAdapterDemo.java
package com.tutorialspoint.gui;

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

public class SwingAdapterDemo {
   private JFrame mainFrame;
   private JLabel headerLabel;
   private JLabel statusLabel;
   private JPanel controlPanel;

   public SwingAdapterDemo(){
      prepareGUI();
   }

   public static void main(String[] args){
      AwtAdapterDemo  awtAdapterDemo = new AwtAdapterDemo();  
      swingAdapterDemo.showMouseAdapterDemo();
   }

   private void prepareGUI(){
      mainFrame = new JFrame("Java SWING Examples");
      mainFrame.setSize(400,400);
      mainFrame.setLayout(new GridLayout(3, 1));

      headerLabel = new JLabel("",JLabel.CENTER );
      statusLabel = new JLabel("",JLabel.CENTER);        

      statusLabel.setSize(350,100);
      mainFrame.addWindowListener(new WindowAdapter() {
         public void windowClosing(WindowEvent windowEvent){
	        System.exit(0);
         }        
      });    
      controlPanel = new JPanel();
      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");      

      JPanel panel = new JPanel();      
      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() +")");
         }                
      });

      JLabel msglabel 
      = new JLabel("Welcome to TutorialsPoint SWING Tutorial."
      ,JLabel.CENTER);
      
      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:/ > SWING and type the following command.

D:\SWING>javac com\tutorialspoint\gui\SwingAdapterDemo.java

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

D:\SWING>java com.tutorialspoint.gui.SwingAdapterDemo

Verify the following output

SWING MouseAdapter

SWING 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:/ > SWING > com > tutorialspoint > gui >

SwingAdapterDemo.java
package com.tutorialspoint.gui;

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

public class SwingAdapterDemo {
   private JFrame mainFrame;
   private JLabel headerLabel;
   private JLabel statusLabel;
   private JPanel controlPanel;

   public SwingAdapterDemo(){
      prepareGUI();
   }

   public static void main(String[] args){
      SwingAdapterDemo  swingAdapterDemo = new SwingAdapterDemo();        
      swingAdapterDemo.showMouseMotionAdapterDemo();
   }

   private void prepareGUI(){
      mainFrame = new JFrame("Java SWING Examples");
      mainFrame.setSize(400,400);
      mainFrame.setLayout(new GridLayout(3, 1));

      headerLabel = new JLabel("",JLabel.CENTER );
      statusLabel = new JLabel("",JLabel.CENTER);        

      statusLabel.setSize(350,100);
      mainFrame.addWindowListener(new WindowAdapter() {
         public void windowClosing(WindowEvent windowEvent){
	        System.exit(0);
         }        
      });    
      controlPanel = new JPanel();
      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");      

      JPanel panel = new JPanel();      
      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() +")");
         }                
      });

      JLabel msglabel 
      = new JLabel("Welcome to TutorialsPoint SWING Tutorial."
      ,JLabel.CENTER);
      panel.add(msglabel);

      controlPanel.add(panel);

      mainFrame.setVisible(true);  
   }
}

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

D:\SWING>javac com\tutorialspoint\gui\SwingAdapterDemo.java

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

D:\SWING>java com.tutorialspoint.gui.SwingAdapterDemo

Verify the following output

SWING MouseMotionAdapter

SWING 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:/ > SWING > com > tutorialspoint > gui >

SwingAdapterDemo.java
package com.tutorialspoint.gui;

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

public class SwingAdapterDemo {
   private JFrame mainFrame;
   private JLabel headerLabel;
   private JLabel statusLabel;
   private JPanel controlPanel;

   public SwingAdapterDemo(){
      prepareGUI();
   }

   public static void main(String[] args){
      SwingAdapterDemo  swingAdapterDemo = new SwingAdapterDemo();        
      swingAdapterDemo.showWindowAdapterDemo();
   }

   private void prepareGUI(){
      mainFrame = new JFrame("Java SWING Examples");
      mainFrame.setSize(400,400);
      mainFrame.setLayout(new GridLayout(3, 1));

      headerLabel = new JLabel("",JLabel.CENTER );
      statusLabel = new JLabel("",JLabel.CENTER);        

      statusLabel.setSize(350,100);
      mainFrame.addWindowListener(new WindowAdapter() {
         public void windowClosing(WindowEvent windowEvent){
	        System.exit(0);
         }        
      });    
      controlPanel = new JPanel();
      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");      

      JButton okButton = new JButton("OK");

      final JFrame aboutFrame = new JFrame();
      aboutFrame.setSize(300,200);;
      aboutFrame.setTitle("WindowAdapter Demo");
      aboutFrame.addWindowListener(new WindowAdapter() {
            public void windowClosing(WindowEvent windowEvent){
               aboutFrame.dispose();
         }        
      });    
      JLabel msglabel 
      = new JLabel("Welcome to TutorialsPoint SWING Tutorial."
      ,JLabel.CENTER);
	  aboutFrame.add(msgLabel);
      aboutFrame.setVisible(true);
   }
}

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

D:\SWING>javac com\tutorialspoint\gui\SwingAdapterDemo.java

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

D:\SWING>java com.tutorialspoint.gui.SwingAdapterDemo

Verify the following output

SWING WindowAdapter

SWING 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.

SWING 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.

SWING 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.

SWING 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:/ > SWING > com > tutorialspoint > gui >

SwingLayoutDemo.java
package com.tutorialspoint.gui;

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;

public class SwingLayoutDemo {
   private JFrame mainFrame;
   private JLabel headerLabel;
   private JLabel statusLabel;
   private JPanel controlPanel;
   private JLabel msglabel;

   public SwingLayoutDemo(){
      prepareGUI();
   }

   public static void main(String[] args){
      SwingLayoutDemo swingLayoutDemo = new SwingLayoutDemo();  
      swingLayoutDemo.showBorderLayoutDemo();       
   }
      
   private void prepareGUI(){
      mainFrame = new JFrame("Java SWING Examples");
      mainFrame.setSize(400,400);
      mainFrame.setLayout(new GridLayout(3, 1));

      headerLabel = new JLabel("",JLabel.CENTER );
      statusLabel = new JLabel("",JLabel.CENTER);        

      statusLabel.setSize(350,100);
      mainFrame.addWindowListener(new WindowAdapter() {
         public void windowClosing(WindowEvent windowEvent){
	        System.exit(0);
         }        
      });    
      controlPanel = new JPanel();
      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");      

      JPanel panel = new JPanel();
      panel.setBackground(Color.darkGray);
      panel.setSize(300,300);
      BorderLayout layout = new BorderLayout();
      layout.setHgap(10);
      layout.setVgap(10);
      panel.setLayout(layout);        
	  
      panel.add(new JButton("Center"),BorderLayout.CENTER);
      panel.add(new JButton("Line Start"),BorderLayout.LINE_START); 
      panel.add(new JButton("Line End"),BorderLayout.LINE_END);
      panel.add(new JButton("East"),BorderLayout.EAST);   
      panel.add(new JButton("West"),BorderLayout.WEST); 
      panel.add(new JButton("North"),BorderLayout.NORTH); 
      panel.add(new JButton("South"),BorderLayout.SOUTH); 

      controlPanel.add(panel);

      mainFrame.setVisible(true);  
   }
}

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

D:\SWING>javac com\tutorialspoint\gui\SwingLayoutDemo.java

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

D:\SWING>java com.tutorialspoint.gui.SwingLayoutDemo

Verify the following output

SWING BorderLayout

SWING 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:/ > SWING > com > tutorialspoint > gui >

SwingLayoutDemo.java
package com.tutorialspoint.gui;

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;

public class SwingLayoutDemo {
   private JFrame mainFrame;
   private JLabel headerLabel;
   private JLabel statusLabel;
   private JPanel controlPanel;
   private JLabel msglabel;

   public SwingLayoutDemo(){
      prepareGUI();
   }

   public static void main(String[] args){
      SwingLayoutDemo swingLayoutDemo = new SwingLayoutDemo();  
      swingLayoutDemo.showCardLayoutDemo();       
   }
      
   private void prepareGUI(){
      mainFrame = new JFrame("Java SWING Examples");
      mainFrame.setSize(400,400);
      mainFrame.setLayout(new GridLayout(3, 1));

      headerLabel = new JLabel("",JLabel.CENTER );
      statusLabel = new JLabel("",JLabel.CENTER);        

      statusLabel.setSize(350,100);
      mainFrame.addWindowListener(new WindowAdapter() {
         public void windowClosing(WindowEvent windowEvent){
	        System.exit(0);
         }        
      });    
      controlPanel = new JPanel();
      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 JPanel panel = new JPanel();
      panel.setBackground(Color.CYAN);
      panel.setSize(300,300);

      CardLayout layout = new CardLayout();
      layout.setHgap(10);
      layout.setVgap(10);
      panel.setLayout(layout);        

      JPanel buttonPanel = new JPanel(new FlowLayout());

      buttonPanel.add(new JButton("OK"));
      buttonPanel.add(new JButton("Cancel"));    

      JPanel textBoxPanel = new JPanel(new FlowLayout());

      textBoxPanel.add(new JLabel("Name:"));
      textBoxPanel.add(new JTextField(20));

      panel.add("Button", buttonPanel);
      panel.add("Text", textBoxPanel);
      
	  final DefaultComboBoxModel panelName = new DefaultComboBoxModel();

      panelName.addElement("Button");
      panelName.addElement("Text");
     	  
	  final JComboBox listCombo = new JComboBox(panelName);    
      listCombo.setSelectedIndex(0);

      JScrollPane listComboScrollPane = new JScrollPane(listCombo);    

      JButton showButton = new JButton("Show");

      showButton.addActionListener(new ActionListener() {
         public void actionPerformed(ActionEvent e) { 
            String data = "";
            if (listCombo.getSelectedIndex() != -1) {  
               CardLayout cardLayout = (CardLayout)(panel.getLayout());
               cardLayout.show(panel, 
               (String)listCombo.getItemAt(listCombo.getSelectedIndex()));	               
            }              
            statusLabel.setText(data);
         }
      }); 
	  
      controlPanel.add(listComboScrollPane);
      controlPanel.add(showButton);
	  controlPanel.add(panel);

      mainFrame.setVisible(true);  
   }
}

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

D:\SWING>javac com\tutorialspoint\gui\SwingLayoutDemo.java

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

D:\SWING>java com.tutorialspoint.gui.SwingLayoutDemo

Verify the following output

SWING  CardLayout

SWING 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:/ > SWING > com > tutorialspoint > gui >

SwingLayoutDemo.java
package com.tutorialspoint.gui;

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;

public class SwingLayoutDemo {
   private JFrame mainFrame;
   private JLabel headerLabel;
   private JLabel statusLabel;
   private JPanel controlPanel;
   private JLabel msglabel;

   public SwingLayoutDemo(){
      prepareGUI();
   }

   public static void main(String[] args){
      SwingLayoutDemo swingLayoutDemo = new SwingLayoutDemo();  
      swingLayoutDemo.showFlowLayoutDemo();       
   }
      
   private void prepareGUI(){
      mainFrame = new JFrame("Java SWING Examples");
      mainFrame.setSize(400,400);
      mainFrame.setLayout(new GridLayout(3, 1));

      headerLabel = new JLabel("",JLabel.CENTER );
      statusLabel = new JLabel("",JLabel.CENTER);        

      statusLabel.setSize(350,100);
      mainFrame.addWindowListener(new WindowAdapter() {
         public void windowClosing(WindowEvent windowEvent){
	        System.exit(0);
         }        
      });    
      controlPanel = new JPanel();
      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");      

      JPanel panel = new JPanel();
      panel.setBackground(Color.darkGray);
      panel.setSize(200,200);
      FlowLayout layout = new FlowLayout();
      layout.setHgap(10);              
      layout.setVgap(10);
      panel.setLayout(layout);        
      panel.add(new JButton("OK"));
      panel.add(new JButton("Cancel"));       

      controlPanel.add(panel);

      mainFrame.setVisible(true);  
   }
}

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

D:\SWING>javac com\tutorialspoint\gui\SwingLayoutDemo.java

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

D:\SWING>java com.tutorialspoint.gui.SwingLayoutDemo

Verify the following output

SWING  FlowLayout

SWING 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:/ > SWING > com > tutorialspoint > gui >

SwingLayoutDemo.java
package com.tutorialspoint.gui;

import javax.swing.*;

public class SwingLayoutDemo {
   private JFrame mainFrame;
   private JLabel headerLabel;
   private JLabel statusLabel;
   private JPanel controlPanel;
   private JLabel msglabel;

   public SwingLayoutDemo(){
      prepareGUI();
   }

   public static void main(String[] args){
      SwingLayoutDemo swingLayoutDemo = new SwingLayoutDemo();  
      swingLayoutDemo.showGridLayoutDemo();       
   }
      
   private void prepareGUI(){
      mainFrame = new JFrame("Java SWING Examples");
      mainFrame.setSize(400,400);
      mainFrame.setLayout(new GridLayout(3, 1));

      headerLabel = new JLabel("",JLabel.CENTER );
      statusLabel = new JLabel("",JLabel.CENTER);        

      statusLabel.setSize(350,100);
      mainFrame.addWindowListener(new WindowAdapter() {
         public void windowClosing(WindowEvent windowEvent){
	        System.exit(0);
         }        
      });    
      controlPanel = new JPanel();
      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");      

      JPanel panel = new JPanel();
      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 JButton("Button 1"));
      panel.add(new JButton("Button 2")); 
      panel.add(new JButton("Button 3")); 
      panel.add(new JButton("Button 4")); 
      panel.add(new JButton("Button 5")); 
      controlPanel.add(panel);
      mainFrame.setVisible(true);  
   }
}

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

D:\SWING>javac com\tutorialspoint\gui\SwingLayoutDemo.java

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

D:\SWING>java com.tutorialspoint.gui.SwingLayoutDemo

Verify the following output

SWING  GridLayout

SWING 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.GridBagLayout class:

  • static int DEFAULT_SIZE --Indicates the size from the component or gap should be used for a particular range value.

  • static int PREFERRED_SIZE --Indicates the preferred size from the component or gap should be used for a particular range value.

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:/ > SWING > com > tutorialspoint > gui >

SwingLayoutDemo.java
package com.tutorialspoint.gui;

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;

public class SwingLayoutDemo {
   private JFrame mainFrame;
   private JLabel headerLabel;
   private JLabel statusLabel;
   private JPanel controlPanel;
   private JLabel msglabel;

   public SwingLayoutDemo(){
      prepareGUI();
   }

   public static void main(String[] args){
      SwingLayoutDemo swingLayoutDemo = new SwingLayoutDemo();  
      swingLayoutDemo.showGridBagLayoutDemo();       
   }
      
   private void prepareGUI(){
      mainFrame = new JFrame("Java SWING Examples");
      mainFrame.setSize(400,400);
      mainFrame.setLayout(new GridLayout(3, 1));

      headerLabel = new JLabel("",JLabel.CENTER );
      statusLabel = new JLabel("",JLabel.CENTER);        

      statusLabel.setSize(350,100);
      mainFrame.addWindowListener(new WindowAdapter() {
         public void windowClosing(WindowEvent windowEvent){
	        System.exit(0);
         }        
      });    
      controlPanel = new JPanel();
      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");      

      JPanel panel = new JPanel();
      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 JButton("Button 1"),gbc);

      gbc.gridx = 1;
      gbc.gridy = 0;
      panel.add(new JButton("Button 2"),gbc); 

      gbc.fill = GridBagConstraints.HORIZONTAL;
      gbc.ipady = 20;   
      gbc.gridx = 0;
      gbc.gridy = 1;
      panel.add(new JButton("Button 3"),gbc); 

      gbc.gridx = 1;
      gbc.gridy = 1;       
      panel.add(new JButton("Button 4"),gbc);  

      gbc.gridx = 0;
      gbc.gridy = 2;      
      gbc.fill = GridBagConstraints.HORIZONTAL;
      gbc.gridwidth = 2;
      panel.add(new JButton("Button 5"),gbc);  

      controlPanel.add(panel);

      mainFrame.setVisible(true);  
   }
}

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

D:\SWING>javac com\tutorialspoint\gui\SwingLayoutDemo.java

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

D:\SWING>java com.tutorialspoint.gui.SwingLayoutDemo

Verify the following output

SWING  GridBagLayout

SWING GroupLayout Class

Introduction

The class GroupLayout hierarchically groups components in order to position them in a Container .

Class declaration

Following is the declaration for javax.swing.GroupLayout class:

public class GroupLayout
   extends Object
      implements LayoutManager2

Field

Following are the fields for javax.swing.GroupLayout class:

  • static int DEFAULT_SIZE -- Indicates the size from the component or gap should be used for a particular range value.

  • static int PREFERRED_SIZE -- Indicates the preferred size from the component or gap should be used for a particular range value.

Class constructors

S.N.Constructor & Description
1GroupLayout(Container host)
Creates a GroupLayout for the specified Container.

Class methods

S.N.Method & Description
1void addLayoutComponent(Component component, Object constraints)
Notification that a Component has been added to the parent container.
2void addLayoutComponent(String name, Component component)
Notification that a Component has been added to the parent container.
3GroupLayout.ParallelGroup createBaselineGroup(boolean resizable, boolean anchorBaselineToTop)
Creates and returns a ParallelGroup that aligns it's elements along the baseline.
4GroupLayout.ParallelGroup createParallelGroup()
Creates and returns a ParallelGroup with an alignment of Alignment.LEADING.
5GroupLayout.ParallelGroup createParallelGroup(GroupLayout.Alignment alignment)
Creates and returns a ParallelGroup with the specified alignment.
6GroupLayout.ParallelGroup createParallelGroup(GroupLayout.Alignment alignment, boolean resizable)
Creates and returns a ParallelGroup with the specified alignment and resize behavior.
7GroupLayout.SequentialGroup createSequentialGroup()
Creates and returns a SequentialGroup.
8boolean getAutoCreateContainerGaps()
Returns true if gaps between the container and components that border the container are automatically created.
9boolean getAutoCreateGaps()
Returns true if gaps between components are automatically created.
10boolean getHonorsVisibility()
Returns whether component visiblity is considered when sizing and positioning components.
11float getLayoutAlignmentX(Container parent)
Returns the alignment along the x axis.
12float getLayoutAlignmentY(Container parent)
Returns the alignment along the y axis.
13LayoutStyle getLayoutStyle()
Returns the LayoutStyle used for calculating the preferred gap between components.
14void invalidateLayout(Container parent)
Invalidates the layout, indicating that if the layout manager has cached information it should be discarded.
15void layoutContainer(Container parent)
Lays out the specified container.
16void linkSize(Component... components)
Forces the specified components to have the same size regardless of their preferred, minimum or maximum sizes.
17void linkSize(int axis, Component... components)
Forces the specified components to have the same size along the specified axis regardless of their preferred, minimum or maximum sizes.
18Dimension maximumLayoutSize(Container parent)
Returns the maximum size for the specified container.
19Dimension minimumLayoutSize(Container parent)
Returns the minimum size for the specified container.
20Dimension preferredLayoutSize(Container parent)
Returns the preferred size for the specified container.
21void removeLayoutComponent(Component component)
Notification that a Component has been removed from the parent container.
22void replace(Component existingComponent, Component newComponent)
Replaces an existing component with a new one.
23void setAutoCreateContainerGaps(boolean autoCreateContainerPadding)
Sets whether a gap between the container and components that touch the border of the container should automatically be created.
24void setAutoCreateGaps(boolean autoCreatePadding)
Sets whether a gap between components should automatically be created.
25void setHonorsVisibility(boolean honorsVisibility)
Sets whether component visiblity is considered when sizing and positioning components.
26void setHonorsVisibility(Component component, Boolean honorsVisibility)
Sets whether the component's visiblity is considered for sizing and positioning.
27void setHorizontalGroup(GroupLayout.Group group)
Sets the Group that positions and sizes components along the horizontal axis.
28void setLayoutStyle(LayoutStyle layoutStyle)
Sets the LayoutStyle used to calculate the preferred gaps between components.
29void setVerticalGroup(GroupLayout.Group group)
Sets the Group that positions and sizes components along the vertical axis.
30String toString()
Returns a string representation of this GroupLayout.

Methods inherited

This class inherits methods from the following classes:

  • java.lang.Object

GroupLayout Example

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

SwingLayoutDemo.java
package com.tutorialspoint.gui;

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;

public class SwingLayoutDemo {
   private JFrame mainFrame;
   private JLabel headerLabel;
   private JLabel statusLabel;
   private JPanel controlPanel;
   private JLabel msglabel;

   public SwingLayoutDemo(){
      prepareGUI();
   }

   public static void main(String[] args){
      SwingLayoutDemo swingLayoutDemo = new SwingLayoutDemo();  
      swingLayoutDemo.showGroupLayoutDemo();       
   }
      
   private void prepareGUI(){
      mainFrame = new JFrame("Java SWING Examples");
      mainFrame.setSize(400,400);
      mainFrame.setLayout(new GridLayout(3, 1));

      headerLabel = new JLabel("",JLabel.CENTER );
      statusLabel = new JLabel("",JLabel.CENTER);        

      statusLabel.setSize(350,100);
      mainFrame.addWindowListener(new WindowAdapter() {
         public void windowClosing(WindowEvent windowEvent){
	        System.exit(0);
         }        
      });    
      controlPanel = new JPanel();
      controlPanel.setLayout(new FlowLayout());

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

   private void showGroupLayoutDemo(){
      headerLabel.setText("Layout in action: GroupLayout");      

      JPanel panel = new JPanel();
      // panel.setBackground(Color.darkGray);
      panel.setSize(200,200);
      GroupLayout layout = new GroupLayout(panel);
      layout.setAutoCreateGaps(true);
      layout.setAutoCreateContainerGaps(true);
      JButton btn1 = new JButton("Button 1");
      JButton btn2 = new JButton("Button 2");
      JButton btn3 = new JButton("Button 3");

      layout.setHorizontalGroup(layout.createSequentialGroup()
         .addComponent(btn1)
         .addGroup(layout.createSequentialGroup()
            .addGroup(layout.createParallelGroup(
               GroupLayout.Alignment.LEADING)
               .addComponent(btn2)
               .addComponent(btn3)       
            )
         )    
      );


      layout.setVerticalGroup(layout.createSequentialGroup()
         .addComponent(btn1)
         .addComponent(btn2)
         .addComponent(btn3)                                    
      );
      panel.setLayout(layout);        
      controlPanel.add(panel);

      mainFrame.setVisible(true);  
   }
}

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

D:\SWING>javac com\tutorialspoint\gui\SwingLayoutDemo.java

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

D:\SWING>java com.tutorialspoint.gui.SwingLayoutDemo

Verify the following output

SWING GroupLayout

SWING SpringLayout Class

Introduction

The class SpringLayout positions the children of its associated container according to a set of constraints.

Class declaration

Following is the declaration for javax.swing.SpringLayout class:

public class SpringLayout
   extends Object
      implements LayoutManager2

Field

Following are the fields for javax.swing.SpringLayout class:

  • static String BASELINE --Specifies the baseline of a component.

  • static String EAST --Specifies the right edge of a component's bounding rectangle.

  • static String HEIGHT --Specifies the height of a component's bounding rectangle.

  • static String HORIZONTAL_CENTER --Specifies the horizontal center of a component's bounding rectangle.

  • static String NORTH --Specifies the top edge of a component's bounding rectangle.

  • static String SOUTH --Specifies the bottom edge of a component's bounding rectangle.

  • static String VERTICAL_CENTER --Specifies the vertical center of a component's bounding rectangle.

  • static String WEST --Specifies the left edge of a component's bounding rectangle.

  • static String WIDTH --Specifies the width of a component's bounding rectangle.

Class constructors

S.N.Constructor & Description
1SpringLayout()
Creates a new SpringLayout.

Class methods

S.N.Method & Description
1void addLayoutComponent(Component component, Object constraints)
If constraints is an instance of SpringLayout.Constraints, associates the constraints with the specified component.
2void addLayoutComponent(String name, Component c)
Has no effect, since this layout manager does not use a per-component string.
3Spring getConstraint(String edgeName, Component c)
Returns the spring controlling the distance between the specified edge of the component and the top or left edge of its parent.
4SpringLayout.Constraints getConstraints(Component c)
Returns the constraints for the specified component.
5float getLayoutAlignmentX(Container p)
Returns 0.5f (centered).
6float getLayoutAlignmentY(Container p)
Returns 0.5f (centered).
7void invalidateLayout(Container p)
Invalidates the layout, indicating that if the layout manager has cached information it should be discarded.
8void layoutContainer(Container parent)
Lays out the specified container.
9Dimension maximumLayoutSize(Container parent)
Calculates the maximum size dimensions for the specified container, given the components it contains.
10Dimension minimumLayoutSize(Container parent)
Calculates the minimum size dimensions for the specified container, given the components it contains.
11Dimension preferredLayoutSize(Container parent)
Calculates the preferred size dimensions for the specified container, given the components it contains.
12void putConstraint(String e1, Component c1, int pad, String e2, Component c2)
Links edge e1 of component c1 to edge e2 of component c2, with a fixed distance between the edges.
13void putConstraint(String e1, Component c1, Spring s, String e2, Component c2)
Links edge e1 of component c1 to edge e2 of component c2.
14void removeLayoutComponent(Component c)
Removes the constraints associated with the specified component.

Methods inherited

This class inherits methods from the following classes:

  • java.lang.Object

SpringLayout Example

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

SwingLayoutDemo.java
package com.tutorialspoint.gui;

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;

public class SwingLayoutDemo {
   private JFrame mainFrame;
   private JLabel headerLabel;
   private JLabel statusLabel;
   private JPanel controlPanel;
   private JLabel msglabel;

   public SwingLayoutDemo(){
      prepareGUI();
   }

   public static void main(String[] args){
      SwingLayoutDemo swingLayoutDemo = new SwingLayoutDemo();  
      swingLayoutDemo.showSpringLayoutDemo();       
   }
      
   private void prepareGUI(){
      mainFrame = new JFrame("Java SWING Examples");
      mainFrame.setSize(400,400);
      mainFrame.setLayout(new GridLayout(3, 1));

      headerLabel = new JLabel("",JLabel.CENTER );
      statusLabel = new JLabel("",JLabel.CENTER);        

      statusLabel.setSize(350,100);
      mainFrame.addWindowListener(new WindowAdapter() {
         public void windowClosing(WindowEvent windowEvent){
	        System.exit(0);
         }        
      });    
      controlPanel = new JPanel();
      controlPanel.setLayout(new FlowLayout());

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

   private void showSpringLayoutDemo(){

      headerLabel.setText("Layout in action: SpringLayout");   
      SpringLayout layout = new SpringLayout();

      JPanel panel = new JPanel();
      panel.setLayout(layout);
      JLabel label = new JLabel("Enter Name: ");
      JTextField textField = new JTextField("", 15);
      panel.add(label);
      panel.add(textField);

      layout.putConstraint(SpringLayout.WEST, label,5,
         SpringLayout.WEST, controlPanel);
      layout.putConstraint(SpringLayout.NORTH, label,5,
         SpringLayout.NORTH, controlPanel);
      layout.putConstraint(SpringLayout.WEST, textField,5,
         SpringLayout.EAST, label);
      layout.putConstraint(SpringLayout.NORTH, textField,5,
         SpringLayout.NORTH, controlPanel);
      layout.putConstraint(SpringLayout.EAST, panel,5,
         SpringLayout.EAST, textField);
      layout.putConstraint(SpringLayout.SOUTH, panel,5,
         SpringLayout.SOUTH, textField);
      controlPanel.add(panel);
      mainFrame.setVisible(true);  
   } 
}

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

D:\SWING>javac com\tutorialspoint\gui\SwingLayoutDemo.java

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

D:\SWING>java com.tutorialspoint.gui.SwingLayoutDemo

Verify the following output

SWING SpringLayout

SWING 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

Swing Menu Hiearchy

SWING JMenuBar Class

Introduction

The JMenuBar class provides an implementation of a menu bar.

Class declaration

Following is the declaration for javax.swing.JMenuBar class:

public class JMenuBar
   extends JComponent
      implements Accessible, MenuElement

Class constructors

S.N.Constructor & Description
1JMenuBar()
Creates a new menu bar.

Class methods

JMenu add(JMenu c)
Appends the specified menu to the end of the menu bar.
S.N.Method & Description
1void addNotify()
Overrides JComponent.addNotify to register this menu bar with the current keyboard manager.
1AccessibleContext getAccessibleContext()
Gets the AccessibleContext associated with this JMenuBar.
2Component getComponent()
Implemented to be a MenuElement.
3Component getComponentAtIndex(int i)
Deprecated. replaced by getComponent(int i)
4int getComponentIndex(Component c)
Returns the index of the specified component.
5JMenu getHelpMenu()
Gets the help menu for the menu bar.
6Insets getMargin()
Returns the margin between the menubar's border and its menus.
7JMenu getMenu(int index)
Returns the menu at the specified position in the menu bar.
8int getMenuCount()
Returns the number of items in the menu bar.
9SingleSelectionModel getSelectionModel()
Returns the model object that handles single selections.
10MenuElement[] getSubElements()
Implemented to be a MenuElement -- returns the menus in this menu bar.
11MenuBarUI getUI()
Returns the menubar's current UI.
12String getUIClassID()
Returns the name of the L&F class that renders this component.
13boolean isBorderPainted()
Returns true if the menu bars border should be painted.
14boolean isSelected()
Returns true if the menu bar currently has a component selected.
15void menuSelectionChanged(boolean isIncluded)
Implemented to be a MenuElement -- does nothing.
16protected void paintBorder(Graphics g)
Paints the menubar's border if BorderPainted property is true.
17protected String paramString()
Returns a string representation of this JMenuBar.
18protected boolean processKeyBinding(KeyStroke ks, KeyEvent e, int condition, boolean pressed)
Subclassed to check all the child menus.
19void processKeyEvent(KeyEvent e, MenuElement[] path, MenuSelectionManager manager)
Implemented to be a MenuElement -- does nothing.
20void processMouseEvent(MouseEvent event, MenuElement[] path, MenuSelectionManager manager)
Implemented to be a MenuElement -- does nothing.
21void removeNotify()
Overrides JComponent.removeNotify to unregister this menu bar with the current keyboard manager.
22void setBorderPainted(boolean b)
Sets whether the border should be painted.
23void setHelpMenu(JMenu menu)
Sets the help menu that appears when the user selects the "help" option in the menu bar.
24void setMargin(Insets m)
Sets the margin between the menubar's border and its menus.
25void setSelected(Component sel)
Sets the currently selected component, producing a a change to the selection model.
26void setSelectionModel(SingleSelectionModel model)
Sets the model object to handle single selections.
27void setUI(MenuBarUI ui)
Sets the L&F object that renders this component.
28void updateUI()
Resets the UI property with a value from the current look and feel.

Methods inherited

This class inherits methods from the following classes:

  • javax.swing.JComponent

  • java.awt.Container

  • java.awt.Component

  • java.lang.Object

JMenuBar Example

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

SwingMenuDemo.java
package com.tutorialspoint.gui;

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

public class SwingMenuDemo {
   private JFrame mainFrame;
   private JLabel headerLabel;
   private JLabel statusLabel;
   private JPanel controlPanel; 

   public SwingMenuDemo(){
      prepareGUI();
   }

   public static void main(String[] args){
      SwingMenuDemo  swingMenuDemo = new SwingMenuDemo();     
      swingMenuDemo.showMenuDemo();
   }
   
   private void prepareGUI(){
      mainFrame = new JFrame("Java SWING Examples");
      mainFrame.setSize(400,400);
      mainFrame.setLayout(new GridLayout(3, 1));

      headerLabel = new JLabel("",JLabel.CENTER );
      statusLabel = new JLabel("",JLabel.CENTER);        

      statusLabel.setSize(350,100);
      mainFrame.addWindowListener(new WindowAdapter() {
         public void windowClosing(WindowEvent windowEvent){
            System.exit(0);
         }        
      });    
      controlPanel = new JPanel();
      controlPanel.setLayout(new FlowLayout());

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

   private void showMenuDemo(){
      //create a menu bar
      final JMenuBar menuBar = new JMenuBar();

      //create menus
      JMenu fileMenu = new JMenu("File");
      JMenu editMenu = new JMenu("Edit"); 
      final JMenu aboutMenu = new JMenu("About");
      final JMenu linkMenu = new JMenu("Links");
     
      //create menu items
      JMenuItem newMenuItem = new JMenuItem("New");
      newMenuItem.setMnemonic(KeyEvent.VK_N);
      newMenuItem.setActionCommand("New");

      JMenuItem openMenuItem = new JMenuItem("Open");
      openMenuItem.setActionCommand("Open");

      JMenuItem saveMenuItem = new JMenuItem("Save");
      saveMenuItem.setActionCommand("Save");

      JMenuItem exitMenuItem = new JMenuItem("Exit");
      exitMenuItem.setActionCommand("Exit");

      JMenuItem cutMenuItem = new JMenuItem("Cut");
      cutMenuItem.setActionCommand("Cut");

      JMenuItem copyMenuItem = new JMenuItem("Copy");
      copyMenuItem.setActionCommand("Copy");

      JMenuItem pasteMenuItem = new JMenuItem("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 JCheckBoxMenuItem showWindowMenu = 
         new JCheckBoxMenuItem("Show About", true);
      showWindowMenu.addItemListener(new ItemListener() {
         public void itemStateChanged(ItemEvent e) {
            if(showWindowMenu.getState()){
               menuBar.add(aboutMenu);
            }else{
               menuBar.remove(aboutMenu);
            }
         }
      });

      final JRadioButtonMenuItem showLinksMenu = 
         new JRadioButtonMenuItem("Show Links", true);
      showLinksMenu.addItemListener(new ItemListener() {
         public void itemStateChanged(ItemEvent e) {
            if(menuBar.getMenu(3)!= null){
               menuBar.remove(linkMenu);
               mainFrame.repaint();
            }else{                   
               menuBar.add(linkMenu);
               mainFrame.repaint();
            }
         }
      });

      //add menu items to menus
      fileMenu.add(newMenuItem);
      fileMenu.add(openMenuItem);
      fileMenu.add(saveMenuItem);
      fileMenu.addSeparator();
      fileMenu.add(showWindowMenu);
      fileMenu.addSeparator();
      fileMenu.add(showLinksMenu);       
      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);       
      menuBar.add(linkMenu);

      //add menubar to the frame
      mainFrame.setJMenuBar(menuBar);
      mainFrame.setVisible(true);     
   }

   class MenuItemListener implements ActionListener {
      public void actionPerformed(ActionEvent e) {            
         statusLabel.setText(e.getActionCommand() 
         + " JMenuItem clicked.");
      }    
   }
}

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

D:\SWING>javac com\tutorialspoint\gui\SwingMenuDemo.java

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

D:\SWING>java com.tutorialspoint.gui.SwingMenuDemo

Verify the following output

SWING JMenuBar

SWING JMenuItem Class

Introduction

The JMenuItem class represents the actual item in a menu. All items in a menu should derive from class JMenuItem, or one of its subclasses. By default, it embodies a simple labeled menu item.

Class declaration

Following is the declaration for javax.swing.JMenuItem class:

public class JMenuItem
   extends AbstractButton
      implements Accessible, MenuElement

Class constructors

S.N.Constructor & Description
1JMenuItem()
Creates a JMenuItem with no set text or icon.
2JMenuItem(Action a)
Creates a menu item whose properties are taken from the specified Action.
3JMenuItem(Icon icon)
Creates a JMenuItem with the specified icon.
4JMenuItem(String text)
Creates a JMenuItem with the specified text.
5JMenuItem(String text, Icon icon)
Creates a JMenuItem with the specified text and icon.
6JMenuItem(String text, int mnemonic)
Creates a JMenuItem with the specified text and keyboard mnemonic.

Class methods

S.N.Method & Description
1protected void actionPropertyChanged(Action action, String propertyName)
Updates the button's state in response to property changes in the associated action.
2void addMenuDragMouseListener(MenuDragMouseListener l)
Adds a MenuDragMouseListener to the menu item.
3void addMenuKeyListener(MenuKeyListener l)
Adds a MenuKeyListener to the menu item.
4protected void configurePropertiesFromAction(Action a)
Sets the properties on this button to match those in the specified Action.
5protected void fireMenuDragMouseDragged(MenuDragMouseEvent event)
Notifies all listeners that have registered interest for notification on this event type.
6protected void fireMenuDragMouseEntered(MenuDragMouseEvent event)
Notifies all listeners that have registered interest for notification on this event type.
7protected void fireMenuDragMouseExited(MenuDragMouseEvent event)
Notifies all listeners that have registered interest for notification on this event type.
8protected void fireMenuDragMouseReleased(MenuDragMouseEvent event)
Notifies all listeners that have registered interest for notification on this event type.
9protected void fireMenuKeyPressed(MenuKeyEvent event)
Notifies all listeners that have registered interest for notification on this event type.
10protected void fireMenuKeyReleased(MenuKeyEvent event)
Notifies all listeners that have registered interest for notification on this event type.
11protected void fireMenuKeyTyped(MenuKeyEvent event)
Notifies all listeners that have registered interest for notification on this event type.
12KeyStroke getAccelerator()
Returns the KeyStroke which serves as an accelerator for the menu item.
13AccessibleContext getAccessibleContext()
Returns the AccessibleContext associated with this JMenuItem.
14Component getComponent()
Returns the java.awt.Component used to paint this object.
15MenuDragMouseListener[] getMenuDragMouseListeners()
Returns an array of all the MenuDragMouseListeners added to this JMenuItem with addMenuDragMouseListener().
16MenuKeyListener[] getMenuKeyListeners()
Returns an array of all the MenuKeyListeners added to this JMenuItem with addMenuKeyListener().
17MenuElement[] getSubElements()
This method returns an array containing the sub-menu components for this menu component.
18String getUIClassID()
Returns the suffix used to construct the name of the L&F class used to render this component.
19protected void init(String text, Icon icon)
Initializes the menu item with the specified text and icon.
20boolean isArmed()
Returns whether the menu item is "armed".
21void menuSelectionChanged(boolean isIncluded)
Called by the MenuSelectionManager when the MenuElement is selected or unselected.
22protected String paramString()
Returns a string representation of this JMenuItem.
23void processKeyEvent(KeyEvent e, MenuElement[] path, MenuSelectionManager manager)
Processes a key event forwarded from the MenuSelectionManager and changes the menu selection, if necessary, by using MenuSelectionManager's API.
24void processMenuDragMouseEvent(MenuDragMouseEvent e)
Handles mouse drag in a menu.
25void processMenuKeyEvent(MenuKeyEvent e)
Handles a keystroke in a menu.
26void processMouseEvent(MouseEvent e, MenuElement[] path, MenuSelectionManager manager)
Processes a mouse event forwarded from the MenuSelectionManager and changes the menu selection, if necessary, by using the MenuSelectionManager's API.
27void removeMenuDragMouseListener(MenuDragMouseListener l)
Removes a MenuDragMouseListener from the menu item.
28void removeMenuKeyListener(MenuKeyListener l)
Removes a MenuKeyListener from the menu item.
29void setAccelerator(KeyStroke keyStroke)
Sets the key combination which invokes the menu item's action listeners without navigating the menu hierarchy.
30void setArmed(boolean b)
Identifies the menu item as "armed".
31void setEnabled(boolean b)
Enables or disables the menu item.
32void setModel(ButtonModel newModel)
Sets the model that this button represents.
33void setUI(MenuItemUI ui)
Sets the look and feel object that renders this component.
34void updateUI()
Resets the UI property with a value from the current look and feel.

Methods inherited

This class inherits methods from the following classes:

  • javax.swing.JAbstractButton

  • javax.swing.JComponent

  • java.awt.Container

  • java.awt.Component

  • java.lang.Object

JMenuItem Example

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

SwingMenuDemo.java
package com.tutorialspoint.gui;

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

public class SwingMenuDemo {
   private JFrame mainFrame;
   private JLabel headerLabel;
   private JLabel statusLabel;
   private JPanel controlPanel; 

   public SwingMenuDemo(){
      prepareGUI();
   }

   public static void main(String[] args){
      SwingMenuDemo  swingMenuDemo = new SwingMenuDemo();     
      swingMenuDemo.showMenuDemo();
   }
   
   private void prepareGUI(){
      mainFrame = new JFrame("Java SWING Examples");
      mainFrame.setSize(400,400);
      mainFrame.setLayout(new GridLayout(3, 1));

      headerLabel = new JLabel("",JLabel.CENTER );
      statusLabel = new JLabel("",JLabel.CENTER);        

      statusLabel.setSize(350,100);
      mainFrame.addWindowListener(new WindowAdapter() {
         public void windowClosing(WindowEvent windowEvent){
            System.exit(0);
         }        
      });    
      controlPanel = new JPanel();
      controlPanel.setLayout(new FlowLayout());

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

   private void showMenuDemo(){
      //create a menu bar
      final JMenuBar menuBar = new JMenuBar();

      //create menus
      JMenu fileMenu = new JMenu("File");
      JMenu editMenu = new JMenu("Edit"); 
      final JMenu aboutMenu = new JMenu("About");
      final JMenu linkMenu = new JMenu("Links");
     
      //create menu items
      JMenuItem newMenuItem = new JMenuItem("New");
      newMenuItem.setMnemonic(KeyEvent.VK_N);
      newMenuItem.setActionCommand("New");

      JMenuItem openMenuItem = new JMenuItem("Open");
      openMenuItem.setActionCommand("Open");

      JMenuItem saveMenuItem = new JMenuItem("Save");
      saveMenuItem.setActionCommand("Save");

      JMenuItem exitMenuItem = new JMenuItem("Exit");
      exitMenuItem.setActionCommand("Exit");

      JMenuItem cutMenuItem = new JMenuItem("Cut");
      cutMenuItem.setActionCommand("Cut");

      JMenuItem copyMenuItem = new JMenuItem("Copy");
      copyMenuItem.setActionCommand("Copy");

      JMenuItem pasteMenuItem = new JMenuItem("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 JCheckBoxMenuItem showWindowMenu = 
         new JCheckBoxMenuItem("Show About", true);
      showWindowMenu.addItemListener(new ItemListener() {
         public void itemStateChanged(ItemEvent e) {
            if(showWindowMenu.getState()){
               menuBar.add(aboutMenu);
            }else{
               menuBar.remove(aboutMenu);
            }
         }
      });

      final JRadioButtonMenuItem showLinksMenu = 
         new JRadioButtonMenuItem("Show Links", true);
      showLinksMenu.addItemListener(new ItemListener() {
         public void itemStateChanged(ItemEvent e) {
            if(menuBar.getMenu(3)!= null){
               menuBar.remove(linkMenu);
               mainFrame.repaint();
            }else{                   
               menuBar.add(linkMenu);
               mainFrame.repaint();
            }
         }
      });

      //add menu items to menus
      fileMenu.add(newMenuItem);
      fileMenu.add(openMenuItem);
      fileMenu.add(saveMenuItem);
      fileMenu.addSeparator();
      fileMenu.add(showWindowMenu);
      fileMenu.addSeparator();
      fileMenu.add(showLinksMenu);       
      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);       
      menuBar.add(linkMenu);

      //add menubar to the frame
      mainFrame.setJMenuBar(menuBar);
      mainFrame.setVisible(true);     
   }

   class MenuItemListener implements ActionListener {
      public void actionPerformed(ActionEvent e) {            
         statusLabel.setText(e.getActionCommand() 
         + " JMenuItem clicked.");
      }    
   }
}

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

D:\SWING>javac com\tutorialspoint\gui\SwingMenuDemo.java

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

D:\SWING>java com.tutorialspoint.gui.SwingMenuDemo

Verify the following output. (Click on File Menu. Select any menu item.)

SWING JMenuItem

SWING JMenu Class

Introduction

The Menu class represents pull-down menu component which is deployed from a menu bar.

Class declaration

Following is the declaration for javax.swing.JMenu class:

public class JMenu
   extends JMenuItem
      implements Accessible, MenuElement

Field

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

  • protected JMenu.WinListener popupListener -- The window-closing listener for the popup.

Class constructors

S.N.Constructor & Description
1JMenu()
Constructs a new JMenu with no text.
2JMenu(Action a)
Constructs a menu whose properties are taken from the Action supplied.
3JMenu(String s)
Constructs a new JMenu with the supplied string as its text.
4JMenu(String s, boolean b)
Constructs a new JMenu with the supplied string as its text and specified as a tear-off menu or not.

Class methods

S.N.Method & Description
1JMenuItem add(Action a)
Creates a new menu item attached to the specified Action object and appends it to the end of this menu.
2Component add(Component c)
Appends a component to the end of this menu.
3Component add(Component c, int index)
Adds the specified component to this container at the given position.
4JMenuItem add(JMenuItem menuItem)
Appends a menu item to the end of this menu.
5JMenuItem add(String s)
Creates a new menu item with the specified text and appends it to the end of this menu.
6void addMenuListener(MenuListener l) Adds a listener for menu events.
7void addSeparator()
Appends a new separator to the end of the menu.
8void applyComponentOrientation(ComponentOrientation o)
Sets the ComponentOrientation property of this menu and all components contained within it.
9protected PropertyChangeListener createActionChangeListener(JMenuItem b)
Returns a properly configured PropertyChangeListener which updates the control as changes to the Action occur.
10protected JMenuItem createActionComponent(Action a)
Factory method which creates the JMenuItem for Actions added to the JMenu.
11protected JMenu.WinListener createWinListener(JPopupMenu p)
Creates a window-closing listener for the popup.
12void doClick(int pressTime)
Programmatically performs a "click".
13protected void fireMenuCanceled()
Notifies all listeners that have registered interest for notification on this event type.
14protected void fireMenuDeselected()
Notifies all listeners that have registered interest for notification on this event type.
15protected void fireMenuSelected()
Notifies all listeners that have registered interest for notification on this event type.
16AccessibleContext getAccessibleContext()
Gets the AccessibleContext associated with this JMenu.
17Component getComponent()
Returns the java.awt.Component used to paint this MenuElement.
18int getDelay()
Returns the suggested delay, in milliseconds, before submenus are popped up or down.
19JMenuItem getItem(int pos)
Returns the JMenuItem at the specified position.
20int getItemCount()
Returns the number of items on the menu, including separators.
21Component getMenuComponent(int n)
Returns the component at position n.
22int getMenuComponentCount()
Returns the number of components on the menu.
23Component[] getMenuComponents()
Returns an array of Components of the menu's subcomponents.
24MenuListener[] getMenuListeners()
Returns an array of all the MenuListeners added to this JMenu with addMenuListener().
25JPopupMenu getPopupMenu()
Returns the popupmenu associated with this menu.
26protected Point getPopupMenuOrigin()
Computes the origin for the JMenu's popup menu.
27MenuElement[] getSubElements()
Returns an array of MenuElements containing the submenu for this menu component.
28String getUIClassID()
Returns the name of the L&F class that renders this component.
29JMenuItem insert(Action a, int pos)
Inserts a new menu item attached to the specified Action object at a given position.
30JMenuItem insert(JMenuItem mi, int pos)
Inserts the specified JMenuitem at a given position.
31void insert(String s, int pos)
Inserts a new menu item with the specified text at a given position.
32void insertSeparator(int index)
Inserts a separator at the specified position.
33boolean isMenuComponent(Component c)
Returns true if the specified component exists in the submenu hierarchy.
34boolean isPopupMenuVisible()
Returns true if the menu's popup window is visible.
35boolean isSelected()
Returns true if the menu is currently selected (highlighted).
36boolean isTearOff()
Returns true if the menu can be torn off.
37boolean isTopLevelMenu()
Returns true if the menu is a 'top-level menu', that is, if it is the direct child of a menubar.
38void menuSelectionChanged(boolean isIncluded)
Messaged when the menubar selection changes to activate or deactivate this menu.
39protected String paramString()
Returns a string representation of this JMenu.
40protected void processKeyEvent(KeyEvent evt)
Processes key stroke events such as mnemonics and accelerators.
41void remove(Component c)
Removes the component c from this menu.
42void remove(int pos)
Removes the menu item at the specified index from this menu.
43void remove(JMenuItem item)
Removes the specified menu item from this menu.
44void removeAll()
Removes all menu items from this menu.
45void removeMenuListener(MenuListener l)
Removes a listener for menu events.
46void setAccelerator(KeyStroke keyStroke)
setAccelerator is not defined for JMenu.
47void setComponentOrientation(ComponentOrientation o)
Sets the language-sensitive orientation that is to be used to order the elements or text within this component.
48void setDelay(int d)
Sets the suggested delay before the menu's PopupMenu is popped up or down.
49void setMenuLocation(int x, int y)
Sets the location of the popup component.
50void setModel(ButtonModel newModel)
Sets the data model for the "menu button" -- the label that the user clicks to open or close the menu.
51void setPopupMenuVisible(boolean b)
Sets the visibility of the menu's popup.
52void setSelected(boolean b)
Sets the selection status of the menu.
53void updateUI()
Resets the UI property with a value from the current look and feel.

Methods inherited

This class inherits methods from the following classes:

  • javax.swing.JAbstractButton

  • javax.swing.JComponent

  • java.awt.Container

  • java.awt.Component

  • java.lang.Object

JMenu Example

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

SwingMenuDemo.java
package com.tutorialspoint.gui;

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

public class SwingMenuDemo {
   private JFrame mainFrame;
   private JLabel headerLabel;
   private JLabel statusLabel;
   private JPanel controlPanel; 

   public SwingMenuDemo(){
      prepareGUI();
   }

   public static void main(String[] args){
      SwingMenuDemo  swingMenuDemo = new SwingMenuDemo();     
      swingMenuDemo.showMenuDemo();
   }
   
   private void prepareGUI(){
      mainFrame = new JFrame("Java SWING Examples");
      mainFrame.setSize(400,400);
      mainFrame.setLayout(new GridLayout(3, 1));

      headerLabel = new JLabel("",JLabel.CENTER );
      statusLabel = new JLabel("",JLabel.CENTER);        

      statusLabel.setSize(350,100);
      mainFrame.addWindowListener(new WindowAdapter() {
         public void windowClosing(WindowEvent windowEvent){
            System.exit(0);
         }        
      });    
      controlPanel = new JPanel();
      controlPanel.setLayout(new FlowLayout());

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

   private void showMenuDemo(){
      //create a menu bar
      final JMenuBar menuBar = new JMenuBar();

      //create menus
      JMenu fileMenu = new JMenu("File");
      JMenu editMenu = new JMenu("Edit"); 
      final JMenu aboutMenu = new JMenu("About");
      final JMenu linkMenu = new JMenu("Links");
     
      //create menu items
      JMenuItem newMenuItem = new JMenuItem("New");
      newMenuItem.setMnemonic(KeyEvent.VK_N);
      newMenuItem.setActionCommand("New");

      JMenuItem openMenuItem = new JMenuItem("Open");
      openMenuItem.setActionCommand("Open");

      JMenuItem saveMenuItem = new JMenuItem("Save");
      saveMenuItem.setActionCommand("Save");

      JMenuItem exitMenuItem = new JMenuItem("Exit");
      exitMenuItem.setActionCommand("Exit");

      JMenuItem cutMenuItem = new JMenuItem("Cut");
      cutMenuItem.setActionCommand("Cut");

      JMenuItem copyMenuItem = new JMenuItem("Copy");
      copyMenuItem.setActionCommand("Copy");

      JMenuItem pasteMenuItem = new JMenuItem("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 JCheckBoxMenuItem showWindowMenu = 
         new JCheckBoxMenuItem("Show About", true);
      showWindowMenu.addItemListener(new ItemListener() {
         public void itemStateChanged(ItemEvent e) {
            if(showWindowMenu.getState()){
               menuBar.add(aboutMenu);
            }else{
               menuBar.remove(aboutMenu);
            }
         }
      });

      final JRadioButtonMenuItem showLinksMenu = 
         new JRadioButtonMenuItem("Show Links", true);
      showLinksMenu.addItemListener(new ItemListener() {
         public void itemStateChanged(ItemEvent e) {
            if(menuBar.getMenu(3)!= null){
               menuBar.remove(linkMenu);
               mainFrame.repaint();
            }else{                   
               menuBar.add(linkMenu);
               mainFrame.repaint();
            }
         }
      });

      //add menu items to menus
      fileMenu.add(newMenuItem);
      fileMenu.add(openMenuItem);
      fileMenu.add(saveMenuItem);
      fileMenu.addSeparator();
      fileMenu.add(showWindowMenu);
      fileMenu.addSeparator();
      fileMenu.add(showLinksMenu);       
      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);       
      menuBar.add(linkMenu);

      //add menubar to the frame
      mainFrame.setJMenuBar(menuBar);
      mainFrame.setVisible(true);     
   }

   class MenuItemListener implements ActionListener {
      public void actionPerformed(ActionEvent e) {            
         statusLabel.setText(e.getActionCommand() 
         + " JMenuItem clicked.");
      }    
   }
}

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

D:\SWING>javac com\tutorialspoint\gui\SwingMenuDemo.java

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

D:\SWING>java com.tutorialspoint.gui.SwingMenuDemo

Verify the following output. (Click on File Menu.)

SWING JMenu

SWING JCheckboxMenuItem Class

Introduction

The JCheckboxMenuItem 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 javax.swing.JCheckBoxMenuItem class:

public class JCheckBoxMenuItem
   extends JMenuItem
      implements SwingConstants, Accessible

Class constructors

S.N.Constructor & Description
1JCheckboxMenuItem()
Creates an initially unselected check box menu item with no set text or icon.
2JCheckboxMenuItem(Action a)
Creates a menu item whose properties are taken from the Action supplied.
3JCheckboxMenuItem(Icon icon)
Creates an initially unselected check box menu item with an icon.
4JCheckboxMenuItem(String text)
Creates an initially unselected check box menu item with text.
5JCheckboxMenuItem(String text, boolean b)
Creates a check box menu item with the specified text and selection state.
6JCheckboxMenuItem(String text, Icon icon)
Creates an initially unselected check box menu item with the specified text and icon.
7JCheckboxMenuItem(String text, Icon icon, boolean b)
Creates a check box menu item with the specified text, icon, and selection state.

Class methods

S.N.Method & Description
1AccessibleContext getAccessibleContext()
Gets the AccessibleContext associated with this JCheckBoxMenuItem.
2Object[] getSelectedObjects()
Returns an array (length 1) containing the check box menu item label or null if the check box is not selected.
3boolean getState()
Returns the selected-state of the item.
4String getUIClassID()
Returns the name of the L&F class that renders this component.
5protected String paramString()
Returns a string representation of this JCheckBoxMenuItem.
6void setState(boolean b)
Sets the selected-state of the item.

Methods inherited

This class inherits methods from the following classes:

  • javax.swing.JMenuItem

  • javax.swing.JAbstractButton

  • javax.swing.JComponent

  • java.awt.Container

  • java.awt.Component

  • java.lang.Object

JCheckboxMenuItem Example

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

SwingMenuDemo.java
package com.tutorialspoint.gui;

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

public class SwingMenuDemo {
   private JFrame mainFrame;
   private JLabel headerLabel;
   private JLabel statusLabel;
   private JPanel controlPanel; 

   public SwingMenuDemo(){
      prepareGUI();
   }

   public static void main(String[] args){
      SwingMenuDemo  swingMenuDemo = new SwingMenuDemo();     
      swingMenuDemo.showMenuDemo();
   }
   
   private void prepareGUI(){
      mainFrame = new JFrame("Java SWING Examples");
      mainFrame.setSize(400,400);
      mainFrame.setLayout(new GridLayout(3, 1));

      headerLabel = new JLabel("",JLabel.CENTER );
      statusLabel = new JLabel("",JLabel.CENTER);        

      statusLabel.setSize(350,100);
      mainFrame.addWindowListener(new WindowAdapter() {
         public void windowClosing(WindowEvent windowEvent){
            System.exit(0);
         }        
      });    
      controlPanel = new JPanel();
      controlPanel.setLayout(new FlowLayout());

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

   private void showMenuDemo(){
      //create a menu bar
      final JMenuBar menuBar = new JMenuBar();

      //create menus
      JMenu fileMenu = new JMenu("File");
      JMenu editMenu = new JMenu("Edit"); 
      final JMenu aboutMenu = new JMenu("About");
      final JMenu linkMenu = new JMenu("Links");
     
      //create menu items
      JMenuItem newMenuItem = new JMenuItem("New");
      newMenuItem.setMnemonic(KeyEvent.VK_N);
      newMenuItem.setActionCommand("New");

      JMenuItem openMenuItem = new JMenuItem("Open");
      openMenuItem.setActionCommand("Open");

      JMenuItem saveMenuItem = new JMenuItem("Save");
      saveMenuItem.setActionCommand("Save");

      JMenuItem exitMenuItem = new JMenuItem("Exit");
      exitMenuItem.setActionCommand("Exit");

      JMenuItem cutMenuItem = new JMenuItem("Cut");
      cutMenuItem.setActionCommand("Cut");

      JMenuItem copyMenuItem = new JMenuItem("Copy");
      copyMenuItem.setActionCommand("Copy");

      JMenuItem pasteMenuItem = new JMenuItem("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 JCheckBoxMenuItem showWindowMenu = 
         new JCheckBoxMenuItem("Show About", true);
      showWindowMenu.addItemListener(new ItemListener() {
         public void itemStateChanged(ItemEvent e) {
            if(showWindowMenu.getState()){
               menuBar.add(aboutMenu);
            }else{
               menuBar.remove(aboutMenu);
            }
         }
      });

      final JRadioButtonMenuItem showLinksMenu = 
         new JRadioButtonMenuItem("Show Links", true);
      showLinksMenu.addItemListener(new ItemListener() {
         public void itemStateChanged(ItemEvent e) {
            if(menuBar.getMenu(3)!= null){
               menuBar.remove(linkMenu);
               mainFrame.repaint();
            }else{                   
               menuBar.add(linkMenu);
               mainFrame.repaint();
            }
         }
      });

      //add menu items to menus
      fileMenu.add(newMenuItem);
      fileMenu.add(openMenuItem);
      fileMenu.add(saveMenuItem);
      fileMenu.addSeparator();
      fileMenu.add(showWindowMenu);
      fileMenu.addSeparator();
      fileMenu.add(showLinksMenu);       
      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);       
      menuBar.add(linkMenu);

      //add menubar to the frame
      mainFrame.setJMenuBar(menuBar);
      mainFrame.setVisible(true);     
   }

   class MenuItemListener implements ActionListener {
      public void actionPerformed(ActionEvent e) {            
         statusLabel.setText(e.getActionCommand() 
         + " JMenuItem clicked.");
      }    
   }
}

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

D:\SWING>javac com\tutorialspoint\gui\SwingMenuDemo.java

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

D:\SWING>java com.tutorialspoint.gui.SwingMenuDemo

Verify the following output. (Click on File Menu. Unselect "Show About" menu item.)

SWING JCheckboxMenuItem

SWING JRadioButtonMenuItem Class

Introduction

The JRadioButtonMenuItem 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 javax.swing.JRadioButtonMenuItem class:

public class JRadioButtonMenuItem
   extends JMenuItem
      implements Accessible

Class constructors

S.N.Constructor & Description
1JRadioButtonMenuItem()
Creates a JRadioButtonMenuItem with no set text or icon.
2JRadioButtonMenuItem(Action a)
Creates a radio button menu item whose properties are taken from the Action supplied.
3JRadioButtonMenuItem(Icon icon)
Creates a JRadioButtonMenuItem with an icon.
4JRadioButtonMenuItem(Icon icon, boolean selected)
Creates a radio button menu item with the specified image and selection state, but no text.
5JRadioButtonMenuItem(String text)
Creates a JRadioButtonMenuItem with text.
6JRadioButtonMenuItem(String text, boolean selected)
Creates a radio button menu item with the specified text and selection state.
7JRadioButtonMenuItem(String text, Icon icon)
Creates a radio button menu item with the specified text and Icon.
8JRadioButtonMenuItem(String text, Icon icon, boolean selected)
Creates a radio button menu item that has the specified text, image, and selection state.

Class methods

S.N.Method & Description
1AccessibleContext getAccessibleContext()
Gets the AccessibleContext associated with this JRadioButtonMenuItem.
2String getUIClassID()
Returns the name of the L&F class that renders this component.
3protected String paramString()
Returns a string representation of this JRadioButtonMenuItem.

Methods inherited

This class inherits methods from the following classes:

  • javax.swing.JMenuItem

  • javax.swing.JAbstractButton

  • javax.swing.JComponent

  • java.awt.Container

  • java.awt.Component

  • java.lang.Object

JRadioButtonMenuItem Example

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

SwingMenuDemo.java
package com.tutorialspoint.gui;

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

public class SwingMenuDemo {
   private JFrame mainFrame;
   private JLabel headerLabel;
   private JLabel statusLabel;
   private JPanel controlPanel; 

   public SwingMenuDemo(){
      prepareGUI();
   }

   public static void main(String[] args){
      SwingMenuDemo  swingMenuDemo = new SwingMenuDemo();     
      swingMenuDemo.showMenuDemo();
   }
   
   private void prepareGUI(){
      mainFrame = new JFrame("Java SWING Examples");
      mainFrame.setSize(400,400);
      mainFrame.setLayout(new GridLayout(3, 1));

      headerLabel = new JLabel("",JLabel.CENTER );
      statusLabel = new JLabel("",JLabel.CENTER);        

      statusLabel.setSize(350,100);
      mainFrame.addWindowListener(new WindowAdapter() {
         public void windowClosing(WindowEvent windowEvent){
            System.exit(0);
         }        
      });    
      controlPanel = new JPanel();
      controlPanel.setLayout(new FlowLayout());

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

   private void showMenuDemo(){
      //create a menu bar
      final JMenuBar menuBar = new JMenuBar();

      //create menus
      JMenu fileMenu = new JMenu("File");
      JMenu editMenu = new JMenu("Edit"); 
      final JMenu aboutMenu = new JMenu("About");
      final JMenu linkMenu = new JMenu("Links");
     
      //create menu items
      JMenuItem newMenuItem = new JMenuItem("New");
      newMenuItem.setMnemonic(KeyEvent.VK_N);
      newMenuItem.setActionCommand("New");

      JMenuItem openMenuItem = new JMenuItem("Open");
      openMenuItem.setActionCommand("Open");

      JMenuItem saveMenuItem = new JMenuItem("Save");
      saveMenuItem.setActionCommand("Save");

      JMenuItem exitMenuItem = new JMenuItem("Exit");
      exitMenuItem.setActionCommand("Exit");

      JMenuItem cutMenuItem = new JMenuItem("Cut");
      cutMenuItem.setActionCommand("Cut");

      JMenuItem copyMenuItem = new JMenuItem("Copy");
      copyMenuItem.setActionCommand("Copy");

      JMenuItem pasteMenuItem = new JMenuItem("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 JCheckBoxMenuItem showWindowMenu = 
         new JCheckBoxMenuItem("Show About", true);
      showWindowMenu.addItemListener(new ItemListener() {
         public void itemStateChanged(ItemEvent e) {
            if(showWindowMenu.getState()){
               menuBar.add(aboutMenu);
            }else{
               menuBar.remove(aboutMenu);
            }
         }
      });

      final JRadioButtonMenuItem showLinksMenu = 
         new JRadioButtonMenuItem("Show Links", true);
      showLinksMenu.addItemListener(new ItemListener() {
         public void itemStateChanged(ItemEvent e) {
            if(menuBar.getMenu(3)!= null){
               menuBar.remove(linkMenu);
               mainFrame.repaint();
            }else{                   
               menuBar.add(linkMenu);
               mainFrame.repaint();
            }
         }
      });

      //add menu items to menus
      fileMenu.add(newMenuItem);
      fileMenu.add(openMenuItem);
      fileMenu.add(saveMenuItem);
      fileMenu.addSeparator();
      fileMenu.add(showWindowMenu);
      fileMenu.addSeparator();
      fileMenu.add(showLinksMenu);       
      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);       
      menuBar.add(linkMenu);

      //add menubar to the frame
      mainFrame.setJMenuBar(menuBar);
      mainFrame.setVisible(true);     
   }

   class MenuItemListener implements ActionListener {
      public void actionPerformed(ActionEvent e) {            
         statusLabel.setText(e.getActionCommand() 
         + " JMenuItem clicked.");
      }    
   }
}

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

D:\SWING>javac com\tutorialspoint\gui\SwingMenuDemo.java

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

D:\SWING>java com.tutorialspoint.gui.SwingMenuDemo

Verify the following output. (Click on File Menu. Unselect "Show Link" menu item.)

SWING JRadioButtonMenuItem

SWING JPopupMenu 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 javax.swing.JPopupMenu class:

public class JPopupMenu
   extends JComponent
      implements Accessible, MenuElement

Class constructors

S.N.Constructor & Description
1JPopupMenu()
Constructs a JPopupMenu without an "invoker".
2JPopupMenu(String label)
Constructs a JPopupMenu with the specified title.

Class methods

S.N.Method & Description
1JMenuItem add(Action a)
Appends a new menu item to the end of the menu which dispatches the specified Action object.
2JMenuItem add(JMenuItem menuItem)
Appends the specified menu item to the end of this menu.
3JMenuItem add(String s)
Creates a new menu item with the specified text and appends it to the end of this menu.
4void addMenuKeyListener(MenuKeyListener l)
Adds a MenuKeyListener to the popup menu.
5void addPopupMenuListener(PopupMenuListener l)
Adds a PopupMenu listener.
6void addSeparator()
Appends a new separator at the end of the menu.
7protected PropertyChangeListener createActionChangeListener(JMenuItem b)
Returns a properly configured PropertyChangeListener which updates the control as changes to the Action occur.
8protected JMenuItem createActionComponent(Action a)
Factory method which creates the JMenuItem for Actions added to the JPopupMenu.
9protected void firePopupMenuCanceled()
Notifies PopupMenuListeners that this popup menu is cancelled.
10protected void firePopupMenuWillBecomeInvisible()
Notifies PopupMenuListeners that this popup menu will become invisible.
11protected void firePopupMenuWillBecomeVisible()
Notifies PopupMenuListeners that this popup menu will become visible.
12AccessibleContext getAccessibleContext()
Gets the AccessibleContext associated with this JPopupMenu.
13Component getComponent()
Returns this JPopupMenu component.
14Component getComponentAtIndex(int i)
Deprecated. replaced by Container.getComponent(int)
15int getComponentIndex(Component c)
Returns the index of the specified component.
16static boolean getDefaultLightWeightPopupEnabled()
Gets the defaultLightWeightPopupEnabled property, which by default is true.
17Component getInvoker()
Returns the component which is the 'invoker' of this popup menu.
18String getLabel()
Returns the popup menu's label
19Insets getMargin()
Returns the margin, in pixels, between the popup menu's border and its containees.
20MenuKeyListener[] getMenuKeyListeners()
Returns an array of all the MenuKeyListeners added to this JPopupMenu with addMenuKeyListener().
21PopupMenuListener[] getPopupMenuListeners()
Returns an array of all the PopupMenuListeners added to this JMenuItem with addPopupMenuListener().
22SingleSelectionModel getSelectionModel()
Returns the model object that handles single selections.
23MenuElement[] getSubElements()
Returns an array of MenuElements containing the submenu for this menu component.
24PopupMenuUI getUI()
Returns the look and feel (L&F) object that renders this component.
25String getUIClassID()
Returns the name of the L&F class that renders this component.
26void insert(Action a, int index)
Inserts a menu item for the specified Action object at a given position.
27void insert(Component component, int index)
Inserts the specified component into the menu at a given position.
28boolean isBorderPainted()
Checks whether the border should be painted.
29boolean isLightWeightPopupEnabled()
Gets the lightWeightPopupEnabled property.
30boolean isPopupTrigger(MouseEvent e)
Returns true if the MouseEvent is considered a popup trigger by the JPopupMenu's currently installed UI.
31boolean isVisible()
Returns true if the popup menu is visible (currently being displayed).
32void menuSelectionChanged(boolean isIncluded)
Messaged when the menubar selection changes to activate or deactivate this menu.
33void pack()
Lays out the container so that it uses the minimum space needed to display its contents.
34protected void paintBorder(Graphics g)
Paints the popup menu's border if the borderPainted property is true.
35protected String paramString()
Returns a string representation of this JPopupMenu.
36protected void processFocusEvent(FocusEvent evt)
Processes focus events occurring on this component by dispatching them to any registered FocusListener objects.
37protected void processKeyEvent(KeyEvent evt)
Processes key stroke events such as mnemonics and accelerators.
38void processKeyEvent(KeyEvent e, MenuElement[] path, MenuSelectionManager manager)
Processes a key event forwarded from the MenuSelectionManager and changes the menu selection, if necessary, by using MenuSelectionManager's API.
39void processMouseEvent(MouseEvent event, MenuElement[] path, MenuSelectionManager manager)
This method is required to conform to the MenuElement interface, but it not implemented.
40void remove(int pos)
Removes the component at the specified index from this popup menu.
41void removeMenuKeyListener(MenuKeyListener l)
Removes a MenuKeyListener from the popup menu.
42void removePopupMenuListener(PopupMenuListener l)
Removes a PopupMenu listener.
43void setBorderPainted(boolean b)
Sets whether the border should be painted.
44static void setDefaultLightWeightPopupEnabled(boolean aFlag)
Sets the default value of the lightWeightPopupEnabled property.
45void setInvoker(Component invoker)
Sets the invoker of this popup menu -- the component in which the popup menu menu is to be displayed.
46void setLabel(String label)
Sets the popup menu's label.
47void setLightWeightPopupEnabled(boolean aFlag)
Sets the value of the lightWeightPopupEnabled property, which by default is true.
48void setLocation(int x, int y)
Sets the location of the upper left corner of the popup menu using x, y coordinates.
49void setPopupSize(Dimension d)
Sets the size of the Popup window using a Dimension object.
50void setPopupSize(int width, int height)
Sets the size of the Popup window to the specified width and height.
51void setSelected(Component sel)
Sets the currently selected component, This will result in a change to the selection model.
52void setSelectionModel(SingleSelectionModel model)
Sets the model object to handle single selections.
53void setUI(PopupMenuUI ui)
Sets the L&F object that renders this component.
54void setVisible(boolean b)
Sets the visibility of the popup menu.
55void show(Component invoker, int x, int y)
Displays the popup menu at the position x,y in the coordinate space of the component invoker.
56void updateUI()
Resets the UI property to a value from the current look and feel.

Methods inherited

This class inherits methods from the following classes:

  • javax.swing.JComponent

  • java.awt.Container

  • java.awt.Component

  • java.lang.Object

JPopupMenu Example

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

SwingMenuDemo.java
package com.tutorialspoint.gui;

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

public class SwingMenuDemo {
   private JFrame mainFrame;
   private JLabel headerLabel;
   private JLabel statusLabel;
   private JPanel controlPanel; 

   public SwingMenuDemo(){
      prepareGUI();
   }

   public static void main(String[] args){
      SwingMenuDemo  swingMenuDemo = new SwingMenuDemo();     
      swingMenuDemo.showPopupMenuDemo();
   }
   
   private void prepareGUI(){
      mainFrame = new JFrame("Java SWING Examples");
      mainFrame.setSize(400,400);
      mainFrame.setLayout(new GridLayout(3, 1));

      headerLabel = new JLabel("",JLabel.CENTER );
      statusLabel = new JLabel("",JLabel.CENTER);        

      statusLabel.setSize(350,100);
      mainFrame.addWindowListener(new WindowAdapter() {
         public void windowClosing(WindowEvent windowEvent){
            System.exit(0);
         }        
      });    
      controlPanel = new JPanel();
      controlPanel.setLayout(new FlowLayout());

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

   private void showPopupMenuDemo(){
      final JPopupMenu editMenu = new JPopupMenu("Edit"); 

      JMenuItem cutMenuItem = new JMenuItem("Cut");
      cutMenuItem.setActionCommand("Cut");

      JMenuItem copyMenuItem = new JMenuItem("Copy");
      copyMenuItem.setActionCommand("Copy");

      JMenuItem pasteMenuItem = new JMenuItem("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);   

      mainFrame.addMouseListener(new MouseAdapter() {
         public void mouseClicked(MouseEvent e) {            
            editMenu.show(mainFrame, e.getX(), e.getY());
         }               
      });
      mainFrame.add(editMenu); 
      mainFrame.setVisible(true);
   }
}

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

D:\SWING>javac com\tutorialspoint\gui\SwingMenuDemo.java

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

D:\SWING>java com.tutorialspoint.gui.SwingMenuDemo

Verify the following output. (Click in the middle on the screen.)

SWING JPopupMenu

SWING Containers

Containers are integral part of SWING 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 Container. For example JPanel, JFrame and JWindow.

  • Container can add only Component to itself.

  • A default layout is present in each container which can be overridden using setLayout method.

SWING JPanel Class

Introduction

The class JPanel is a generic lightweight container.

Class declaration

Following is the declaration for javax.swing.JPanel class:

public class JPanel
   extends JComponent
      implements Accessible

Class constructors

S.N.Constructor & Description
1JPanel()
Creates a new JPanel with a double buffer and a flow layout.
2JPanel(boolean isDoubleBuffered)
Creates a new JPanel with FlowLayout and the specified buffering strategy.
3JPanel(LayoutManager layout)
Create a new buffered JPanel with the specified layout manager.
4JPanel(LayoutManager layout, boolean isDoubleBuffered)
Creates a new JPanel with the specified layout manager and buffering strategy.

Class methods

S.N.Method & Description
1AccessibleContext getAccessibleContext()
Gets the AccessibleContext associated with this JPanel.
2PanelUI getUI()
Returns the look and feel (L&F) object that renders this component.
3String getUIClassID()
Returns a string that specifies the name of the L&F class that renders this component.
4protected String paramString()
Returns a string representation of this JPanel.
5void setUI(PanelUI ui)
Sets the look and feel (L&F) object that renders this component.
6void updateUI()
Resets the UI property with a value from the current look and feel.

Methods inherited

This class inherits methods from the following classes:

  • javax.swing.JComponent

  • java.awt.Container

  • java.awt.Component

  • java.lang.Object

JPanel Example

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

SwingContainerDemo.java
package com.tutorialspoint.gui;

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;

public class SwingContainerDemo {
   private JFrame mainFrame;
   private JLabel headerLabel;
   private JLabel statusLabel;
   private JPanel controlPanel;
   private JLabel msglabel;

   public SwingContainerDemo(){
      prepareGUI();
   }

   public static void main(String[] args){
      SwingContainerDemo  swingContainerDemo = new SwingContainerDemo();  
      swingContainerDemo.showJPanelDemo();
   }

   private void prepareGUI(){
      mainFrame = new JFrame("Java Swing 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 JLabel("", JLabel.CENTER);        
      statusLabel = new JLabel("",JLabel.CENTER);    

      statusLabel.setSize(350,100);

      msglabel = new JLabel("Welcome to TutorialsPoint SWING Tutorial."
         , JLabel.CENTER);

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

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


   private void showJPanelDemo(){
      headerLabel.setText("Container in action: JPanel");      

      JPanel panel = new JPanel();
      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:/ > SWING and type the following command.

D:\SWING>javac com\tutorialspoint\gui\SwingContainerDemo.java

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

D:\SWING>java com.tutorialspoint.gui.SwingContainerDemo

Verify the following output

SWING JPanel

SWING JFrame Class

Introduction

The class JFrame is an extended version of java.awt.Frame that adds support for the JFC/Swing component architecture.

Class declaration

Following is the declaration for javax.swing.JFrame class:

public class JFrame
   extends Frame
      implements WindowConstants, Accessible
         , RootPaneContainer

Field

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

  • protected AccessibleContext accessibleContext --The accessible context property.

  • static int EXIT_ON_CLOSE --The exit application default window close operation.

  • protected JRootPane rootPane --The JRootPane instance that manages the contentPane and optional menuBar for this frame, as well as the glassPane.

  • protected boolean rootPaneCheckingEnabled --If true then calls to add and setLayout will be forwarded to the contentPane.

Class constructors

S.N.Constructor & Description
1JFrame()
Constructs a new frame that is initially invisible.
2JFrame(GraphicsConfiguration gc)
Creates a Frame in the specified GraphicsConfiguration of a screen device and a blank title.
3JFrame(String title)
Creates a new, initially invisible Frame with the specified title.
4JFrame(String title, GraphicsConfiguration gc)
Creates a JFrame with the specified title and the specified GraphicsConfiguration of a screen device.

Class methods

S.N.Method & Description
1protected void addImpl(Component comp, Object constraints, int index)
Adds the specified child Component.
2protected JRootPane createRootPane()
Called by the constructor methods to create the default rootPane.
3protected void frameInit()
Called by the constructors to init the JFrame properly.
4AccessibleContext getAccessibleContext()
Gets the AccessibleContext associated with this JFrame.
5Container getContentPane()
Returns the contentPane object for this frame.
6int getDefaultCloseOperation()
Returns the operation that occurs when the user initiates a "close" on this frame.
7Component getGlassPane()
Returns the glassPane object for this frame.
8Graphics getGraphics()
Creates a graphics context for this component.
9JMenuBar getJMenuBar()
Returns the menubar set on this frame.
10JLayeredPane getLayeredPane()
Returns the layeredPane object for this frame.
11JRootPane getRootPane()
Returns the rootPane object for this frame.
12TransferHandler getTransferHandler()
Gets the transferHandler property.
13static boolean isDefaultLookAndFeelDecorated()
Returns true if newly created JFrames should have their Window decorations provided by the current look and feel.
14protected boolean isRootPaneCheckingEnabled()
Returns whether calls to add and setLayout are forwarded to the contentPane.
15protected String paramString()
Returns a string representation of this JFrame.
16protected void processWindowEvent(WindowEvent e)
Processes window events occurring on this component.
17void remove(Component comp)
Removes the specified component from the container.
18void repaint(long time, int x, int y, int width, int height)
Repaints the specified rectangle of this component within time milliseconds.
19void setContentPane(Container contentPane)
Sets the contentPane property.
20void setDefaultCloseOperation(int operation)
Sets the operation that will happen by default when the user initiates a "close" on this frame.
21static void setDefaultLookAndFeelDecorated(boolean defaultLookAndFeelDecorated)
Provides a hint as to whether or not newly created JFrames should have their Window decorations (such as borders, widgets to close the window, title...) provided by the current look and feel.
22void setGlassPane(Component glassPane)
Sets the glassPane property.
23void setIconImage(Image image)
Sets the image to be displayed as the icon for this window.
24void setJMenuBar(JMenuBar menubar)
Sets the menubar for this frame.
25void setLayeredPane(JLayeredPane layeredPane)
Sets the layeredPane property.
26void setLayout(LayoutManager manager)
Sets the LayoutManager.
27protected void setRootPane(JRootPane root)
Sets the rootPane property.
28protected void setRootPaneCheckingEnabled(boolean enabled)
Sets whether calls to add and setLayout are forwarded to the contentPane.
29void setTransferHandler(TransferHandler newHandler)
Sets the transferHandler property, which is a mechanism to support transfer of data into this component.
30void update(Graphics g)
Just calls paint(g).

Methods inherited

This class inherits methods from the following classes:

  • java.awt.Frame

  • java.awt.Window

  • java.awt.Container

  • java.awt.Component

  • java.lang.Object

JFrame Example

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

SwingContainerDemo.java
package com.tutorialspoint.gui;

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;

public class SwingContainerDemo {
   private JFrame mainFrame;
   private JLabel headerLabel;
   private JLabel statusLabel;
   private JPanel controlPanel;
   private JLabel msglabel;

   public SwingContainerDemo(){
      prepareGUI();
   }

   public static void main(String[] args){
      SwingContainerDemo  swingContainerDemo = new SwingContainerDemo();  
      swingContainerDemo.showJFrameDemo();
   }

   private void prepareGUI(){
      mainFrame = new JFrame("Java Swing 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 JLabel("", JLabel.CENTER);        
      statusLabel = new JLabel("",JLabel.CENTER);    

      statusLabel.setSize(350,100);

      msglabel = new JLabel("Welcome to TutorialsPoint SWING Tutorial."
         , JLabel.CENTER);

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

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

   private void showJFrameDemo(){
      headerLabel.setText("Container in action: JFrame");   

      final JFrame frame = new JFrame();
      frame.setSize(300, 300);
      frame.setLayout(new FlowLayout());       
      frame.add(msglabel);
      frame.addWindowListener(new WindowAdapter() {
         public void windowClosing(WindowEvent windowEvent){
            frame.dispose();
         }        
      });    
      JButton okButton = new JButton("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:/ > SWING and type the following command.

D:\SWING>javac com\tutorialspoint\gui\SwingContainerDemo.java

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

D:\SWING>java com.tutorialspoint.gui.SwingContainerDemo

Verify the following output

SWING JFrame

SWING JWindow Class

Introduction

The class JWindow is a container that can be displayed but does not have the title bar or window-management buttons.

Class declaration

Following is the declaration for javax.swing.JWindow class:

public class JWindow
   extends Window
      implements Accessible, RootPaneContainer

Field

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

  • protected AccessibleContext accessibleContext --The accessible context property.

  • protected JRootPane rootPane --The JRootPane instance that manages the contentPane and optional menuBar for this frame, as well as the glassPane.

  • protected boolean rootPaneCheckingEnabled --If true then calls to add and setLayout will be forwarded to the contentPane.

Class constructors

S.N.Constructor & Description
1JWindow()
Creates a window with no specified owner.
2JWindow(Frame owner)
Creates a window with the specified owner frame.
3JWindow(GraphicsConfiguration gc)
Creates a window with the specified GraphicsConfiguration of a screen device.
4JWindow(Window owner)
Creates a window with the specified owner window.
5JWindow(Window owner, GraphicsConfiguration gc)
Creates a window with the specified owner window and GraphicsConfiguration of a screen device.

Class methods

S.N.Method & Description
1protected void addImpl(Component comp, Object constraints, int index)
Adds the specified child Component.
2protected JRootPane createRootPane()
Called by the constructor methods to create the default rootPane.
3AccessibleContext getAccessibleContext()
Gets the AccessibleContext associated with this JWindow.
4Container getContentPane()
Returns the Container which is the contentPane for this window.
5Component getGlassPane()
Returns the glassPane Component for this window.
6Graphics getGraphics()
Creates a graphics context for this component.
7JLayeredPane getLayeredPane()
Returns the layeredPane object for this window.
8JRootPane getRootPane()
Returns the rootPane object for this window.
9TransferHandler getTransferHandler()
Gets the transferHandler property.
10protected boolean isRootPaneCheckingEnabled()
Returns whether calls to add and setLayout are forwarded to the contentPane.
11protected String paramString()
Returns a string representation of this JWindow.
12void remove(Component comp)
Removes the specified component from the container.
13void repaint(long time, int x, int y, int width, int height)
Repaints the specified rectangle of this component within time milliseconds.
14void setContentPane(Container contentPane)
Sets the contentPane property for this window.
15void setGlassPane(Component glassPane)
Sets the glassPane property.
16void setLayeredPane(JLayeredPane layeredPane)
Sets the layeredPane property.
17void setLayout(LayoutManager manager)
Sets the LayoutManager.
18protected void setRootPane(JRootPane root)
Sets the new rootPane object for this window.
19protected void setRootPaneCheckingEnabled(boolean enabled)
Sets whether calls to add and setLayout are forwarded to the contentPane.
20void setTransferHandler(TransferHandler newHandler)
Sets the transferHandler property, which is a mechanism to support transfer of data into this component.
21void update(Graphics g)
Calls paint(g).
22protected void windowInit()
Called by the constructors to init the JWindow properly.

Methods inherited

This class inherits methods from the following classes:

  • java.awt.Window

  • java.awt.Container

  • java.awt.Component

  • java.lang.Object

JWindow Example

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

SwingContainerDemo.java
package com.tutorialspoint.gui;

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;

public class SwingContainerDemo {
   private JFrame mainFrame;
   private JLabel headerLabel;
   private JLabel statusLabel;
   private JPanel controlPanel;
   private JLabel msglabel;

   public SwingContainerDemo(){
      prepareGUI();
   }

   public static void main(String[] args){
      SwingContainerDemo  swingContainerDemo = new SwingContainerDemo();  
      swingContainerDemo.showJWindowDemo();
   }

   private void prepareGUI(){
      mainFrame = new JFrame("Java Swing 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 JLabel("", JLabel.CENTER);        
      statusLabel = new JLabel("",JLabel.CENTER);    

      statusLabel.setSize(350,100);

      msglabel = new JLabel("Welcome to TutorialsPoint SWING Tutorial."
         , JLabel.CENTER);

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

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

   private void showJWindowDemo(){
      headerLabel.setText("Container in action: JWindow");   
      final MessageWindow window = 
         new MessageWindow(mainFrame, 
         "Welcome to TutorialsPoint SWING Tutorial.");

      JButton okButton = new JButton("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 JWindow{
      private String message; 

      public MessageWindow(JFrame parent, String 
         message) { 
         super(parent);               
         this.message = message; 
         setSize(300, 300);       
         setLocationRelativeTo(parent);         
      }

      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:/ > SWING and type the following command.

D:\SWING>javac com\tutorialspoint\gui\SwingContainerDemo.java

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

D:\SWING>java com.tutorialspoint.gui.SwingContainerDemo

Verify the following output

SWING JWindow

Advertisements
Advertisements