0% found this document useful (0 votes)
0 views

GUI

Uploaded by

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

GUI

Uploaded by

africa.facts123
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 24

GUI Programming

GUI Programming

A graphical user interface (GUI) presents a user-friendly mechanism for interacting with an
application.
A GUI (pronounced “GOO-ee”) gives an application a distinctive “look and feel.” GUIs are built from
GUI components. These are sometimes called controls or widgets—short for window gadgets. 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.

Common Terms
Some familiar terms associated with GUI programs include :
a) Window - A GUI program runs within a window. One window at a time has focus and
receives input from the keyboard and mouse.
b) Menus - Commands the program accepts may be organized on menus, usually along the
top of a window.
c) Components-These are sometimes called controls or widgets—short for window gadgets. 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.
d) container is a special component that holds and organizes other components
dialog boxes, applets, frames, panels, etc.
e) An event is an object that represents some activity to which we may want to respond . For
example, we may want our program to perform some action when the following occurs:
the mouse is moved
a mouse button is clicked
the mouse is dragged
f) A listener is an object that awaits an event to occur.
g) Layout manager:An object contained inside frames and other graphical containers that
decides the position and size of the components inside the container.

java.awt and javax.swing packages


Two sets of Java GUI components: java.awt and javax.swing components.
The Abstract Window Toolkit (AWT) is in the package java.awt and swing in javax.swing.
AWT is a set of classes and interfaces that are part of the core Java API. The awt components
look like the native GUI components of the platform on which a Java program executes. For
example, a Button object displayed in a Java program running on Microsoft Windows looks like
those in other Windows applications. On Apple Mac OS X, the Button looks like those in other
Mac applications. Sometimes, even the manner in which a user can interact with an AWT
component differs between platforms. The component’s appearance and the way in which the
user interacts with it are known as its look-and-feel.

java.awt package

Java.awt package provides a set of classes to build user interfaces.


– Window, Button, Textfield, etc..
To build a UI we just instantiate objects from those classes:
GUI Programming

1. Create a window or top-level container


2. Create components and insert them into the top-level container
3. Wait for user interface events to arrive from components (for example, mouse
click,button press,key press etc ). Handle user interface events as they arrive.

Example 1: A simple GUI application using awt package

import java.awt.*;// we use awt package


import java.awt.event.*;
public class MyGuiApplication
{
public static void main(String args[])
{
// create awt frame container and set properties
Frame frm= new Frame(" AWT GUI");
frm.setLayout(new FlowLayout());// set the layout
frm.setBackground(Color.MAGENTA);// sets the color
frm.setFont(new Font("arial",Font.PLAIN,14));// sets the font

// instantiate components

Button b1= new Button("Button 1");


Button b2= new Button("Button 2");
TextField tf= new TextField();

// add components to the frame


frm.add(b1);
frm.add(b2);
frm.add(tf);
frm.pack();
frm.setLocation(50,100);
frm.setVisible(true);

// close the window by handling WindowEvent –windowClosing method


frm.addWindowListener(new WindowAdapter()
{
@Override
public void windowClosing(WindowEvent evt)
{
frm.dispose();
}
});
}
}
GUI Programming

AWT Components Peers


Native operating system components are connected to a Java program through peer classes.
AWT components are called heavyweight because for each component created three resources
need to be created:
1. Java class representing the component
2. Java class representing the peer
3. Native operating system component

Each java interpreter knows how to do it in the platform it is running.

Swing API

Swing API is a set of extensible GUI Components to ease the developer's life to create JAVA
based Front End/GUI Applications. It is built on top of AWT API and acts as a replacement of
AWT API, since it has almost every control corresponding to AWT controls. The diagram below
shows the inheritance hierarchy of classes from which lightweight Swing components inherit their
common attributes and behaviors.

Class Component (package java.awt) is a superclass that declares the common features of GUI
components in packages java.awt and javax.swing. A Component is the abstract base class for the
GUI Programming

non-menu user-interface controls of SWING. Component represents an object with graphical


representation.

