Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
7 views

Java GUI Development

This document provides an introduction to Java GUI programming using AWT and Swing. It outlines the differences between AWT and Swing, highlighting Swing's advantages in terms of portability, component variety, and visual consistency across platforms. Additionally, it details the structure of GUI applications, including container classes, component classes, and helper classes, along with examples of how to create and manipulate GUI elements in Java.

Uploaded by

Naoly Get
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
7 views

Java GUI Development

This document provides an introduction to Java GUI programming using AWT and Swing. It outlines the differences between AWT and Swing, highlighting Swing's advantages in terms of portability, component variety, and visual consistency across platforms. Additionally, it details the structure of GUI applications, including container classes, component classes, and helper classes, along with examples of how to create and manipulate GUI elements in Java.

Uploaded by

Naoly Get
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 71

1

METTU UNIVERSITY
FACULTY OF ENGINEERING & TECHNOLOGY
DEPARTMENT OF COMPUTER SCIENCE

Java programming Course


Introduction to Java GUI’s API: AWT and SWING

By: Naol G.
2

Introduction
• GUI: A graphical user interface (GUI) presents a user-friendly
mechanism for interacting with an application.
• It gives an application a distinctive “look” and “feel.”
• Providing different applications with consistent, intuitive user interface
components allows users to be somewhat familiar with an application,
so that they can learn it more quickly and use it more productively.
• GUIs are built from GUI components. These are sometimes called
controls or widgets.
• A GUI component is an object with which the user interacts via the
mouse, the keyboard or another form of input, such as voice
recognition.
3

Java GUI APIs


• Java has two GUI packages,
• the original Abstract Windows Toolkit (AWT) and
• the newer Swing.
• When java was introduced, the GUI classes were bundled in a
library known as Abstract Windows Toolkit (AWT).
• It is Java’s original set of classes for building GUIs.
• It uses peer components of the OS; It is heavyweight and uses the
native operating system's window routines so the visual effect is
dependent on the run-time system platform.
• For every platform on which Java runs, the AWT components are
automatically mapped to the platform- specific components through
their respective agents, known as peers.
• It is not truly portable as it looks different and lays out inconsistently on
different OSs.
• The application's GUI components display differently on each platform.
• In addition, AWT is adequate for many applications but it is difficult to
build an attractive GUI.
4

• Swing: is designed to solve AWT’s problems (since Java 2).


• It is 99% java; It is lightweight components as drawing of
components is done in java.
• Swing GUI components allow you to specify a uniform look-and-
feel for your application across all platforms.
• It also lays out consistently on all Oss. It has much bigger set of
built-in components and uses AWT event handling.
• Swing is built “on top of” AWT, so you need to import AWT and use
a few things from it.
• Swing is bigger and slower. Swing is more flexible and better
looking.
• Swing and AWT are incompatible.
• Thus, you can use either, but you can’t mix them
5

• Basic components/controls are practically the same in


both.
• For example:
• AWT: Button b = new Button ("OK");
• Swing: JButton b = new JButton("OK");
• Swing gives far more options for everything (buttons with
pictures on them, etc.).
• AWT classes are contained inside package java.awt
while Swing classes are located in package javax.swing.
6

Swing vs. AWT


• First Java GUI library was known as the Abstract Windows Toolkit (AWT).
• AWT is fine for developing simple graphical user interfaces, but not for
complex GUI projects.
• A newer, more robust, and flexible library is known as Swing components.
• Swing components are less dependent on the target platform and use
less of the native GUI resource.
• Swing components that don’t rely on native GUI are referred to as
lightweight components and AWT components are referred to as
heavyweight components.
• To distinguish new Swing component classes from their older AWT
counterparts, Swing GUI component classes are named with a prefixed J.
• Although AWT components are still supported in Java, it is better to learn
to how program using Swing components, because the AWT user-
interface components will eventually fade away
7

Difference Between AWT and Swing


• Definition
• AWT is a collection of GUI components (widgets) and
other related services required for GUI programming in
Java.
• Swing is a part of Java Foundation Classes (JFC) that
is used to create Java-based Front end GUI
applications.
• Hence, this explains the main difference between AWT
and Swing in Java.
• Type
• AWT components are heavyweight while Swing
components are lightweight.
8

• Platform Dependency
• Another major difference between AWT and Swing in Java is
that AWT is platform dependent while Swing is platform
independent.
• Display
• Moreover, AWT does not support pluggable look and feel.
• Swing supports a pluggable look and feel.
• Components
• Also, Swing has more advanced components than AWT.
• Speed
• Furthermore, execution of AWT is slower. However, Swing
executes faster.
9

