How I may help
LinkedIn Profile Email me!
Call me using Skype client on your machine

Reload this page Java GUI Event Programming

This page summarizes how to use the JFC (Java Foundation Classes) from the Java 1.2 SDK, which includes the machine-dependent Abstract Window Toolkit (AWT), machine-independent Swing extensions, Java 2D, Drag and Drop, and Accessibility API's.

Consistent user interfaces enable a user to learn new applications faster, and avoid errors when switching among applications.


Topics this page:

  • Libraries
  • Look and Feel,
  • Frames,
  • GUI Elements, Controls
  • Event Delegation,
  • Events Types & Objects, Mouse, Keyboard, Other
  • Layout Managers
  • Hierarchy of Classes
  • Swing
  • JMF
  • Your comments???

    Site Map List all pages on this site 
    About this site About this site 
    Go to first topic Go to Bottom of this page

    Annoying dog bark

    Set screen Which J2SE GUI Library?

      AWT and Swing are part of the Java Foundation Classes (JFC). Swing was released by Sun in 1997.

      AWT components are called "heavyweight" components (in contrast to the Swing JDK 1.1 "Lightweight" UI Framework) because they make use of the operating system's underlying platform's native windowing functionality, which custom Java code access through peer native code counterpart components in SDK package java.awt.peer. So AWT components inherit a familiar look of the OS they run on. Use of native code (written in C) enables AWT to run faster than Swing, and without the user Java plug-in installation hassles required by Swing.

      Some Java developers are reluctant to use Swing since many users are reluctant to do the internet browser upgrade required. New Swing classes are not supported in older versions of the Java Runtime Environment distributed with browsers (IE, Netscape, etc.). Clients browsers running Swing must download download Java “fat” client plug-in or upgrade a version of the run-time containing the plug-in.

      With the Google Web Toolkit (GWT), Ajax applications are implemented by writing almost entirely in Java. The Google compiler compiles AWT-like API statements to JavaScript that runs on the client.

      Swing, entirely written in Java ("Pure Java"), provides programmers a greater range of behaviors from a richer set of higher-level components (such as icons, tool-tips, tree view, list box, and tabbed panes). Swing components start with 'J' (JButton vs Button, etc.).

      Programmers have more flexibility programming Swing than AWT because Swing follows the MVC (Model-View-Controller) design patternanother page on this site. Swing classes store state data used to paint various views in one common place (the model). A UI delegate is responsible for how components are drawn on the screen and how events are handled. This allows programmers to determine the look and feel of components without affecting the data.

      Swing doesn't completely replace AWT packages. Subclasses of java.awt.window are still “heavyweight” components, and Layout Managers relying on local platforms for their look and feel. Most event handling is still handled by the awt.event class.

      SWT (The Standard Widget Toolkit)

      IBM released SWT (Standard Widgets Toolkit) in 2001 under an OSI approved EPL license after developing it to support development of their Eclipse IDE (supposedly due to the slow speed of Swing). SWT uses a rich set of native widgets for Windows® and Motif implementations. The GUI looks "natural" because underneath the Java code, the SWT library makes calls to C (JNI) interface to the operating system using one-to-one mapping.

      SWT now has API's for windowing platforms: Windows, GTK, Carbon, etc.

      SWT's detractors point to bugs found during development of Azureus BitTorrent client and RSSOwl (a newsreader), the most visible products developed using SWT.

        Swing programmers will think nothing of having a Button widget that displays both a text label and image, and be surprised they can't do that in SWT unless the Button appears within a ToolBar or CoolBar. They will be used to attaching Borders to widgets as they see fit, using the Swing BorderFactory, but wonder why borders are only supported on some SWT widgets such as Text and Label. They will be accustomed to setting up input masks on text fields using the facilities on JTextField, but find in SWT they will have to write that themselves by listening to individual keystrokes on a Text widget.

      On top of SWT

      JFace is a model and utility layer RCP (Rich Client Platform) and Eclipse component, like SWT. It provides for a model layer that is architecturally separate from the widgets.

      Other GUI for Eclipse

      Several tool sets are available for developing Eclipse desktop user interfaces at a higher level than hand writing Simple Widget Toolkit (SWT) code.

      • GUI: The Eclipse VEP (Visual Editor Project) provides a framework for developing GUI builders that support both SWT/RPC code and Swing/Java Foundation Classes code.

      • XML: XSWT and EclipseXUL, provide for the development and construction of Eclipse user interfaces through specifically formatted XML files that provides a one-to-one mapping between XSWT elements and SWT Java code.

      • EclipseXUL, an Eclipse feature under development adds XML User Interface Language support to Eclipse and is based on the Eclipse Web Tools Project .

      The Sun Netbeans IDE provides a GUI builder missing in Eclipse.

      Other: Internationalized GUI

      tool Jeff Tsay's $149 text2gui JAR library makes it easier for Java programmers to internationalize applications by specifying GUI descriptions instead of coding localization methods referencing resource files. The Tsay library parses tex2gui descriptions at runtime, so changes to a GUI do not require recompilation, which can be a big deal. Use of the library allows specialized syntax, such as Subkeys and chaining of resource bundles that inherit from other resource bundles. The library can also create component hierarchies with a single line of Java code. Because the library allows more properties to be specified in resource bundles, different fonts and layouts can be automatically displayed for each target locale. Brilliant. I use this whenever I can instead of resource files.


    Go to Top of this page.
    Previous topic this page
    Next topic this page

    Set screen Look and Feel

      Swing programmers don't have to code for platform specific GUI features because they can use the default "metal" look-and-feel behavior of Swing controls (views), which can be customized by specifying a PL&F (pluggable Look and Feel) to look like Microsoft Windows, UNIX Motif, or Apple MacOS instead of the default cross-platform "metal".

      To invoke a Java program with the Windows pluggable Look and Feel:

      java class

    Go to Top of this page.
    Previous topic this page
    Next topic this page

    Set screen Swing GUI Elements

      download Download this Visio 2000 flow chart.

      In Swing, JFrame is called top-level and heavyweight because it is not contained within any other object or window (such as an applet within the browser panel). Some call JFrames a “window” because JFrames have a title bar, menu bar, and border with resizing corners like stand-alone application programs that sits on the user's desktop. Also, AWT instead used the Window class to create a top-level window. With Swing, a JFrame is created as a subclass of the Window object:

      public class MyFrameClass1 extends JFrame {

      A JPanel does not contain a title bar, menu bar, or border with resizing corners. Output on an applet is drawn on a panel.

      JWindow does not contain a title bar, so they are often used to build Splash Screens.

      When a JDialog pop-up windows is defined with a title bar, the JFrame or a JApplet that owns them are also specified:

      class OptionDialog extends JDialog {
        OptionDialog( Frame f, String title, String msg, boolean modal ) {
          super( f, title, modal );

      A Canvas encapsulates a blank window for drawing.

    Go to Top of this page.
    Previous topic this page
    Next topic this page

    Set screen Window Frames

      Windows are opened or closed by specifying true or false in method call frame.setVisible(true)

      Unlike AWT's Frame component, Swing's Jframes can be set to close automatically when the "X" button is clicked on the window frame:

      app.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE );

      Here is the default overlap:

        Default Components
          Palette and toolbars
            Modal dialogs
              PopUp message dialogs
                Dragged components

    Go to Top of this page.
    Previous topic this page
    Next topic this page

    Set screen GUI Controls Components

      A Container is a collection of related Components. JComponent is a superclass to most Swing components.

      Adding to a container a component that has not been instantiated throws a NullPointerException. So, to add an interface a button labeled “Save”:

      Button saveIt = new Button("Save");

      To add a control object to the GUI interface:

      add (saveIt);

      A Button generates an action event when the user clicks on it; the button is normally used to issue a command, such as to save or to exit. For example, you can build a database application to process personnel records; when you have entered the details you can click on the Save button.

      A check box enables a user to select or deselect an option. If selected, it contains a check mark. For example, you are writing an application for an ice cream shop. You can choose what kinds of toppings you want. You can choose no toppings, one topping or many toppings. You will implement the choice of toppings with check boxes.

      You can group check boxes to function as radio buttons. This means that you can select any one of them at any time. For example, you are in the ice cream shop again. You can choose either a cone or a cup for your ice cream, but not both.

      The Choice control creates a pop-up list of items to choose from. For example, you are filling out a personnel form and you need to specify your title such as Mr. or Mrs. You would put these titles into a choice list.

      A Label displays a string on the screen. It is a passive control. It cannot accept user input, and it serves to identify the text field next to it.

      The List control is a scrolling list where you can make multiple selections.

      A Scrollbar is much like the horizontal and vertical scroll bars on a window. It allows you to specify a value visually within a specified range of values.

      A TextField is used to get single-line text input from the user. You typically use the TextField control to get information such as a person's first name and last name for an employee database.

      A textarea is used to get multiple-lines of text input from the user. For example, when you want to capture a lot of text such as in a comments field, you must use the textarea control.

      The exact size and location of every component using the setBounds() method.

    Go to Top of this page.
    Previous topic this page
    Next topic this page

    Set screen Java GUI Event Delegation

      Javascript does not require initialization of a listener such as this Java method:


      Java coding is event-driven. An event is generated when a state change occurs in a source object. Event classes are from the java.awt.event package.

      In Java version 1.02 and before, all events that occurred were passed on to the application program's handleEvent method defined in the Component class. The handleEvent method then calls other specific event-handling methods such as mouseClick, mouseDown, and mouseUp. Developers had to write event-handling methods to respond to all possible events. During run-time, apps receiving notifications and making decisions not to process them was a waste of time and resources.

      Java version 1.1 and after use the event delegation model. Not all events are passed on to the app's event handler, only application listeners which have registered to receive specific events are sent messages. The listeners also process events. Listeners are registered using the following syntax:

      public void addTypeListener (TypeListener evtRef)

      Users interacts with the event source. This information is encapsulated into the event object. Most event-listener components are common to packages javax.swing.event and java.awt.event.


      Most of the event delegation model classes reside in the java.awt.event package. But Java.util.EventObject is The topmost superclass. Its method Object getSource() returns the object that originated the event. Its subclass, java.awt.AWTEvent, is the superclass of all delegation model event classes, with method int getID() which returns the ID of the event.

      The InputEvent superclass getWhen() method returns a long containing the time when the event took place;

      The MouseEvent class int getX() and getY() methods return the position of the mouse within the originating component at the time the event took place;

    Go to Top of this page.
    Previous topic this page
    Next topic this page

    Set screen Events Types & Objects in Java Swing, AWT, & Javascript

      12 Subclasses of EventObject in java.awt.event: Action, Adjustment, Component, Container, Focus, Input, Item, Key, Mouse, MouseWheel, Text, Window

      JFC Java AWT Event AWT
      Supported by Javascript object
      document or image is finished loading. ADDED LOAD_FILE 1002 onLoad Image, Window
      user exits a document. REMOVED ?? SAVE_FILE 1003 onUnload Window
      an error is detected while loading an image n/a - - onError Image, Window
      user presses a key on the keyboard. _PRESS
      Document, Image, Link, textarea
      user releases a key on the keyboard. _RELEASE
      user clicks the mouse. _CLICKED _DOWN 501 onMouseDown Document, Button, Link
      user moves a mouse off the element. _MOVED _MOVE 503 - -
      user moves a mouse off the element. _RELEASED _UP 502 onMouseOut Layer, Link, Image
      user moves a mouse over an element. _ENTERED _ENTER 504 onMouseOver
      user releases the mouse button. _EXITED _EXIT 505 onMouseUp Document, Image, button elements, Link
      an object (such as a shortcut or file) is dragged and dropped into the browser window. _DRAGGED _DRAG 506 onDragDrop Window elements
      user moves a mouse wheel. _BLOCK_SCROLL
      (JDK 1.4+) - - -
      (Java Object or Javascript Element)
      element is given input focus. GAINED GOT_FOCUS 1004 onFocus Button, Checkbox, FileUpload, Password, Radio, Reset, Select, Submit, Text, textarea, Window
      element loses input focus. LOST LOST_FOCUS 1005 onBlur Button, Checkbox, FileUpload, Layer, Password, Radio, Reset, Select, Submit, Text, textarea, Window
      JFrame _ACTIVATED - - - -
      _OPENED _EXPOSE 202 - -
      _CLOSED - - - -
      _CLOSING - - - -
      _MOVED _MOVE 205 onMove Window
      (JDK 1.4+) - - -
      _DEACTIVATED _DESTROY 201 onAbort Image
      _ICONIFIED _ICONIFY 203 - -
      user drags a Window border. ??? - - onResize Window
      JTextField edit box - - - -
      - - - - -
      JCheckBox. JList LIST_SELECT
      - -
      use manipulates scrollbars SCROLL_LINE_UP
      onSubmit Form
      user selects or deslects an item or events text and moves input focus to another element. JButton - - onChange Select, text, input elements
      user clicks once (performs a single click). - - onClick Button, Document, Checkbox, Link, Radio, Reset, Submit
      user clicks twice rapidly (IE only), generally to invoke an entirely new application program. ACTION_EVENT 1001 onDblClick Document, Image, button elements, Link
      user selects some of the text. - - onSelect Text, textarea
      user clicks a form's reset button. n/a - - onReset Form
      user clicks a form's submit element. n/a - - onSubmit Form
        - position MOVED, RESIZED, visibility HIDDEN, SHOWN - - -

      Semantic events support the illusion that a graphical user interface (GUI) component on the screen is actually a mechanical input device. For example, the Button class is described in terms of pushing a button, when in reality; the mouse pointer is inside the button's territory of the screen.

    Go to Top of this page.
    Previous topic this page
    Next topic this page

    Set screen Mouse Event Methods

      Activity Java Method
      button's surface area is entered or exited mouseEntered or
      button is pressed mousePressed
      button is pressed and released mouseClicked
      button is pressed and moved mouseDragged

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

      public class MouseTracker extends JFrame implements MouseListener, MouseMotionListener { private JLabel statusBar; public myMouseTracker() { super( "Mouse Events Demo" ); statusBar = new JLabel(); getContentPane().add( statusBar, BorderLayout.SOUTH ); // application listens to its own mouse events: addMouseListener( this ); addMouseMotionListener( this ); setSize( 275, 100 ); show(); } // MouseListener event handlers: public void mouseClicked( MouseEvent e ) { statusBar.setText( "Clicked at [" + e.getX() + ", " + e.getY() + "]" ); repaint(); // redraw screen: calls paintComponent() } } }

    Go to Top of this page.
    Previous topic this page
    Next topic this page

    Set screen Keyboard Event Methods

      import java.awt.*;
      import java.awt.event.*;
      import javax.swing.*;
      public class myKeyDemo extends JFrame 
          implements KeyListener {
      	private JLabel statusBar;
      	public myKeyDemo() {
      		super( "Keystroke Events Demo" );
      		textarea = new Jtextarea( 10, 15 );
      		textarea.setText( "Press any key on the keyboard..." );
      		textarea.setEnabled( false );
         		// allow frame to process Key events:
      		addKeyListener( this );
      		getContentPane().add( textarea );
      		setSize( 350, 100 );
      	// KeyListener interface requires definition of keyPressed, 
      	// keyReleased, and keyTyped methods:
      	public void keyPressed( KeyEvent e ) {
      		line1 = "Key pressed: " + 
      			e.getKeyText( e.getKeyCode() );
      		setLines2and3( e );
      	public void keyReleased( KeyEvent e ) {
      		line1 = "Key released: " + e.getKeyText( e.getKeyCode() );
      		setLines2and3( e );
      	public void keyTyped( KeyEvent e ) {
      		line1 = "Key typed: " + e.getKeyChar();
      		setLines2and3( e );
      	public static void main( String args[] ) {
      		KeyDemo app = new KeyDemo();

    Go to Top of this page.
    Previous topic this page
    Next topic this page

    Set screen Other Action Events

    Go to Top of this page.
    Previous topic this page
    Next topic this page

    Set screen AWT Layout Managers

      Layout Managers provide a level of platform independence while they reduce some of the drudgery in building user interfaces. They allow developers define a containment hierarchy instead of specific positions of elements. The steps:

      1. Construct the panel
      2. Give the panel a layout manager

        public class MyFrame extends Frame {
        FlowLayout lm = new FlowLayout2(FlowLayout.LEFT);

      3. Populate the panel p with component c:


      4. Add the panel to its own container


      java.awt. Layout Manager Description


      is the simplest — the default — layout manager. It lays the components from left to right starting at the top. When it runs out of space on one row, it goes to the next row. By default the Flow layout leaves a gap of five pixels vertically and horizontally between components, and also aligns components in the center of the window. This behavior is controlled with the FlowLayout constructor:
        FlowLayout(int align, int hgap, int vgap);
      FlowLayout.CENTER and these other constants are provided to specify align:
      FlowLayout.LEADING FlowLayout.LEFT FlowLayout.RIGHT FlowLayout.TRAILING

      FlowLayout always uses a component's preferred size.



      is the default for frames, honors components' preferred size in directional regions: north (top), south (bottom), east (left), west (right). CENTER is what's left over.
        setLayout(new java.awt.BorderLayout());




      lays the components on different cards, and displays only one card at a time over time, so users can cycle through them using methods first, next, previous.


      lays out the components on a grid of evenly spaced rows and columns going from left to right and going from top to bottom. A component's preferred size is ignored.
        setLayout(new java.awt.GridLayout(3, 2));


      provides maximum control over the layout of components and their sizes. Similar to the Grid structure, but the size of its 10 cells (such as NORTHWEST) can vary -- possibly occupying more than one cell (by spcifying GridBagConstraints object fields gridwidth and gridheight). Programming its GriBagConstraint statements can be tedious, though. To control stretchiness, specify weightx in only one component in each column and weighty only in one component in each row.

      It is futile to call setBounds() on a component because layout managers call it as well.

      Public double type arrays define the minimum RowWeights and columnWeights.

      To use no layout manager, call myContainer.setLayout(null).

    Go to Top of this page.
    Previous topic this page
    Next topic this page

    Set screen Abstract Window Toolkit (AWT) Classes

      Class Description Usage in 1.4+
      FlowLayout, etc. Layout managers same
      AWTEvent Wrapper for (encapsulates) AWT events
      AWTEventMulticaster Dispatches events to several listeners
      Button Push button control component JButton
      Canvas Blank semantics-free window
      Checkbox Component
      CheckboxGroup Groups Checkbox components
      CheckboxMenuItem On/off menu item
      Choice Popup list
      Color Change colors
      Component Abstract superclass for components
      Container Subclass of Component class for other container type classes
      Dialog Creates a Dialog (pop-up) window
      Dimension width and height of an object, e.g. the applet window
      Event Wrapper for (encapsulates) events
      EventQueue Queues events
      FileDialog File selection box window
      Font Encapsulates type fonts
      FontMetrics Font related information to display text
      Frame Window with menu bar, title and resizing corners JFrame
      Graphics Encapsulates graphics context used to display on a window
      GraphicsDevice Screen or printer
      Image Wrapper for images
      Label Component
      List List box component
      Menu Pull down menu
      Panel Container
      Point Wrapper for x & y coordinates
      Polygon Wrapper for a polygon
      PopupMenu Wrapper for popup menu
      Scrollbar Component
      SystemColor Standard system colors for windows, text, etc.
      textarea Component
      Window Window with no frame, no menu bar, no title

      Listed alphabetically:

      When programming with AWT, you can place a Panel object in a Frame object and place other components on the Panel object if you wish, or you can simply place other components directly on the viewable area of the Frame object.

    Go to Top of this page.
    Previous topic this page
    Next topic this page

    Set screen Swing Classes

      Swing components are Java extensions, thus the "javaz" in their package name (javax.swing.JComponent class library), a subclass of the Container class. Here is a partial list of them:

      JLabel Area in which uneditable text or icons can be displayed, such as “tool tip” text appearing when a user mouses over an item.
      JTextField Area that accepts keyboard input (text) from users.
      JPasswordField Area that accepts keyboard input (text) from users and hides them.
      JButton Area that triggers an event when clicked.
      JCheckBox Area that logs whether or not it's checked.
      JComboBox Dropdown list of selectable items.
      JList List of selectable and executable items. (uses the MVS approach)
      JPanel Container in which other components can be placed.

      Use setVisible( true ); instead of the deprecated show().

      The viewable area of a Frame or a JFrame is the bounds minus the insets. Insets are used to account for the space covered by the borders and the values of the insets on all four sides are available by invoking the method named getInsets() on the object.

      Objects (components) cannot be placed directly on the viewable area of a JFrame object.

      To place components in the JFrame, we invoke the add() method of getContentPane(), which deals with the JRootPane container object automatically placed in the JFrame object. JRootPane owns the entire viewable area of the JFrame object. An object of type JLayeredPane An object of type JPanel (the glassPane) because it is usually transparent. JFrame object JRootPane 1. JPanel (the transparent "glassPane") automatically the first child So this is good for pop-up messages that should go on top. 2. layeredPane a. it contains a menuBar positioned at the upper edge b. contentPane, which has a BorderLayout manager by default. Components drawn on layers with high (algebraically signed) numbers are painted on top of components on layers with smaller (algebraically signed) numbers. The layer position for the contentPane is effectively layer number -30,000. -29,999 (we will place one there in our sample program later).


      webpage article Sun's Swing Gallery of GUI Components, such as tabbed panes and fancy borders to sliders and spinners.

      A website external to this site Swing Sightings demo Swing applications in use.

      Swing components are not inherantly thread-safe. So use javax.swing.SwingUtilities.invokeLater() and invokeAndWait() in code called by several threads, such as cusom ListModels and TreeModels responding to non-local or non-GUI events.

    Go to Top of this page.
    Previous topic this page
    Next topic this page

      Set screen Pop-up Dialog Boxes

      Reminder When specifying class libraries, declare the class actually used in the code rather than all classes of the library. This reduces overhead and bloat.

        To display dialog boxes, use methods of class JOptionPane in the javax.swing package.

          import javax.swing.JOptionPane;

      JOptionPane. dialog type literal Icon
      Reminder Specify graphic icons appropriate to the message.

        ClassName.methodName( arguments )

        JOptionPane.showMessageDialog( null, "Aloha!", JOptionPane.PLAIN_MESSAGE );

      Reminder Avoid unnecessary user interaction. Don't require user response unless it is important to the user. So orovide a way for each user to customize how a message is displayed. Displaying a message within the application (without requiring the user to click OK).

      A truly modal dialog window not only maintains focus but also prevents users from accessing the main window while it's showing. This kind of window is a good way to display user preference settings as well as to show details and user controls for summary data displayed on the main page.

    Go to Top of this page.
    Previous topic this page
    Next topic this page

    Set screen Java Media Framework Classes

      download Download Sun's Java Media Framework API to support multimedia file formats:
      • Audio protocols: AIFF, AU, AVI, MIDI, MP3, WAV
      • Video protocols: AVI, MPEG-1, QT
      • Animation protocols: Flash 2, HotMedia, Vivo (VIV), GSM

      The list of media handlers, plugin components and capture devices used by JMF is configured using the JMFRegistry built with the Swing GUI toolkit.

      JMF supports the Session Initiation Protocol (SIP) and Realtime Transport Protocol (RTP) to unicast, broadcast, and multicast Real-Time Media Streams.


    Go to Top of this page.
    Previous topic this page
    Next topic this page

    Set screen Java Charting Libraries


    Go to Top of this page.
    Previous topic this page
    Next topic this page

    Set screen Eclipse Libraries

      The Eclipse Web Services Tools contribution provides an extensible framework of wizards, actions, preferences, code generators and Web applications to help Eclipse developers create, publish, discover, consume and test Web Services chiefly for, but not limited to, the Java programming language and the J2EE platform. Included in the contribution are tools for building Apache Axis Web services and Web service clients on Apache Tomcat.

      Eclipse Web Tools Platform (WTP) community resources, such as articles, books, tutorials.


    Go to Top of this page.
    Previous topic this page
    Next topic this page

    Portions ©Copyright 1996-2010 Wilson Mar. All rights reserved. | Privacy Policy |


  • Programming Languages
  • Java Architecture,
  • Java I/O,
  • Functions, Threads
  • Data Types, Strings, Escape Characters, Fonts
  • Applications Development
  • On the web
  • Search

    How I may help

    Send a message with your email client program

    Your rating of this page:
    Low High

    Your first name:

    Your family name:

    Your location (city, country):

    Your Email address: 

      Top of Page Go to top of page

    Thank you!