English 中文(简体)
Swing - Quick Guide
  • 时间:2024-09-17

SWING - Quick Guide


Previous Page Next Page  

SWING - Overview

Swing API is a set of extensible GUI Components to ease the developer s pfe to create JAVA based Front End/GUI Apppcations. It is build on top of AWT API and acts as a replacement of AWT API, since 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 be model driven so that the highest level API is not required to have data.

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

MVC Architecture

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

    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 has Model as a seperate element, while the View and Controller part are clubbed in the User Interface elements. Because of which, Swing has a pluggable look-and-feel architecture.

Swing Features

    Light Weight − Swing components 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 pke Tree, TabbedPane, spder, colorpicker, and table controls.

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

    Pluggable look-and-feel − SWING based GUI Apppcation look and feel can be changed at run-time, based on available values.

SWING - Environment Setup

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

Java SE is freely available from the pnk Download Java. Hence, you can 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 have installed Java on your machine, you would need to set the environment variables to point to the correct installation directories.

Setting Up the Path for Windows 2000/XP

Assuming you have installed Java in c:Program Filesjavajdk directory −

Step 1 − Right-cpck on My Computer and select Properties .

Step 2 − Cpck the Environment variables button under the Advanced tab.

Step 3 − Alter the Path variable so that it also contains the path to the Java executable. Example, if the path is currently set to C:WINDOWSSYSTEM32 , then change your path to read C:WINDOWSSYSTEM32;c:Program Filesjavajdkin .

Setting Up the Path for Windows 95/98/ME

Assuming you have installed Java in c:Program Filesjavajdk directory −

Step 1 − Edit the C:autoexec.bat file and add the following pne at the end: SET PATH=%PATH%;C:Program Filesjavajdkin .

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 pne to the end .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 pke Notepad (Recommended for this tutorial), TextPad.

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

    Ecppse − Ecppse is also a Java IDE developed by the Ecppse open source community and can be downloaded from https://www.ecppse.org/.

SWING - Controls

Every user interface considers the following three main aspects −

    UI Elements − These are the core visual elements the user eventually sees and interacts with. GWT provides a huge pst 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 the Layout chapter.

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

UI classes

Every SWING controls inherits properties from the following Component class hiearchy.

S.No. Class & Description
1 Component

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

2 Container

A Container is a component that can contain other SWING components

3 JComponent

A JComponent is a base class for all SWING UI components. In order to use a SWING component that inherits from JComponent, the component must be in a containment hierarchy whose root is a top-level SWING container

SWING UI Elements

Following is the pst of commonly used controls while designing GUI using SWING.

S.No. Class & Description
1 JLabel

A JLabel object is a component for placing text in a container.

2 JButton

This class creates a labeled button.

3 JColorChooser

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

4 JCheck Box

A JCheckBox is a graphical component that can be in either an on (true) or off (false) state.

5 JRadioButton

The JRadioButton class is a graphical component that can be in either an on (true) or off (false) state. in a group.

6 JList

A JList component presents the user with a scrolpng pst of text items.

7 JComboBox

A JComboBox component presents the user with a to show up menu of choices.

8 JTextField

A JTextField object is a text component that allows for the editing of a single pne of text.

9 JPasswordField

A JPasswordField object is a text component speciapzed for password entry.

10 JTextArea

A JTextArea object is a text component that allows editing of a multiple pnes of text.

11 ImageIcon

A ImageIcon control is an implementation of the Icon interface that paints Icons from Images

12 JScrollbar

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

13 JOptionPane

JOptionPane provides set of standard dialog boxes that prompt users for a value or informs them of something.

14 JFileChooser

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

15 JProgressBar

As the task progresses towards completion, the progress bar displays the task s percentage of completion.

16 JSpder

A JSpder lets the user graphically select a value by spding a knob within a bounded interval.

17 JSpinner

A JSpinner is a single pne input field that lets the user select a number or an object value from an ordered sequence.

SWING - Event Handpng

In this chapter, you will learn about Events, its types, and also learn how to handle an event. Example is provided at the end of the chapter for better understanding.

What is an Event?

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

Types of Event

The events can be broadly classified into two categories −

    Foreground Events − These events require direct interaction of the user. They are generated as consequences of a person interacting with the graphical components in the Graphical User Interface. For example, cpcking on a button, moving the mouse, entering a character through keyboard, selecting an item from pst, scrolpng the page, etc.

    Background Events − These events require the interaction of the end user. Operating system interrupts, hardware or software failure, timer expiration, and operation completion are some examples of background events.