Any object that is a Container (package java.awt) can be used to organize Components by
attaching the Components to the Container. A Container is a component that can contain other
SWING components. Containers can be placed in other Containers to organize a GUI.
Class JComponent (package javax.swing) is a subclass of Container.
JComponent is the superclass of all lightweight Swing components and declares their common
attributes and behaviors. Because JComponent is a subclass of Container, all lightweight
Swing components are also Container.

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 like Tree, TabbedPane,
slider, colorpicker, and table controls.
 Highly Customizable − Swing controls can be customized in a very easy way as visual
appearance 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.
 Tool tips- Brief descriptions of a GUI component’s purpose (called tool tips) that are
displayed when the mouse cursor is positioned over the component for a short time.

AWT swing
Platform dependent –dependent on Platform-independent-purely scripted
the platform in java
Heavyweight Largely lightweight-most components
do not need any native OS objects for
implementing their functionality.
Do not support pluggable look and Support pluggable look and feel
feel
Components are less in number Richer controls both in numbers and feature
and features. support
GUI Programming

Does not support MVC pattern Supports MVC pattern

import java.awt import javax.swing

GUI Building with swing

Like the with the awt package, programming a user interface with swing involves the following
aspects:

1) Creating a top- level container and its associated layout manager


2) Adding the components. These are the core visual elements the user eventually sees and
interacts with. A list of common swing components is presented below.
3) Defining how UI elements should be organized on the screen and provide a final look and
feel to the GUI (Graphical User Interface).
4) Handling events .Giving behavior to the components.These are the events which occur
when the user interacts with UI elements. This is called event handling.

A list of common swing components


JLabel
1
A JLabel object is a component that displays uneditable text and/or icons
JButton
2
This class creates a labeled button. Triggers an event when clicked with the mouse.
JColorChooser
3 A JColorChooser provides a pane of controls designed to allow a user to manipulate and
select a color.
JCheckBox
4 A JCheckBox is a graphical component that can be in either an on (true) or off (false) state.
Specifies an option that can be selected or not selected
JRadioButton
5 The JRadioButton class is a graphical component that can be in either an on (true) or off
(false) state in a group.
JList
6 A JList component presents the user with a scrolling list of text items. The user can make a
selection by clicking on any one of them. Multiple elements can be selected.

7 JComboBox
A drop-down list of items from which the user can make a selection
8 JTextField
GUI Programming

A text field is a basic text control that enables the user to type a small amount of text. When the
user indicates that text entry is complete (usually by pressing Enter), the text field fires an action
event. If you need to obtain more than one line of input from the user, use a text area. A
JTextField object is a text component that allows for the editing of a single line of text.
JPasswordField
9
A JPasswordField object is a text component specialized for password entry.
JTextArea
A JTextArea object is a text component that allows editing of a multiple lines of text. A text
10
area is a multi-line text field

ImageIcon
11 A ImageIcon control is an implementation of the Icon interface that paints Icons from
Images
JScrollbar
12 A Scrollbar control represents a scroll bar component in order to enable the user to select
from range of values.
JOptionPane
13 JOptionPane provides set of standard dialog boxes that prompt users for a value or informs
them of something.
JFileChooser
14
A JFileChooser control represents a dialog window from which the user can select a file.
JProgressBar
15 As the task progresses towards completion, the progress bar displays the task's percentage of
completion.
JSlider
16
A JSlider lets the user graphically select a value by sliding a knob within a bounded interval.
JSpinner
17 A JSpinner is a single line input field that lets the user select a number or an object value
from an ordered sequence.

JOptionPane class

Most applications on a daily basis use windows or dialog boxes (also called dialogs) to interact
with the user.

Dialog boxes are windows in which programs display important messages to the user or obtain
information from the user.
Java’s JOptionPane class (package javax.swing) provides prebuilt dialog boxes for both input
and output.

These dialogs are displayed by invoking static JOptionPane methods.


Advantages:
 simple
GUI Programming

 flexible (in some ways)


Disadvantages:
 created with static methods; not very object-oriented
 not very powerful (just simple dialog boxes)

Dialog Types
The JOptionPane provides the following dialog boxes:
1. Message Dialog