• Package
• The programmer has to import the javax.awt package
to develop an AWT-based GUI.
• However, the programmer has to import javax.swing
package to write a Swing application.
10

Java AWT, Swing and Applet Components Hierarchy


11

• Generally, the Java GUI APIs are categorized into


three groups.
• Container class
• Component classes and
• Helper class.
12

GUI Container classes


• A GUI is built by putting components/controls into containers.
• Thus, container is used to group components.
• Frames, Panels and applets are examples of containers.

• Important Container classes are JFrame, JApplet, JDialog and


JPanel.
• Frame:
• A resizable, movable window with title bar and close button.
• Usually it contains JPanels.
• It is a container that holds other Swing user-interface components in Java GUI
application.
• JPanel:
• JPanel is a region internal to a JFrame or another JPanel.
• It is used for grouping components together.
• JPanel is optionally bounded by a visible border .
• It lives inside some enclosing Container.
• Panels can be nested, that is, you can place panels inside a container that includes
a panel.
• In fact, every frame has at least one pane, the default “Content Pane”.
13

GUI Component classes


• GUI Components or Controls (also known as "widgets") are the
basic user interface elements the user interacts with.
• These include labels, buttons and text fields.
• The visual arrangement of the components depends on the
container's layout (which are part of helper classes)
• Here is a list of controls in the javax.swing package.
• Input Components
• Buttons ( JButton, JRadioButtons, JCheckBox)
• Text (JTextField, JTextArea)
• Menus (JMenuBar, JMenu, JMenuItem)
• Sliders (JSlider)
• JComboBox (uneditable) (JComboBox)
• List (Jlist)
14

• Information Display Components