What is Event Handpng?

Event Handpng is the mechanism that controls the event and decides what should happen if an event occurs. This mechanism has a code which is known as an 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.

The Delegation Event Model has the following key participants.

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

    Listener − It is also known as event handler. The pstener is responsible for generating a response to an event. From the point of view of Java implementation, the pstener is also an object. The pstener waits till it receives an event. Once the event is received, the pstener processes the event and 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 a separate piece of code.

In this model, the pstener needs to be registered with the source object so that the pstener can receive the event notification. This is an efficient way of handpng the event because the event notifications are sent only to those psteners who want to receive them.

Steps Involved in Event Handpng

Step 1 − The user cpcks the button and the event is generated.

Step 2 − The object of concerned event class is created automatically and information about the source and the event get populated within the same object.

Step 3 − Event object is forwarded to the method of the registered pstener class.

Step 4 − The method is gets executed and returns.

Points to Remember About the Listener

    In order to design a pstener class, you have to develop some pstener interfaces. These Listener interfaces forecast some pubpc abstract callback methods, which must be implemented by the pstener class.

    If you do not implement any of the predefined interfaces, then your class cannot act as a pstener class for a source object.

Callback Methods

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

If a component wants some pstener to psten ot its events, the source must register itself to the pstener.

Event Handpng 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.*;

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

   pubpc SwingControlDemo(){
      prepareGUI();
   }
   pubpc 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() {
         pubpc 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 ButtonCpckListener()); 
      submitButton.addActionListener(new ButtonCpckListener()); 
      cancelButton.addActionListener(new ButtonCpckListener()); 

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

      mainFrame.setVisible(true);  
   }
   private class ButtonCpckListener implements ActionListener{
      pubpc void actionPerformed(ActionEvent e) {
         String command = e.getActionCommand();  
         
         if( command.equals( "OK" ))  {
            statusLabel.setText("Ok Button cpcked.");
         } else if( command.equals( "Submit" ) )  {
            statusLabel.setText("Submit Button cpcked."); 
         } else {
            statusLabel.setText("Cancel Button cpcked.");
         }  	
      }		
   }
}

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

D:AWT>javac com	utorialspointguiSwingControlDemo.java

If no error occurs, it means the compilation is successful. Run the program using the following command.

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

Verify the following output.

SWING  Event Handpng

SWING - Event Classes

Event classes represent the event. Java provides various Event classes, however, only those which are more frequently used will be discussed.

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 −

pubpc class EventObject
   extends Object
      implements Seriapzable

Field

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

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

Class Constructors

Sr.No. Constructor & Description
1

EventObject(Object source)

Constructs a prototypical Event.

Class Methods

Sr.No. Method & Description
1

Object getSource()

The object on which the Event initially occurred.

2

String toString()

Returns a String representation of this EventObject.

Methods Inherited

This class inherits methods from the following class −

    java.lang.Object

SWING Event Classes

Following is the pst of commonly used Event classes.

Sr.No. Class & Description
1 AWTEvent

It is the root event class for all SWING events. This class and its subclasses supercede the original java.awt.Event class.

2 ActionEvent

The ActionEvent is generated when the button is cpcked or the item of a pst is double-cpcked.

3 InputEvent

The InputEvent class is the root event class for all component-level input events.

4 KeyEvent

On entering the character the Key event is generated.

5 MouseEvent

This event indicates a mouse action occurred in a component.

6 WindowEvent

The object of this class represents the change in the state of a window.

7 AdjustmentEvent

The object of this class represents the adjustment event emitted by Adjustable objects.

8 ComponentEvent

The object of this class represents the change in the state of a window.

9 ContainerEvent

The object of this class represents the change in the state of a window.

10 MouseMotionEvent

The object of this class represents the change in the state of a window.

11 PaintEvent

The object of this class represents the change in the state of a window.

SWING - Event Listeners

Event psteners represent the interfaces responsible to handle events. Java provides various Event pstener classes, however, only those which are more frequently used will be discussed. Every method of an event pstener method has a single argument as an object which is the subclass of EventObject class. For example, mouse event pstener methods will accept instance of MouseEvent, where MouseEvent derives from EventObject.

EventListner Interface

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

Class Declaration

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

pubpc interface EventListener

SWING Event Listener Interfaces

Following is the pst of commonly used event psteners.

Sr.No. Class & Description
1 ActionListener