To create the message dialog, you invoke the JOptionPane’s showMessageDialog method.
The method is overloaded with the following two versions:
a) showMessageDialog(<parent>, <message>)
Displays a message on a dialog with an OK button.
Eg JOptionPane.showMessageDialog(null, “Hello World”);

b) showMessageDialog(<parent>, <message>,<title>,<messagetype>)

e.g JOptionPane.showMessageDialog(null, “Hello World”, “Message


Dialog”,JOptionPane.PLAIN_MESSAGE);

 The first argument helps the Java application determine where to position the dialog box. If
the first argument is null, the dialog box is displayed at the center of your screen.
 The second argument is the message to display.
 The third argument—"Message Dialog "—is the String that should appear in the title bar at the top
of the dialog.
 The fourth argument—JOptionPane.PLAIN_MESSAGE—is the type of message dialog to display.
A PLAIN_MESSAGE dialog does not display an icon to the left of the message.

Note : message type can be any of the following integer valued constants :
.INFORMATION_MESSAGE, PLAIN_MESSAGE, WARNING_MESSAGE,
ERROR_MESSAGE, QUESTION_MESSAGE

2. Input Dialog

The JOptionPane static method showInputDialog displays an input dialog.


showInputDialog(<parent>, <message>)
Displays a message and text field for input; returns the user's value entered as a String.
Eg

String firstNumber = JOptionPane.showInputDialog( "Enter first integer" );

3. Confirm Dialog

The JOptionPane static method showConfirmDialog displays a confirm dialog


 It displays a message and list of choices Yes, No, Cancel
 returns user's choice as an int with one of the following values:
JOptionPane.YES_OPTION
JOptionPane.NO_OPTION
JOptionPane.CANCEL_OPTION
GUI Programming

Example2: Displaying various dialogs

