HTML

html content help to improve the coding

Thursday, 13 November 2014

How to use SWING IN JAVA

SWING

AVA provides a rich set of libraries to create Graphical User Interface in platform independent way. In this article we'll look in SWING GUI controls.
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.
    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/.
    Every user interface considers the following three main aspects:
  • UI elements : Thes are the core visual elements the user eventually sees and interacts with. GWT provides a huge list of widely used and common elements varying from basic to complex which we will cover in this tutorial.
  • Layouts: They define how UI elements should be organized on the screen and provide a final look and feel to the GUI (Graphical User Interface). This part will be covered in Layout chapter.
  • Behavior: These are events which occur when the user interacts with UI elements. This part will be covered in Event Handling chapter.
UI classes Every SWING controls inherits properties from following Component class hiearchy.
Sr. No.Class & Description
1Component
A Container is the abstract base class for the non menu user-interface controls of SWING. Component represents an object with graphical representation
2Container
A Container is a component that can contain other SWING components.
3JComponent
A JComponent is a base class for all swing UI components. In order to use a swing component that inherits from JComponent, component must be in a containment hierarchy whose root is a top-level Swing container.

SWING UI Elements:

Following is the list of commonly used controls while designed GUI using SWING.
Sr. No.Control & Description
1JLabel
A JLabel object is a component for placing text in a container.
2JButton
This class creates a labeled button.
3JColorChooser
A JColorChooser provides a pane of controls designed to allow a user to manipulate and select a color.
4JCheck Box
A JCheckBox is a graphical component that can be in either an on (true) or off (false) state.
5JRadioButton
The JRadioButton class is a graphical component that can be in either an on (true) or off (false) state. in a group.
6JList
A JList component presents the user with a scrolling list of text items.
7JComboBox
A JComboBox component presents the user with a to show up menu of choices.
8JTextField
A JTextField object is a text component that allows for the editing of a single line of text.
9JPasswordField
A JPasswordField object is a text component specialized for password entry.
10JTextArea
A JTextArea object is a text component that allows for the editing of a multiple lines of text.
11ImageIcon
A ImageIcon control is an implementation of the Icon interface that paints Icons from Images
12JScrollbar
A Scrollbar control represents a scroll bar component in order to enable user to select from range of values.
13JOptionPane
JOptionPane provides set of standard dialog boxes that prompt users for a value or informs them of something.
14JFileChooser
A JFileChooser control represents a dialog window from which the user can select a file.
15JProgressBar
As the task progresses towards completion, the progress bar displays the task's percentage of completion.
16JSlider
A JSlider lets the user graphically select a value by sliding a knob within a bounded interval.
17JSpinner
A JSpinner is a single line input field that lets the user select a number or an object value from an ordered sequence.

  • 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 SwingControlDemo(){
      prepareGUI();
   }

   public static void main(String[] args){
      SwingControlDemo swingControlDemo = new SwingControlDemo();  
      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


  • 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 Event Classes:

Following is the list of commonly used event classes.
Sr. No.Control & Description
1AWTEvent
It is the root event class for all SWING events. This class and its subclasses supercede the original java.awt.Event class.
2ActionEvent
The ActionEvent is generated when button is clicked or the item of a list is double clicked.
3InputEvent
The InputEvent class is root event class for all component-level input events.
4KeyEvent
On entering the character the Key event is generated.
5MouseEvent
This event indicates a mouse action occurred in a component.
6WindowEvent
The object of this class represents the change in state of a window.
7AdjustmentEvent
The object of this class represents the adjustment event emitted by Adjustable objects.
8ComponentEvent
The object of this class represents the change in state of a window.
9ContainerEvent
The object of this class represents the change in state of a window.
10MouseMotionEvent
The object of this class represents the change in state of a window.
11PaintEvent
The object of this class represents the change in state of a window.


  • 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 Event Listener Interfaces:

    Following is the list of commonly used event listeners.
    Sr. No.Control & Description
    1ActionListener
    This interface is used for receiving the action events.
    2ComponentListener
    This interface is used for receiving the component events.
    3ItemListener
    This interface is used for receiving the item events.
    4KeyListener
    This interface is used for receiving the key events.
    5MouseListener
    This interface is used for receiving the mouse events.
    6WindowListener
    This interface is used for receiving the window events.
    7AdjustmentListener
    This interface is used for receiving the adjusmtent events.
    8ContainerListener
    This interface is used for receiving the container events.
    9MouseMotionListener
    This interface is used for receiving the mouse motion events.
    10FocusListener
    This interface is used for receiving the focus events.

    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 Adapters:

    Following is the list of commonly used adapters while listening GUI events in SWING.
    Sr. No.Adapter & Description
    1FocusAdapter
    An abstract adapter class for receiving focus events.
    2KeyAdapter
    An abstract adapter class for receiving key events.
    3MouseAdapter
    An abstract adapter class for receiving mouse events.
    4MouseMotionAdapter
    An abstract adapter class for receiving mouse motion events.
    5WindowAdapter
    An abstract adapter class for receiving window events.

    Introduction

    Layout means the arrangement of components within the container. In other way we can say that placing the components at a particular position within the container. The task of layouting the controls is done automatically by the Layout Manager.

    Layout Manager

    The layout manager automatically positions all the components within the container. If we do not use layout manager then also the components are positioned by the default layout manager. It is possible to layout the controls by hand but it becomes very difficult because of the following two reasons.
  • It is very tedious to handle a large number of controls within the container.
  • Oftenly the width and height information of a component is not given when we need to arrange them.

Java provide us with various layout manager to position the controls. The properties like size,shape and arrangement varies from one layout manager to other layout manager. When the size of the applet or the application window changes the size, shape and arrangement of the components also changes in response i.e. the layout managers adapt to the dimensions of appletviewer or the application window.
The layout manager is associated with every Container object. Each layout manager is an object of the class that implements the LayoutManager interface.
Following are the interfaces defining functionalities of Layout Managers.
Sr. No.Interface & Description
1LayoutManager
The LayoutManager interface declares those methods which need to be implemented by the class whose object will act as a layout manager.
2LayoutManager2
The LayoutManager2 is the sub-interface of the LayoutManager.This interface is for those classes that know how to layout containers based on layout constraint object.

AWT Layout Manager Classes:

Following is the list of commonly used controls while designed GUI using AWT.
Sr. No.LayoutManager & Description
1BorderLayout
The borderlayout arranges the components to fit in the five regions: east, west, north, south and center.
2CardLayout
The CardLayout object treats each component in the container as a card. Only one card is visible at a time.
3FlowLayout
The FlowLayout is the default layout.It layouts the components in a directional flow.
4GridLayout
The GridLayout manages the components in form of a rectangular grid.
5GridBagLayout
This is the most flexible layout manager class.The object of GridBagLayout aligns the component vertically,horizontally or along their baseline without requiring the components of same size.
6GroupLayout
The GroupLayout hierarchically groups components in order to position them in a Container.
7SpringLayout
A SpringLayout positions the children of its associated container according to a set of constraints.


  • 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

    Menu Controls

    Sr. No.Control & Description
    1JMenuBar
    The JMenuBar object is associated with the top-level window.
    2JMenuItem
    The items in the menu must belong to the JMenuItem or any of its subclass.
    3JMenu
    The JMenu object is a pull-down menu component which is displayed from the menu bar.
    4JCheckboxMenuItem
    JCheckboxMenuItem is subclass of JMenuItem.
    5JRadioButtonMenuItem
    JRadioButtonMenuItem is subclass of JMenuItem.
    6JPopupMenu
    JPopupMenu can be dynamically popped up at a specified position within a component.

    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 Containers:

Following is the list of commonly used containers while designed GUI using SWING.
Sr. No.Container & Description
1Panel
JPanel is the simplest container. It provides space in which any other component can be placed, including other panels.
2Frame
A JFrame is a top-level window with a title and a border
3Window
A JWindow object is a top-level window with no borders and no menubar.


  • 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

No comments:

Post a Comment