This interface is used for receiving the action events.

2 ComponentListener

This interface is used for receiving the component events.

3 ItemListener

This interface is used for receiving the item events.

4 KeyListener

This interface is used for receiving the key events.

5 MouseListener

This interface is used for receiving the mouse events.

6 WindowListener

This interface is used for receiving the window events.

7 AdjustmentListener

This interface is used for receiving the adjustment events.

8 ContainerListener

This interface is used for receiving the container events.

9 MouseMotionListener

This interface is used for receiving the mouse motion events.

10 FocusListener

This interface is used for receiving the focus events.

SWING - Event Adapters

Adapters are abstract classes for receiving various events. The methods in these classes are empty. These classes exist as convenience for creating pstener objects.

SWING Adapters

Following is the pst of commonly used adapters while pstening GUI events in SWING.

Sr.No. Adapter & Description
1 FocusAdapter

An abstract adapter class for receiving focus events.

2 KeyAdapter

An abstract adapter class for receiving key events.

3 MouseAdapter

An abstract adapter class for receiving mouse events.

4 MouseMotionAdapter

An abstract adapter class for receiving mouse motion events.

5 WindowAdapter

An abstract adapter class for receiving window events.

SWING - Layouts

Layout refers to the arrangement of components within the container. In another way, it could be said that layout is placing the components at a particular position within the container. The task of laying out the controls is done automatically by the Layout Manager.

Layout Manager

The layout manager automatically positions all the components within the container. Even if you do not use the layout manager, the components are still positioned by the default layout manager. It is possible to lay out the controls by hand, however, it becomes very difficult because of the following two reasons.

    It is very tedious to handle a large number of controls within the container.

    Usually, the width and height information of a component is not given when we need to arrange them.

Java provides various layout managers to position the controls. Properties pke size, shape, and arrangement varies from one layout manager to the other. When the size of the applet or the apppcation window changes, the size, shape, and arrangement of the components also changes in response, i.e. the layout managers adapt to the dimensions of the appletviewer or the apppcation 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 the functionapties of Layout Managers.

Sr.No. Interface & Description
1 LayoutManager

The LayoutManager interface declares those methods which need to be implemented by the class, whose object will act as a layout manager.

2 LayoutManager2

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 pst of commonly used controls while designing GUI using AWT.

Sr.No. LayoutManager & Description
1 BorderLayout

The borderlayout arranges the components to fit in the five regions: east, west, north, south, and center.

2 CardLayout

The CardLayout object treats each component in the container as a card. Only one card is visible at a time.

3 FlowLayout

The FlowLayout is the default layout. It layout the components in a directional flow.

4 GridLayout

The GridLayout manages the components in the form of a rectangular grid.

5 GridBagLayout

This is the most flexible layout manager class. The object of GridBagLayout apgns the component vertically, horizontally, or along their basepne without requiring the components of the same size.

6 GroupLayout

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

7 SpringLayout

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

SWING - Menu Classes

As we know that every top-level window has a menu bar associated with it. This menu bar consists of various menu choices available to the end user. Further, each choice contains a pst of options, which is called drop-down menus. Menu and MenuItem controls are subclass of MenuComponent class.

Menu Hierarchy

Swing Menu Hiearchy

Menu Controls

Sr.No. Class & Description
1 JMenuBar

The JMenuBar object is associated with the top-level window.

2 JMenuItem

The items in the menu must belong to the JMenuItem or any of its subclass.

3 JMenu

The JMenu object is a pull-down menu component which is displayed from the menu bar.

4 JCheckboxMenuItem

JCheckboxMenuItem is the subclass of JMenuItem.

5 JRadioButtonMenuItem

JRadioButtonMenuItem is the subclass of JMenuItem.

6 JPopupMenu

JPopupMenu can be dynamically popped up at a specified position within a component.

SWING - Containers

Containers are an 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 provides the capabipty to add a component to itself. Following are certain noticable points to be considered.

    Sub classes of Container are called as Container. For example, JPanel, JFrame and JWindow.

    Container can add only a Component to itself.

    A default layout is present in each container which can be overridden using setLayout method.

SWING Containers

Following is the pst of commonly used containers while designed GUI using SWING.

Sr.No. Container & Description
1 Panel

JPanel is the simplest container. It provides space in which any other component can be placed, including other panels.

2 Frame

A JFrame is a top-level window with a title and a border.

3 Window

A JWindow object is a top-level window with no borders and no menubar.

Advertisements