import javax.swing.JOptionPane;
public class DialogBoxes
{
public static void main(String args[])
{

//message dialog
JOptionPane.showMessageDialog(null, "Welcome to GUI programming",
"GUI",JOptionPane.INFORMATION_MESSAGE);
// input Dialog
String name=JOptionPane.showInputDialog(null,"Enter your name");
//message dialog
JOptionPane.showMessageDialog(null, name, "Name
Dialog",JOptionPane.INFORMATION_MESSAGE);
// confirm Dialog
int choice = JOptionPane.showConfirmDialog(null, "Restart your computer?");
if (choice == JOptionPane.YES_OPTION)
JOptionPane.showMessageDialog(null, "Restarting!");
else if(choice == JOptionPane.NO_OPTION)
JOptionPane.showMessageDialog(null, "Restart later !");
else
JOptionPane.showMessageDialog(null, "Cancel Restart!");
}
}

Example 3: Addition Program using Dialogs

// Addition program that uses JOptionPane for input and output.


import javax.swing.JOptionPane; // program uses JOptionPane

public class Addition


{
public static void main( String[] args )
{
// obtain user input from JOptionPane input dialogs
String firstNumber = JOptionPane.showInputDialog( "Enter first integer" );
String secondNumber = JOptionPane.showInputDialog( "Enter second integer" );

// convert String inputs to int values for use in a calculation


int number1 = Integer.parseInt( firstNumber );// convert string input to an integer using Integer Wrapper class
int number2 = Integer.parseInt( secondNumber );
int sum = number1 + number2; // add numbers

// display result in a JOptionPane message dialog


JOptionPane.showMessageDialog( null, "The sum is " + sum,
"Sum of Two Integers", JOptionPane.PLAIN_MESSAGE );
GUI Programming

}// end main


}// end class addition

Input Dialogs:
The JOptionPane static method showInputDialog displays an input dialog, using the method’s
String argument ("Enter first integer") as a prompt. From the example the following statement calls the
showInputDialog method.
String firstNumber = JOptionPane.showInputDialog( "Enter first integer" );

Message Dialogs:
The JOptionPane static method showMessageDialog displays a message dialog. In the example
the statement: JOptionPane.showMessageDialog( null, "The sum is " + sum, "Sum of Two
Integers", JOptionPane.PLAIN_MESSAGE ); is a call to the message dialog.

Container
Most GUIs are not composed of option panes; they are too limited. Instead, typical GUI
applications include containers such as frames , windows, panels that can hold other components.
A container is an object that holds components; it also governs their positions, sizes, and
resizing behavior.
In general, all containers have the following public methods:
 public void add(Component comp)
 public void add(Component comp, Object info)
Adds a component to the container, possibly giving extra information about where to
place it.
 public void remove(Component comp)
Removes the given component from the container.
 public void setLayout(LayoutManager mgr)
Uses the given layout manager to position the components in the container.
 public void validate()
You should call this if you change the contents of a container that is already on the
screen, to make it re-do its layout.

A frame is a container component used for stand-alone GUI-based applications. It is a top-level


window with a title and a border. The size of the frame includes any area designated for the border.

A panel is a container, but unlike a frame, it cannot be displayed on its own


• it must be added to another container
• it helps organize the components in a GUI

Example 4: A simple JFrame Application

import java.awt.*;
GUI Programming

import javax.swing.*;
public class SimpleFrame {
public static void main(String[] args) {
JFrame frame = new JFrame();
frame.setForeground(Color.WHITE);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLocation(new Point(10, 50));
frame.setSize(new Dimension(300, 120));
frame.setTitle("A frame");
frame.setVisible(true);
}
}

Example 5: Using JPanel


import javax.swing.*;
public class TestPanel
{
public static void main(String args[])
{
// create top level container
JFrame frm= new JFrame("Panel in Frame");
// create panel container
JPanel pan= new JPanel();
//create other components
JButton bt1= new JButton("One");
JButton bt2= new JButton("One");
JLabel lb1= new JLabel("Number1");
JLabel lb2= new JLabel("Number2");
JTextField tf= new JTextField(20);

// add the components to a panel


pan.add(lb1);
pan.add(bt1);
pan.add(lb2);
pan.add(bt2);
pan.add(tf);
// add the panel to the frame
frm.add(pan);
frm.setVisible(true);
frm.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
}

Extending JFrame Class


GUI Programming

You could also create a class that extends JFrame class.


Note with this approach you call JFrame methods directly without creating an object
Example 5 b
import java.awt.FlowLayout;// specifies how components are arranged
import javax.swing.JFrame;// provides basic window features
import javax.swing.JLabel; // displays text and images
import javax.swing.SwingConstants;
// common constants used with Swing
import javax.swing.Icon; // interface used to manipulate images
import javax.swing.ImageIcon; // loads images

public class LabelFrame extends JFrame //extending JFrame


{
private final JLabel label1;// JLabel with just text
private final JLabel label2; // JLabel constructed with text and icon
private final JLabel label3; // JLabel with added text and icon

// LabelFrame constructor adds JLabels to JFrame


public LabelFrame()
{
super("Testing JLabel");
setLayout(new FlowLayout()); // set frame layout
// JLabel constructor with a string argument
label1 = new JLabel("Label with text");
label1.setToolTipText("This is label1");
add(label1); // add label1 to JFrame
// JLabel constructor with string, Icon and alignment arguments
//have an appropriate icon in the current folder
Icon bug = new ImageIcon(getClass().getResource( "forward.gif"));
label2 = new JLabel("Label with text and icon", bug,
SwingConstants.LEFT);
label2.setToolTipText("This is label2");
add(label2); // add label2 to JFrame
label3 = new JLabel(); // JLabel constructor no arguments
label3.setText("Label with icon and text at bottom");
label3.setIcon(bug); // add icon to JLabel
label3.setHorizontalTextPosition(SwingConstants.CENTER);
label3.setVerticalTextPosition(SwingConstants.BOTTOM);
label3.setToolTipText("This is label3");
add(label3); // add label3 to JFrame
}

public static void main(String[] args)


{
LabelFrame labelFrame = new LabelFrame();
GUI Programming

labelFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
labelFrame.setSize(260, 180);
labelFrame.setVisible(true);
}
}

LAYOUT MANAGERS

When building a GUI, you must attach each GUI component to a container, such as a window
created with a JFrame.
Also, you typically must decide where to position each GUI component, known as specifying the
layout. Java provides several layout managers that can help you position components.

A layout manager is an object contained inside frames and other graphical containers that
decides the position and size of the components inside the container.

AWT Layout Manager Classes


The layout manager is associated with every Container object. Each layout manager is an object
of the class that implements the LayoutManager interface. Java provides various layout
managers to position the controls. Properties like size, shape, and arrangement varies from one
layout manager to the other.

Following is the list of commonly used layouts while designing GUI using AWT.

Sr.No. Layout Manager & Description


Border Layout
1
The borderlayout arranges the components to fit in the five regions: east, west,
north, south, and center.
CardLayout
2
The CardLayout object treats each component in the container as a card. Only one
card is visible at a time.
FlowLayout

The FlowLayout is the default layout. It layout the components in a directional flow.
3 The components are placed on a container from left to right in the order in which they’re
added. When no more components can fit on the current line, they continue to display
left to right on the next line. If the container is resized, a FlowLayout reflows the
components, possibly with fewer or more rows based on the new container width.
4 GridLayout
GUI Programming

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


GridBagLayout

5 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 the same size.
GroupLayout
6
The GroupLayout hierarchically groups the components in order to position them in
a Container.
SpringLayout
7
A SpringLayout positions the children of its associated container according to a set
of constraints.

Container panel = new JPanel();// a variable of container assigned JPanel object


panel.setLayout(new GridLayout(2,3));// set the layout to a 2 by 3 grid
panel.add(new JButton("Button 1"));

Example : FlowLayout Manager

import java.awt.*;
import javax.swing.*;
public class FlowLayoutExample {
public static void main(String[] args) {
JFrame frame = new JFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(new Dimension(320, 75));
frame.setTitle("Flow layout");
frame.setLayout(new FlowLayout());// set the layout
frame.add(new JLabel("Type your ZIP Code: "));
frame.add(new JTextField(5));
frame.add(new JButton("Submit"));
frame.setVisible(true);
}
}

Example 6: GridLayout

import java.awt.*;
import javax.swing.*;
public class GridLayoutExample {
public static void main(String[] args) {
JFrame frame = new JFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
GUI Programming

frame.setSize(new Dimension(300, 120));


frame.setTitle("The grid");
// 2 rows, 3 columns
frame.setLayout(new GridLayout(2, 3));
for (int i = 1; i <= 6; i++) {
JButton button = new JButton();
button.setText("Button " + i);
frame.add(button);
}
frame.setVisible(true);
}
}

Example 7: BorderLayout

import java.awt.*;
import javax.swing.*;
public class BorderLayoutExample {
public static void main(String[] args) {
JFrame frame = new JFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(new Dimension(210, 200));
frame.setTitle("Run for the border");
frame.setLayout(new BorderLayout());
frame.add(new JButton("north"), BorderLayout.NORTH);
frame.add(new JButton("south"), BorderLayout.SOUTH);
frame.add(new JButton("west"), BorderLayout.WEST);
frame.add(new JButton("east"), BorderLayout.EAST);
frame.add(new JButton("center"), BorderLayout.CENTER);
frame.setVisible(true);
}
}

Swing Event Handling

What is an Event?
GUI Building is Event Driven. 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, clicking on a button, moving the
mouse, entering a character through keyboard, selecting an item from the list, and scrolling the
page are some of activities that cause an event to occur.

The code that performs a task in response to an event is called an event handler, and the overall
process of responding to events is known as event handling
GUI Programming

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, clicking on a button, moving the mouse, entering
a character through keyboard, selecting an item from list, scrolling the page, etc.
 Background Events − these events do not 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.

Event Classes

Event classes represent the event. Java provides various Event classes. The classes are availed to
programs by importing java.awt. event or javax.swing.event packages. The following are some
of the event classes.

EventObject Class
It is the root class from which all event state objects are derived. This class is defined in java.util
package.

The EventObject class defines one very useful method:

Object getSource() that returns the object that fired the event.

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.

Following is the list of commonly used Event classes.

Sr.No. Class & Description


AWTEvent
1
It is the root event class for all SWING events. This class and its subclasses supercede
the original java.awt.Event class.
ActionEvent
2
The ActionEvent is generated when the button is clicked or the item of a list is
double-clicked.
GUI Programming

InputEvent
3
The InputEvent class is the root event class for all component-level input events.
KeyEvent
4
On entering the character the Key event is generated.
MouseEvent
5
This event indicates a mouse action occurred in a component.
WindowEvent
6
The object of this class represents the change in the state of a window.
AdjustmentEvent
7
The object of this class represents the adjustment event emitted by Adjustable objects.
ComponentEvent
8
The object of this class represents the change in the state of a window.
ContainerEvent
9
The object of this class represents the change in the state of a window.
MouseMotionEvent
10
The object of this class represents the change in the state of a window.
PaintEvent
11
The object of this class represents the change in the state of a window.

What is Event Handling?


Event Handling 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.
GUI Programming

Programming for event –driven programming involves the following steps

1) Define and set up the components. The components are the source objects on
which events occur. For example a Button is a source object for action event.
2) Create listener objects. Listeners are objects which are notified whenever a
certain event happens. The listener is responsible for generating a response to an
event.
3) Set up the relationships between the listeners and the components which
generate events of interest. This is called registering the event.
4) Define what happens in response to each event. This is event handling proper