• JLabel
• Progress bars (JProgressBar)
• Tool tips (using JComponent's setToolTipText(s) method)

• Choosers
• File chooser (JFileChooser)
• Color chooser (JColorChooser)
• More complex displays
• Tables (JTable)
• Trees (JTree)
15

GUI helper classes


• Helper classes are used to describe the properties of GUI
components.
• It encompasses the classes for graphics context, colors,
fonts and dimension
• Graphics:
• It is an abstract class that provides a graphical context for drawings
strings, lines, and simple shapes.
• Color:
• It deals with the colors of GUI components.
• For example, we can specify background colors in components like
JFrame and JPanel while we can specify colors of lines, shapes
and etc.
16

• Font:
• It specifies fonts for the text and drawings on GUI
components.
• Font is available on the java.awt package.
• Example:
• panel1.setFont(new Font("Serif",Font.TRUETYPE_FONT +
Font.ITALIC + Font.BOLD,20));
17

LayoutManager
• LayoutManager is an interface whose instances specify
how components are arranged in a container.
• There are different types of layouts.
• FlowLayout, GridLayout and BorderLayout are three examples of
the layouts.
• These layouts are found in the java.awt package of JDK API.
• Let us see an example using one of these three layout
types. LayoutManager lay_out = new FlowLayout();
JFrame frame = new JFrame(“I am a container");
frame .setLayout(lay_out);
setLayout(new FlowLayout());//default one
setLayout(new FlowLayout(FlowLayout.LEFT));
setLayout(new FlowLayout(FlowLayout.LEFT, 20,30));
18

Steps in building GUI Application


• 1. Creating GUI Containers:
• Create a container that could contain components or other
containers.
• We need to create either a frame or an applet to hold the user-
interface components.
• Frame:
• It is an independent window that has decorations such as a border, a
title and buttons for closing, minimizing and maximizing the window.
• Frame is a window that is not contained inside another window.
• A frame can be moved around on the screen independently of any other
GUI windows.
• Applications with a GUI typically use at least one frame.
• Frame is the basis to contain other user interface components in Java
GUI applications.
19

• The following statement creates a window with title “My First JFrame”
• JFrame frame = new Jframe(“My First JFrame”);

• The JFrame class has the following two constructors:


• JFrame(): This constructor constructs a new frame with no title and it is
initially invisible.
• JFrame(String title): This constructor constructs a new, initially
invisible frame with specified title
20

Methods of JFrame
• Some of the methods of JFrame class are described here
in class diagram:
21

• setBounds(int x, int y, int width,Int height) :


• It is another method of JFrame class that encompasses the methods
setLocation(int x, int y) and setSize(int width, int height).
• It specifies the size of the frame and the location of the upperbleft corner.
• This puts the upper left corner at location (x, y), where x the number of
pixels from the left of the screen and y is the number from the top of the
screen, height and width are as before.
• public void setDefaultCloseOperation(int mode):
• It is a method of JFrame class that is used to specify one of several
options for the close button.
• Every JFrame instance window has a close button.
• We can program how the window reacts when this close button is clicked.
• Use one of the following constants to specify your choice:
• JFrame.EXIT_ON_CLOSE: exit the application.
• JFrame.HIDE_ON_CLOSE: Hide the frame, but keep the application running.
• JFrame.DO_NOTHING_ON_CLOSE: Ignore the click.
22

• Example: Here is a java code that creates a window/frame with the specified
title, location, size, frame visibility and default close operation
import javax.swing.*;
public class JFrameSample {
public static void main(String[] args) {
JFrame frame = new JFrame(“First JFrame");
frame.setSize(400, 300);

frame.setLocationRelativeTo(null);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
• Here is another way of writing the above code (by extending JFrame):
import javax.swing.JFrame;
public class Simple extends JFrame {
public Simple() {
setSize(300,200);
setTitle("First JFrame");
setLocationRelativeTo(null);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setVisible(true);
}
public static void main(String[] args) {
Simple simple = new Simple();
}}
23

• 2. Create some more Components (such as buttons and


text areas)
• JButton:
• A button is a component that triggers an action event when
clicked.
• A JButton component can be created using one of the following
constructors.
• JButton(): Creates a default button with no text and icon.
• JButton(Icon icon): Creates a button with an icon.
• JButton(String text): Creates a button with text.
• JButton(String text, Icon icon): Creates a button with text and an icon.
24

• JButton class has different methods including the


following:
• public void setText(String text) : Sets the button's text.
• public String getText(): Returns the button's text.
• public void setEnabled(boolean b) : Enables (or disables) the
button.
• public void setSelectedIcon(Icon selectedIcon): Sets the selected
icon for the button.
• public boolean isSelected() : Returns the state of the button. True if
the toggle button is selected, false if it's not.
• Here two alternative examples that create a JButton component
with text “Click Here”.
JButton button= new JButton();
button.setText(“Click Here”);
OR
JButton button= new JButton(“Click Here");
25

• JLabel:
• A label is a display area for a short text(a non-editable), an image,
or both.
• A JLabel component can be created using one of the following
constructors:
• JLabel(): Creates a default label with no text and icon.
• JLabel(String text): Creates a label with text.
• JLabel(Icon icon): Creates a label with an icon.
• JLabel(String text, int horizontalAlignment): Creates a label with a text
and the specified horizontal alignment.
• JLabel(Icon icon, int horizontalAlignment): Creates a label with an icon
and the specified horizontal alignment.
• JLabel(String text, Icon icon, int horizontalAlignment): Creates a label
with text, an icon, and the specified horizontal alignment.
26

• JLabel component has various methods including the


following:
• public String getText(): Returns a string containing the text in the
label component
• public void setText(String): Sets the label component to contain the
string value
• public Icon getIcon(): Returns the graphic image (icon) that the
label displays.
• public void setIcon(Icon icon): Defines the icon this component will
display. If the value of icon is null, nothing is displayed.
27

• For example, JLabel can be used as follows.


// Create an image icon from image file
ImageIcon icon = new ImageIcon("image/grapes.gif");

// Create a label with text, an icon, with centered horizontal alignment


JLabel jlbl = new JLabel("Grapes", icon, SwingConstants.CENTER);

// Set label's text alignment and gap between text and icon
jlbl.setHorizontalTextPosition(SwingConstants.CENTER);
jlbl.setVerticalTextPosition(SwingConstants.BOTTOM);
jlbl.setIconTextGap(5);
28

• JTextField:
• A text field is a box that contains a line of text.
• The user can type text into the box and the program can get it and
then use it as data.
• The program can write the results of a calculation to a text field.
• Text fields are useful in that they enable the user to enter in
variable data (such as a name or a description).
• JTextField is swing class for an editable text display.
29

• JTextField components can be created using one of the


following constructors:
• JTextField(): it creates a default empty text field with
number of columns set to 0.
• JTextField(int columns): it creates an empty text field
with the specified number of
• columns.
• JTextField(String text): it creates a text field initialized
with the specified text.
• JTextField(String text, int columns): it creates a text field
initialized with the specified text and the column size.
30

• JTextfield class has the following methods:


• public String getText(): returns the string from the text field.
• public void setText(String text): puts the given string in the text
field.
• public void setEditable(boolean editable): enables or disables
the text field to be edited. By default, editable is true.
• public void setColumns(int): sets the number of columns in this
text field. The length of the text field is changeable.
• public void select(int selectionStart, int selectionEnd): Selects
the text between the
• specified start and end positions.
• public String getSelectedText(): Returns the text value that has
been highlighted in the
• text field.
• public void append(String value): Appends the text value of the
string to the already existing text in the component.
31

• Here is an example in which JTextField is used.


JLabel Fname= new JLabel("First Name");
JTextField text = new JTextField(10);
JLabel Lname= new JLabel("Last Name");
JTextField text1 = new JTextField("Text1",10);
text.setEditable(false);

add(Fname);
add(text);
add(Lname);
add(text1);
32

• JPasswordField:
• Allows the editing of a single line of text where the view indicates
something was typed, but does not show the original characters.
• JPasswordField component can be created using one of the
following constructors:
• JPasswordField(): Constructs a new JPasswordField, with a default
document, null starting text string, and 0 column width
• JPasswordField(int columns): Constructs a new empty
JPasswordField with the specified number of columns
• JPasswordField(String text): Constructs a new JPasswordField
initialized with the specified text.
• JPasswordField(String text, int columns) : Constructs a new
JPasswordField initialized with the specified text and columns.
33

• JTextArea:
• If you want to let the user enter multiple lines of text,
you cannot use text fields unless you create several of
them.
• The solution is to use JTextArea class, which enables
the user to enter multiple lines of text.
• JTextArea components can be created using one of the
following constructors:
• JTextArea(int rows, int columns): creates a text area with the specified
number of rows and columns.
• JTextArea(String s, int rows, int columns): creates a text area with the
initial text and the number of rows and columns specified.
34

• JCheckBox:
• It is a widget that has two states. On and Off.
• It is a box with a label.
• If the checkbox is checked, it is represented by a tick in a box.
• JCheckBox component can be created using one of the following
constructors:
• JCheckBox() :creates an initially unselected check box button with no text, no
icon
• JCheckBox(Icon icon) : creates an initially unselected check box with an icon
• JCheckBox(Icon icon, boolean selected) : creates a check box with an icon and
specifies
• whether or not it is initially selected.
• JCheckBox(String text) : creates an initially unselected check box with text.
• JCheckBox(String text,boolean selected): creates a check box with text and
specifies whether or not it is initially selected.
• JCheckBox(String text,Icon icon) : creates an initially unselected check box with
the specified text and icon.
• JCheckBox(String text, Icon icon, Boolean selected) : creates a check box with
text and icon, and specifies whether or not it is initially selected
35

• Example:

JCheckBox red = new JCheckBox(“Red”, true);


JCheckBox blue = new JCheckBox(“Blue”);
JCheckBox green = new JCheckBox(“Green”);
JCheckBox yellow = new JCheckBox(“Yellow”)
36

Creating Menu Driven Java Application


• We can create a menu driven application in java from
which we can choose an activity.
• There are three important swing components for the
development of menu driven application.
• These are: JMenuBar, JMenu and JMenuItem
• JMenuBar:
• It is used to create the menu bar.
• Menu bar is created using the constructor JMenubar().
• For example, we may create a menu bar as follows.
JMenuBar jmb = new JMenuBar();
• Once a menu bar is created, the menu bar is going to be
embedded onto the container frame using the method
• setJMenuBar(JMenuBar mbr).
37

• JMenu:
• It is used to create menu or submenus.
• The constructor JMenu(String name) can be used to create a
menu/submenu.
• For example, JMenu fileMenu = new JMenu(“File”).
• Once menus are created using JMenu, these menus can be added
onto the menu bar using the function add(JMenu menu).
• Assume we have created two menu component file and edit as
follow
JMenu fileMenu = new JMenu(“File”). JMenu editMenu = new JMenu(“Edit”).

• We can add these menu components to the menu bar we created


earlier as follow
• Jmb.add(fileMenu);
• Jmb.add(editMenu)
38

• JMenuItem:
• This component is used to add menu items under menu
components.
• The constructor JMenuItem(String item) is used to create such
items. Once the items are created the method add(JMenuItem
item) can be used to add the item to a menu component.

• For example, let us create two menu items under the file menu.

JMenuItem menuItemNew = new JMenuItem(“New”);


JMenuItem menuItemOpen = new JMenuItem(“Open”);

fileMenu.add(menuItemNew);
fileMenu.add(menuItemOpen);
39

• Creating submenu under a menu:


• It is possible to have a menu under another menu, that
is, creating a submenu under a menu.
• First, the submenu will be created using the Jmenu
constructor.
• Then, we will use the method add(JMenu menu) to add
the submenu under a menu.
• Let u observe the complete code of the following
example and notice how a submenu is added to a
menu.
40
Example: consider the following example that creates the output displayed next to the code
//adding Submen 3
import java.awt.event.ActionEvent; 1 JMenu openMenu = new JMenu("Open");
import java.awt.event.ActionListener; //items under open
• .
import javax.swing.JFrame; JMenuItem openFromLocalDisk = new JMenuItem("Open from local
import javax.swing.JMenu; disk");
import javax.swing.JMenuBar; JMenuItem openFRomNet = new JMenuItem("Open from the
import javax.swing.JMenuItem; network");
import javax.swing.JOptionPane; //add the items to the open JMenu
public class ClassAtMenuing { openMenu.add(openFromLocalDisk);
public static void main(String[] args) { openMenu.add(openFRomNet);
fileMenu.add(openMenu);
fileMenu.add(closeWindow);
JFrame myEditor = new JFrame("My Editor ++"); 2
JMenuBar myMenuBar = new JMenuBar(); closeWindow.addActionListener(new ActionListener(){ 4
myEditor.setJMenuBar(myMenuBar); @Override
public void actionPerformed(ActionEvent e) {
//Create the Menus JOptionPane.showMessageDialog(null, "You are closing
JMenu fileMenu = new JMenu("File"); thed editor");
JMenu editMenu = new JMenu("Edit"); myEditor.dispose();
Menu developersMenu = new JMenu("The }});
Develpers"); //add menu into the menubar
//add meu items under File myMenuBar.add(fileMenu);
JMenuItem itemSave = new JMenuItem("Save"); myMenuBar.add(editMenu);
JMenuItem closeWindow = new JMenuItem("Exit"); myMenuBar.add(developersMenu);
JMenuItem itemOpen = new JMenuItem("Open"); myEditor.setBounds(100, 150, 400, 300);
fileMenu.add(itemSave); myEditor.setDefaultCloseOperation(JFrame.EXIT_ON_
CLOSE);
myEditor.setVisible(true);
}}
41

Output:
42

• Java JRadioButton
• The JRadioButton class is used to create a radio button.
• It is used to choose one option from multiple options.
• It is widely used in exam systems or quiz.
• It should be added in ButtonGroup to select one radio button only.
• Commonly used Constructors:
43

Commonly used Methods


44

Java JRadioButton Example


45

• Java JComboBox
• The object of Choice class is used to show popup menu of choices.
• Choice selected by user
• is shown on the top of a menu.
• It inherits JComponent class.
• Commonly used Constructors:
46

• Commonly used Methods:


47

Java JComboBox Example


48

• Java Jtable
• The JTable class is used to display data in tabular form.
• It is composed of rows and columns.

• Commonly used Constructors:


49

Java JTable Example

Output:
50

• 3. Add your components to your display area:


• choose a layout manager
• Each JFrame contains a content pane.
• A content pane is an instance of java.awt.Container.
• The GUI components such as buttons are placed in the content
pane in a frame.
• Prior to JDK 1.5, you have to use the getContentPane() method in
the JFrame class to return the content pane of the frame, and then
invoke the content pane’s add method to place a component into a
content pane
• This was cumbersome, JDK 1.5 allows you to place the
components to the content pane by invoking a frame’s add method.
51

• This new feature is called content pane delegation.


• Strictly speaking, a component is added into the content pane of
the frame.
• But for simplicity we say that a component is added to a frame.
• When a component is added to a container, a reference to the
component is added to the list of components in the container.
• Below are four alternatives to add a button with text “OK” into a
frame instance, “frame”.
• We assume that the frame has been instantiated somewhere.
52

• Below is a full java code that adds the button to the frame (following
the approach employed by example 3 above)

• When you run the above program MyFrameWithComponents, the button is always
centered in the frame and occupies the entire frame no matter how you resize it.
• This is because components are put in the frame by the content pane’s layout
manager, and the default layout manager for the content pane places the button in
the center.
• Set layout Manager before adding components.
• In the next section, you will use several different layout managers to place
components in other location as desired.
53

Layout Management
• Layouts tell Java where to put components in containers (JPanel,
content pane, etc).
• Layout manager is created using LayoutManager class.
• Every layout manager class implements the LayoutManager class.
• Each layout manager has a different style of positioning components.
• If you don't specify otherwise, the container will use a default layout
manager.
• Every panel (and other container) has a default layout, but it's better
to set the layout explicitly for clarity.
• Layout managers are set in containers using the
setLayout(LayoutManager) method.
54

• Example:
• Assume we have a Jframe instance called container. If we are
going to add controls inside this container and if we are interested
on the flowlayout, we can set as follow.

LayoutManager layoutManager = new FlowLayout();


container.setLayout(layoutManager);

OR

container.setLayout(new FlowLayout());
55

• Java supplies several layout managers including


• FlowLayout:
• The Simplest layout manager (the default one)Components are
placed left to right in the order in which they were added.
• When one row is filled, a new row is started.
• Components can be right aligned, centered or left aligned by using
• FlowLayout.RIGHT, FlowLayout.CENTER and FlowLayout.LEFT respectivley.
56

• GridLayout:
• The GridLayout manager divides the container up into a given
number of rows and columns.
• All sections of the grid are equally sized and as large as possible.
• GridLayout can be set using one of the constructors depicted
below:
57

• BorderLayout:
• The BorderLayout manager divides the window into five areas:
• East, South, West, North, and Center.
• At most five components can be added.
• If you want more components, add a Panel, then add components
to it.
• Components are added to a BorderLayout by using
add(Component, index) where index is a constant such as:
• BorderLayout.EAST
• BorderLayout.SOUTH
• BorderLayout.WEST
• BorderLayout.NORTH
• BorderLayout.CENTER
58

• BorderLayout can be set using one of the constructors shown below:


59

• 4. Attach Listeners to your components:-


• Interacting with a component causes an Event to occur.
• Usually, we click button, move our mouse pointer onto a text, move our
mouse pointer onto a button, enter a text to a text field and etc.
• When a certain action is performed, some event is fired.
• Listeners are associated with control so that it can sense whenever an
event is fired.
60

• Note that If a component can fire an event, any subclass


of the component can fire the same type of event.
• For example, every GUI component can fire
• MouseEvent, KeyEvent, FocusEvent, and ComponentEvent, since
Component is the superclass of all GUI components.
• Some of the packages of JDK API that we use in handling
event-driven tasks include:
• java.awt.event.ActionEvent
• java.awt.event.ActionListener
• java.awt.event.MouseEvent
• java.awt.event.MouseListener
• java.awt.event.WindowEvent
• java.awt.event.WindowListener
61

• Listeners, registrations, and handling of events:


• Delegation-based model for event handling is employed where a
source object fires an event, and an object interested in the event (a
listener)handles the event.
• For an object to be a listener for an event on a source object, two
things are needed.
• Firstly, the listener object must be an instance of the corresponding
event-listener interface to ensure that the listener has the correct
method for processing the event.
• Java provides a listener interface for every type of event.
• The listener interface is usually named XListener for XEvent, with the
exception of MouseMotionListener.
• For example,
• The corresponding listener interface for ActionEvent is ActionListener and
each listener for ActionEvent should implement the ActionListener interface.
• Secondly, the listener object must be registered by the source object.
62

• Registration methods depend on the event type. For


ActionEvent, the method is addActionListener.
• In general, the method is named addXListener for XEvent.
• A source object may fire several types of events.
• It maintains, for each event, a list of registered listeners and
notifies them by invoking the handler of the listener object to
respond to the event.
• Example:
• Assume I have window/frame that has a label named “Name” and a
text field to enter name.
• There is also a button of which text is “show me my input in
dialog box”.
• Once we enter a name in the text field, we can click the
button to get a dialog box that contain the name we entered
in the text field.
• How can we implement this scenario?
63

• Solution:
• There could be different solutions. But, let us see one way of
setting the layout.
• First, let us create the necessary containers and components with
appropriate layout; then, we will add the components/containers to
the appropriate containers.
64

• If we run the above code, we will get the following GUI application.
65

• But, clicking the button does not do anything as we did not associate
this action on the button with the appropriate event.
• Thus, we are going to improve this code so that clicking the button
shows the desired dialog box.
• We can do this using one of the following three ways.
• The first is register the event listener of the source object and define
the action performed at the same spot or register the event listener on
the source object and define action performed in another class.
• This second way can, in turn, be accomplished in two ways: using an
inner class for the action definition or using another separate class.
• Let us see the implementation using the three approaches.
66

}}
67

} }}
68

} }
69

Output:
70
71

End!
More on chapter-3….

You might also like