Note

1. The event is named xxEvent ( eg ActionEvent, MouseEvent,KeyEvent….)

2. Components that generate events of type xxEvent have a method called addxxListener (eg.

addActionListener, addKeyListener, addMouseListener…). This method is used to register a


reference to a class that wants to be notified when events of type xxEvent occur.

Eg button.addActionListener(listener);

3. An interface defines the methods that will be used to deliver xxEvents. The interface is called

xxListener (eg ActionListener, MouseListener, ). Classes interested in receiving events of type


xxEvent implement the interface and register themselves with the component.

4. The methods which deliver events of type xxEvent have names with the pattern xx<verb> (eg

actionPerformed, mouseDragged, )

5. If the interface defines more than a few methodsan adapter class is provided. (ActionListener

doesn't have an adapter because it has only one mehtod. WindowAdapter is an example adapter

class.) An adapter class is a convenience class provided for interfaces with more than a few
methods

Example 8: Handling Button’s ActionEvent with ActionListener

import javax.swing.*;// components

import java.awt.event.*;// event package


GUI Programming

import java.awt.*;// layout manager

public class TestActionListener implements ActionListener

public static void main(String args[])

// create a frame

JFrame frame= new JFrame("Listeners ");

frame.setLayout(new FlowLayout());

TestActionListener listener= new TestActionListener();// listener object

JButton but1= new JButton("View");

but1.addActionListener(listener);//register the event and handle the event

frame.add(but1);

frame.setVisible(true);

frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

// implements the method of ActionListener interface

public void actionPerformed(ActionEvent evnt)

// implement what happens when Button is clicked

JOptionPane.showMessageDialog(null,"Button Clicked");

Implementing an Event Handler


GUI Programming

Several approaches possible

A separate class, i.e a top-level class

An inner class that implements an event listener interface

An anonymous inner class

Extending Adapter class

Using a Nested Class to Implement an Event Handler

Java allows you to declare classes inside other classes—these are called nested classes.
Nested classes can be static or non-static. Non-static nested classes are called inner
classes and are frequently used to implement event handlers.

As with other class members, inner classes can be declared public, protected or private.
Since event handlers tend to be specific to the application in which they’re defined,
they’re often implemented as private inner classes or as anonymous inner classes.

Example 9: Using a private inner class

mport javax.swing.*;

import java.awt.*;

import java.awt.event.*;

public class CourseGUI

private final int WIDTH = 300, HEIGHT = 100;

//private JFrame frame;

private JPanel primary;

private JLabel course;

private JRadioButton science, arts, sports;

private String sc = "Science Option";

private String art = "Arts Option";


GUI Programming

private String sprt = "Sports Option.";

public CourseGUI()

//frame= new JFrame("Specialization Options ");

course = new JLabel (sc);

course.setFont (new Font ("Arial", Font.BOLD, 16));

science= new JRadioButton ("Science", true);

science.setBackground (Color.blue);

arts = new JRadioButton ("Arts");

arts.setBackground (Color.red);

sports = new JRadioButton ("Sports");

sports.setBackground (Color.magenta);

ButtonGroup group = new ButtonGroup();

group.add (science);

group.add (arts);

group.add (sports);

OptionListener listener = new OptionListener();

science.addActionListener (listener);

arts.addActionListener (listener);

sports.addActionListener (listener);

primary = new JPanel();

primary.add (science);
GUI Programming

primary.add (arts);

primary.add (sports);

primary.add (course);

primary.setBackground (Color.green);

primary.setPreferredSize (new Dimension(WIDTH, HEIGHT));

//frame.add(getPanel());

//frame.setDefaultCloseOperation (JFrame.EXIT_ON_CLOSE);

//frame.setVisible(true);

public JPanel getPanel()

return primary;

// using an inner class

private class OptionListener implements ActionListener

// Sets the text of the label depending on which radio

// button was pressed.

public void actionPerformed (ActionEvent event)

Object source = event.getSource();

if(source == science)
GUI Programming

course.setText (sc);

else

if(source == arts)

course.setText (art);

else

course.setText (sprt);

public static void main (String[] args)

JFrame optionFrame = new JFrame ("Specialization Options");

optionFrame.setDefaultCloseOperation (JFrame.EXIT_ON_CLOSE);

CourseGUI gui = new CourseGUI();

optionFrame.getContentPane().add (gui.getPanel());

optionFrame.setVisible(true);

 In this example the inner class OptionListener implements interface ActionListener and
declares the only method in that interface—actionPerformed. This method specifies the tasks to
perform when an ActionEvent occurs. When the button is pushed, the JButton object invokes
the actionPerformed method, passing it an ActionEvent .

Using anonymous inner classes


GUI Programming

An anonymous inner class—an inner class that’s declared without a name and typically
appears inside a method declaration. As with other inner classes, an anonymous inner
class can access its top-level class’s members. However, an anonymous inner class has
limited access to the local variables of the method in which it’s declared.

Since an anonymous inner class has no name, one object of the class must be created at
the point where the class is declared.

Refer to Example 1—addWindowListener method

SWING Adapters
An adapter class provides the default implementation of all methods in an event listener
interface. Adapter classes are very useful when you want to process only few of the events that
are handled by a particular event listener interface. Adapters are abstract classes for receiving
various events. The methods in these classes are empty. These classes exist as convenience
for creating listener objects.

You can define a new class by extending one of the adapter classes and implement only those
events relevant to you. -

Since EventListener interface has only one method, it does not have an adapter class.

Sr.No. Adapter & Description


FocusAdapter
1
An abstract adapter class for receiving focus events.
KeyAdapter
2
An abstract adapter class for receiving key events.
MouseAdapter
3
An abstract adapter class for receiving mouse events.
MouseMotionAdapter
4
An abstract adapter class for receiving mouse motion events.
WindowAdapter

Mouse Events and MouseAdapter

Events related to the mouse are separated into mouse events and mouse motion events.
GUI Programming

Mouse Events:

• mouse pressed – the mouse button is pressed down


• mouse released – the mouse button is released
• mouse clicked – the mouse button is pressed down and released without moving
the mouse in between
• mouse entered – the mouse pointer is moved onto (over) a component
• mouse exited – the mouse pointer is moved off of a component

Mouse Motion Events:

• mouse moved – the mouse is moved


• mouse dragged – the mouse is dragged

To satisfy the implementation of a listener interface, empty methods must be provided for
unused events since a class that implements an interface must implements all its methods.

A better approach is to extend the MouseAdapter class by overriding the method or methods of
interest and ignoring the rest.

public class MyClass extends MouseAdapter {


...
someObject.addMouseListener(this);
...
//only implement mouseClicked method and ignore the rest
public void mouseClicked(MouseEvent e) {
...//Event listener implementation goes here...
}
}

Note the Adapter can also be implemented as anonymous or inner class. See example 1

You might also like