0% found this document useful (0 votes)
19 views85 pages

Java GUI Development Guide

Chapter Four discusses the Graphical User Interface (GUI) in Java, focusing on components, layout, and user interaction. It introduces AWT and Swing, highlighting the differences between heavyweight and lightweight components, and explains how to create and manage GUI elements like buttons, labels, and text fields. The chapter also provides examples of using JFrame and JPanel to build a simple application.

Uploaded by

samih4376
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
19 views85 pages

Java GUI Development Guide

Chapter Four discusses the Graphical User Interface (GUI) in Java, focusing on components, layout, and user interaction. It introduces AWT and Swing, highlighting the differences between heavyweight and lightweight components, and explains how to create and manage GUI elements like buttons, labels, and text fields. The chapter also provides examples of using JFrame and JPanel to build a simple application.

Uploaded by

samih4376
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 85

Chapter Four

GUI

7/7/2024 1
GUI
• Stands for Graphical User Interface ("Goo-ee")
• Pictorial interface to a program
– Distinctive "look" and "feel"
• Different applications with consistent GUIs improve
productivity
• Example:
– Menu bar, text field, label etc.
• are built from components
• Component: object with which user interacts
– Examples: Labels, Text fields, Buttons, Checkboxes
• allows us to interact with our programs through mouse
movements, button clicks, key presses, and so on.

7/7/2024 2
• There are three basic things that are necessary to develop a
graphical user interface
– The GUI components sets : - form the interface
• buttons, labels, check boxes, etc
– Component arrangement (Layout): - the scheme whereby the
UI components are arranged to create the interface
– Response to user requests: - the act of associating actions to
user requests, known as 'events'

7/7/2024 3
Using AWT Components
• AWT is Java’s original set of classes for building GUIs
– Uses peer components of the OS;
– heavyweight
– Not truly portable: looks different and lays out inconsistently
on different OSs
• Due to OS’s underlying display management system
• Every GUI component is a subclass of the AWT Component
class (except for menus)

7/7/2024 4
Components and Containers
• The AWT set is structured in a class hierarchy
• every UI component is a descendant of the Component class
• This contains the very basic functionality common to all
components
primitive container

7/7/2024 5
Peers and Platform Independence
• UI components that have peers are called heavyweight
because
– they are rendered in their own (opaque) windows and thus are
expensive to use,
– they must be rectangular and cannot have transparent
backgrounds, and
– they are not willing to being subclassed

7/7/2024 6
Using Peers

Native
Java Java Window
Program AWT System
Peers

• A Java program creates and displays an AWT component,


• Java AWT creates and displays a native component, or
peer.
• By using peers
• Platform controls component appearance
• Inconsistencies in implementations
– Interfacing to native platform error-prone
7/7/2024 7
Lightweight Components
• AWT 1.1 introduced the notion of lightweight components
which:
– are contained within a heavyweight component's window
– Does not have peers
– are rendered in their container's window rather than one of their
own
– do not incur performance penalties and can have transparent
backgrounds
• Almost all Swing components are lightweight ones that extend
either
– java.awt.Component or java.awt.Container

7/7/2024 8
What is Swing?
• The Swing toolkit includes a rich set of components for
building GUIs and adding interactivity to Java applications
• Swing includes all the components you would expect from a
modern toolkit:
– table controls, list controls, tree controls, buttons, and labels
• Swing supports numerous look and feels, including the ability
to create your own look and feel
• Swing is part of the Java Foundation Classes (JFC)
• Features
– Pluggable Look and Feel: - allows a program to have control
over its appearance.
– Data Transfer: - Most programs will want to use drag and drop
or cut, copy and paste
7/7/2024 9
• You MUST import the following packages:
import java.awt.*;
import javax.swing.*;
• Swing Philosophy
– Richer Component Set
• Replaces AWT Component Set
• Adds more complex components
– Swing Components Java-Based
• If problems, same problems everywhere
• The Swing Containment Hierarchy: - typically has at least:
– Top-Level Container: the root container that holds everything
together. e.g. JApplet, JFrame, Window
– Intermediate Container: a container to simplify the
positioning of atomic components. e.g. JPanel, JScrollPane
– Atomic Component: a self-sufficient component not holding
other components. eg. JButton, JLabel
7/7/2024 10
A Visual Guide to Swing Components

JButton

JCheckBox
JList
JComboBox
JTextField

JSlider
JSpinner

JPasswordField

JMenu
JLabel JRadioButton
7/7/2024 11
• Top-Level Containers

JApplet JFrame
JDialog

• General-Purpose Containers

JPanel

JScrollPane

7/7/2024 JTabbedPane 12
Components and Containers
• a Container is a special type of component
• you can add other components.
– Example, JFrame, JApplet, JPanel etc
• All containers have methods to add and remove components

7/7/2024 13
AWT vs. Swing
• Swing does not replace the AWT; it is built on top of it
• All 1.0 AWT components are heavyweight; corresponding
Swing components are lightweight
• Swing component names begin with ``J'':
– Component (AWT) vs. JComponent (Swing)
– Button (AWT) vs. JButton (Swing)
• Always use Swing components; however, since Swing is built
on top of AWT, you will need to know some AWT methods

7/7/2024 14
• Frames
– Frame is a window that is not contained inside another
window.
– Frame is the basis to contain other user interface components
in Java GUI applications.
– JFrame is the application window class
– The JFrame class is special; it draws the window and interacts
with the operating system
– When a JFrame is created, an inner container called the
contentPane is automatically created
– We don't draw graphics directly on JFrame; we draw on the
contentPane

7/7/2024 15
Anatomy of a JFrame

title bar

minimize
maximize
close

The contentPane holds your


content; created automatically
when a JFrame is created
7/7/2024 16
Example: Empty Frame
package swinglab;

import java.awt.*;
import javax.swing.*;
// extends keyword makes Calc a JFrame
public class Calc extends JFrame{
public Calc() {
// get the contentPane and assign it to cp
Container cp = getContentPane();
// exit program when user closes the window
setDefaultCloseOperation(EXIT_ON_CLOSE);
// sets the layout; will be covered in later slide
cp.setLayout(new FlowLayout());
// sets title to "My Funky Calculator"
setTitle("My Funky Calculator");
setSize(1000,700); // Frame has 0 default size
}

7/7/2024 17
public static void main (String[] args){
Calc trial = new Calc();
// Frame is invisible by default
trial.setVisible(true);

// main method exits but user interface


// stays alive
}
}

7/7/2024 18
Using the JPanel Class
• A panel is a type of container
• designed to hold a group of components
• The normal way to display a group of controls is to add those
controls to a panel, and then add the panel to the frame.
• You can bypass the panel and add the controls directly to the
frame if you want.
• Constructor
• JPanel () : -Creates a new panel.
• JPanel(LayoutManager layout): - Creates a new panel with
the specified layout manager.
– The default layout manager is FIowLayout

7/7/2024 19
• Method
• void add (Component c): - Adds the specified component to
the panel.
• void remove (Component c): - Removes the specified
component from the panel.
• void setLayout (LayoutManager layout): - Sets the layout
manager used to control how components are arranged when
the panel is displayed.

7/7/2024 20
Example:
package swinglab;

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

public class Calc extends JFrame{


private JPanel entryPanel;
private JPanel answerPanel;
public Calc() {
Container cp = getContentPane();
setDefaultCloseOperation(EXIT_ON_CLOSE);
cp.setLayout(new FlowLayout());
cp.setBackground(Color.white);
setTitle("My Funky Calculator");
setSize(1000,700);
entryPanel = new JPanel();
entryPanel.setBackground(Color.orange);
answerPanel = new JPanel();
answerPanel.setBackground(Color.yellow);
7/7/2024 21
// . . .
cp.add(entryPanel);
cp.add(answerPanel);
}
public static void main (String[] args){
Calc trial = new Calc();
trial.setVisible(true);
}
}

7/7/2024 22
JComponent
• JComponent: The base class for all Swing components
except top-level containers
• JComponents do not extend their AWT counterparts:
– For example, the JButton class is not a subclass (direct or
indirect) of Button
• Jcomponent’s subclasses present information or interact with
the user
– Examples: labels (JLabels), buttons (JButtons), textfields
(JTextField)

7/7/2024 23
Using Labels
• It is a component that is used to:
– display captions for other controls such as text fields or combo
boxes,
– display informational messages, or
– show the results of a calculation or a database lookup.
– display an image, or it can display both an image and some
text.
• you have complete control over the appearance of the text.
– You can specify the font, size, style (bold, italic) or underlined,
what color the text is displayed as, and so on.

7/7/2024 24
• Constructor
– JLabel ( ): - Creates a new label with no initial text.
– JLabel (String): - Creates a new label with specified text
• Methods
– String getText ( ): - Returns the text displayed
by the label.
– void setText (String text): - Sets the text
displayed by the label.

7/7/2024 25
import java.awt.*;
import javax.swing.*;

public class MyTest extends JFrame {


JLabel myLabel = new JLabel("Hello, World!");

public MyTest() {
super("MyTest");
setSize(350, 100);
getContentPane().add(myLabel);
setDefaultCloseOperation(EXIT_ON_CLOSE);
setVisible(true);

public static void main (String args[]) {


MyTest m = new MyTest();
}
}

7/7/2024 26
Simple Swing Application

7/7/2024 27
Creating Buttons
• JButton is the most commonly used component and used to
create a button the user can click.
• You can either create an empty button or a button with text.
• Constructor
– JButton ( ): - Creates a new button with no initial
text.
– JButton (String text): - Creates a new button
with the specified text.

7/7/2024 28
• Methods
– String getText (): - Returns the text displayed by
the button.
– void setEnabled (boolean value): - Enables or
disables the button. The default setting is true (enabled).
– void setText (String text): - Sets the text
displayed by the button.
– void setVisible (boolean value): - Shows or
hides the button. The default setting is true (the button is
visible).

7/7/2024 29
JTextField - JPassWordField
• They are single-line areas in which text can be entered by
the user from the keyboard or text can simply be displayed
• Constructors
– JTextField(int columns): - Creates an empty text field with
the specified number of columns.
– JTextField(String text): - Creates a text field initialized
with the specified text.
– JTextField(String text, int columns): - Creates a text field
initialized with the specified text and the column size.

7/7/2024 30
• Methods
– int getColomns(): - Returns the number of columns of the text
field
– setColumns(int): - Sets the number of columns in this text
field. The length of the text field is changeable.
– getText(): - Returns the string from the text field.
– setText(String text): - Puts the given string in the text field.
– setEditable(boolean editable): - Enables or disables the text
field to be edited. By default, editable is true.
• Example
– JTextField textField1 = new JTextField("This is the initial
text");
– JTextField textField2 = new JTextField("Initial text", columns);
– textField.setText(“hi);

7/7/2024 31
JPasswordField
– a special kind of text field
• Constructor
– JPasswordField(String text, int columns) - constructs a
new password field.
• Methods
– void setEchoChar(char echo) - sets the echo character for this
password field. A value of 0 resets the echo character to the
default.
– Char[ ] getPassword() - returns the text contained in this
password field.

7/7/2024 32
• JTextArea: a component used to accept multiple line text.
Constructors
– JTextArea( ) - Default constructor - Create an empty text area
– 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.

7/7/2024 33
• JComboBox
– drop-down list of items from which the user can makes
selection by clicking an item or possibly by typing into the box
– Constructor
• JComboBox(String str[]);
– Methods
• getSelectedItem(); //returns the selected item
• getSelectedIndex();
• setMaximumRowCount(int n) - maximum of n items will be
displayed if there are more items adds scrollbar.

7/7/2024 34
• JList
• Constructor
– JList(String str[]);
• Method
– int getSelectedIndex();
– Object getSelectedValue();
– Object []ob = getSelectedValues();
– int []idx = getSelectedIndices();
– setListData(ListItems);
• It has no scrollPane, to have scrolling JList we have to add to
the container JScrollPane object.
• Syntax
– container.add(new JScrollPane(obj)); //obj is JList object
– setVisibleRowCount(int n);
7/7/2024 35
• JCheckBox
– JCheckBox and JRadioButton are state buttons on/off
• Constructor
– JCheckBox(String s, Icon i, Boolean state);
– JCheckBox(String label);
– JCheckBox(String s, Boolean state);
• Methods
– void setSelected(boolean state);
– boolean isSelected();
– JRadioButton is similar

7/7/2024 36
import java.awt.*;
import javax.swing.*;
import java.util.*;

public class Calc extends JFrame{

private JLabel letLabel;


private JLabel answerLabel;
private JTextField num1;
private JTextField num2;
private JComboBox operation;
private JButton calculate;
private JButton quit;
private JPanel entryPanel;
private JPanel answerPanel;

static final String ADD_OP = "ADDITION";


static final String SUB_OP = "SUBTRACTION";
static final String MUL_OP = "MULTIPLICATION";
static final String DIV_OP = "DIVISION";
7/7/2024 37
private static final int XSIZE = 1000;
private static final int YSIZE = 700;

public Calc() {
Container cp = getContentPane();
setDefaultCloseOperation(EXIT_ON_CLOSE);
cp.setLayout(new FlowLayout());
cp.setBackground(Color.WHITE);
setTitle("My Funky Calculator");
setSize(XSIZE,YSIZE);

entryPanel = new JPanel();


entryPanel.setBackground(Color.ORANGE);

answerPanel = new JPanel();


answerPanel.setBackground(Color.YELLOW);

letLabel = new JLabel("Let's Calculate!");


entryPanel.add(letLabel);
letLabel.setForeground(Color.GREEN);
7/7/2024 38
num1 = new JTextField("1st Number", 10);
entryPanel.add(num1);
num1.setBackground(Color. LIGHT_GRAY);

num2= new JTextField("2nd Number", 10);


entryPanel.add(num2);
num2.setBackground(Color.LIGHT_GRAY);

operation = new JComboBox();


operation.addItem(ADD_OP);
operation.addItem(SUB_OP);
operation.addItem(MUL_OP);
operation.addItem(DIV_OP);
entryPanel.add(operation);
operation.setBackground(Color.BLUE);

answerLabel = new JLabel("Answer");

7/7/2024 39
entryPanel.add(answerLabel);
answerLabel.setForeground(Color.red);

calculate = new JButton("Calculate");


calculate.setBackground(Color.pink);
answerPanel.add(calculate);

quit = new JButton("Quit");


answerPanel.add(quit);
Color quitter = new Color(50,100,50);
quit.setBackground(quitter);

cp.add(entryPanel);
cp.add(answerPanel);

}
public static void main(String[] args){
Calc trial = new Calc();
trial.setVisible(true);
}
7/7/2024 40
}
7/7/2024 41
Exercise
• Write a program that creates the following image

7/7/2024 42
Layout Managers
• Associated with containers
• provide a level of abstraction to automatically map your user
interface on all windowing systems
• Automate the layout of elements
– When elements are added to the container
– When the window is resized
• automatically adjust the positions and sizes of the elements.
• Layout managers control:
– Where components appear
– What sizes they are
– How they react when they are resized

7/7/2024 43
• Each container has a layout manager to arrange the UI
components within the container
• Layout managers are:
– FlowLayout
– GridLayout
– BorderLayout
– GridBagLayout

7/7/2024 44
Hierarchy of Layout Managers

7/7/2024 45
• Flow Layout
– the component objects appear in order in which they are added
to the container from left to right until no more component will
fit on a row. It then moves to the row and continue going left to
right.
Constructors
– FlowLayout();
– FlowLayout(int align); //align is a constant left, center or right
– FlowLayout(int align, int hSpace, int VSpace);
– setAlignment(int align); //FlowLayout.LEFT, .CENTER,
//.RIGHT

7/7/2024 46
• BorderLayout
– It uses five areas to hold components: NORTH, SOUTH,
EAST, WEST, and CENTER.
– All extra space is placed in the center area.

• Constructor:
– BorderLayout(int n, int m); //n pixel gaps
• Methods
– void add(Component cp, int region);
– Example: cont.add(btn, BorderLayout.CENTER);
7/7/2024 47
• GridLayout
– creates a grid structure on the container
– Every component in a GridLayout has the same width and
height.
• Constructor:
– GridLayout(int row, int col);
– GridLayout(int row, int col, int hSpace, int VSpace);
• Components are added to a GridLayout starting at the top-left
cell of the grid and proceeding left to right until the row is full
– Eg. new GridLayout(4,3);
– Example: Use GridLayout to write a calculator program

7/7/2024 48
7/7/2024 49
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
class Calculator extends JFrame{
JButton btn[]=new JButton[16];
JTextField txtResult;
Calculator(){
String caption[]={"7", "8", "9", "/", "4", "5", "6", "*","1",
"2", "3", "-", "0", "=",".","+"};
for(int i=0;i<16;i++)
btn[i]=new JButton(caption[i]);
txtResult=new JTextField();
Container cp=getContentPane();
cp.setLayout(new BorderLayout());
cp.add(txtResult,BorderLayout.NORTH);
7/7/2024 50
JPanel jp=new JPanel();
cp.add(jp,BorderLayout.CENTER);
jp.setLayout(new GridLayout(4,4));
for(int i=0;i<16;i++)
jp.add(btn[i]);
pack();
}
public static void main(String args[]){
Calculator cl=new Calculator();
cl.setVisible(true);
}
}
}

7/7/2024 51
– The Grid Bag Layout
• The grid bag layout is the mother of all layout managers.
– the rows and columns can have variable sizes.
– You can join adjacent cells to make room for larger
components.
– The components need not fill the entire cell area, and you can
specify their alignment within cells.

7/7/2024 52
• To describe the layout to the grid bag manager, use the
following procedure:
– Create an object of type GridBagLayout.
• You don’t tell it how many rows and columns the underlying grid
has. Instead, the layout manager will try to guess it from the
information you give it later.
– Set this GridBagLayout object to be the layout manager for the
component.
– For each component, create an object of type
GridBagConstraints.
• Set field values of the GridBagConstraint object to specify how
s

the components are laid out within the grid bag.


– Finally, add each component with its constraints by using the
call
• gridObject.setConstraints(component,constraints);
7/7/2024• container.add(component); 53
• Example
GridBagLayout layout = new GridBagLayout();
panel.setLayout(layout);
GridBagConstraints constraints = new GridBagConstraints();
constraints.weightx = 100;
constraints.weighty = 100;
constraints.gridx = 0;
constraints.gridy = 2;
constraints.gridwidth = 2;
constraints.gridheight = 1;
layout.setConstraints (component, constraints);
panel.add(component);
• The gridx, gridy, gridwidth, and gridheight constraints
define where the component is located in the grid.

54
7/7/2024
• gridx - The column in which the component will be placed.
• gridy - The row in which the component will be placed
• gridwidth - The number of columns the component occupies
• gridheight - The number of rows the component occupies
• weightx - The portion of extra space to allocate horizontally.
The components can become wider when extra space is
available
• weighty - The portion of extra space to allocate vertically.
The components can become taller when extra space is
available.
• If you set the weight to 0, then the area never grows or
shrinks beyond its initial size in that direction.

7/7/2024 55
• The Null Layout Manager
– If you set the layout manager in a container to null,
– you can explicitly set the sizes and positions of the components.
class NullLayout extends JFrame{
JButton btn;
JTextField txt;
JComboBox jcb;
NullLayout(){
btn = new JButton(“Ok”);
txt = new JTextField();
jcb = new JComboBox();
Container cp = getContentPane();
Cp.add(btn);
cp.add(txt);
cp.add(jcb);
7/7/2024 56
cp.setLayout(null);
btn.setBounds(50, 50, 60, 30);
txt.setBounds(50, 90, 60, 20);
jcb.setBounds(50, 120, 60, 20);
}
public static void main(String args[]){
NullLayout nl = new NullLayout();
nl.setVisible(true);
}
}

7/7/2024 57
The Java Event Handling
• Event-Driven Programming
• An event: a type of signal to the program that something has
happened
• The event is generated by external user actions such as
– mouse movements, mouse button clicks, and keystrokes, or by
the operating system, such as a timer
• The GUI component on which an event is generated is called
the source object
• Programmer writes code to respond to the various events
that may occur

7/7/2024 58
• The Delegation Event Model
– lies at the heart of Java’s event handling system
– Defines a standard and consistent mechanism to generate and
process events
– The main advantage is
• the application logic that process the event is cleanly separated
from the user interface logic that generates those events.
– Events are supported by the java.awt.event. Package
– There are three objects active in Delegation Event Model
• event sources
• event objects
• event listeners

7/7/2024 59
• Event Sources
– Event sources are objects that generates an event: menus,
buttons, text fields etc.
– Events are generated when the objects internal states are
changed in some way
– A source may generate more than one event.
– Event sources have methods to add event listeners to them
• For example: addActionListener()
– Event source reports on events and notifies all its listeners

7/7/2024 60
• Event Objects
– Objects that represent a user action (e.g. mouse click)
– contain reference to source that generates the event and other
event information.
– When an event happens an event source sends an event object
to its event listeners
– Event can be generated as a consequence of:
• Person Interaction with the elements of GUI
– Pressing a button, Entering a character, Selecting an item in
a list, Click a mouse
• System generated events
– Timer, System Failure
– EventObject is the superclass
• ActionEvent, MouseEvent, etc. are the subclasses that we
use

7/7/2024 61
• Event Listeners
– are objects that respond when an event occurs
– Have two major requirements.
• It must have been registered with one or more sources to receive
notifications about specific types of events.
• It must implements methods to receive and process these
notifications
– If the event listener has been added to an event source, the
listener will be called when an event occurs on that source.
– Any event listener is specific to an event source.
• For example, you'd have one kind of event listener to respond to
the click of a button on your mouse, and another to respond to
the press of a key on your keyboard.
– Listeners are interfaces, not classes
• Class MyButtonListener implements ActionListener {…}

7/7/2024 62
EventObject
User
action
Generate Notify listener
an event

Trigger an event

Source Object Listener Object


Register a listener object Event Handler

7/7/2024 63
• A source must register listeners
– Each of the event has its own registration method:
– Syntax:
<Source> . add<Type>Listener (<Type>Listener el);
• Type is the name of event
• el reference to the event listener
– Example:
• addKeyListener()
• addMouseMotionListener()
• A source also provides a method to ‘unregister’ the listeners.
– Syntax:
public void remove<type>Listener(<Type>Listener tl);

7/7/2024 64
• Example:
– If the listener class is different class, we have to do
ListenerClass lc = new ListenerClass();
JButton btnTest = new JButton(“Test”);
btnTest.addActionListener(lc);
– if the Listener class is the class that contains the source object,
then the reference to the Listener object will be ‘this’
btnTest.addActionListener(this);
• The Listener must implement the appropriate Listener
interface and define methods to receive and process
notifications

7/7/2024 65
• Example
– to Listen and process the ActionEvent generated by the source
button, the Listener class must implement ActionListener
interface
– The method to be implemented is actionPerformed.
class ListenerClass implements ActionListener{
public void ActionPerformed (ActionEvent ae){
ae.getSource(); //returns source object reference
ae.getActionCommand(); //returns caption of the
//source(String)
}
}

7/7/2024 66
• ActionEvent
– In a Button click, TextField focus on the TextField and pressing
Enter
– Source that create ActionEvent
JButton, JTextField, JMenuItem
– Listener interface that the Listener class must implement is
ActionListener
– Method that the Listener should implement is
public void actionPerformed(ActionEvent ae);
– Methods
• String getActionCommand(); - returns String(text) which is the
caption on the source
• Object getSource(); - returns object reference of the source

7/7/2024 67
• DocumentEvent
– occur when the content of a document changes in any way.
– Source that create ActionEvent
• JTextField, JTextArea
– Listener interface that the Listener class must implement is
DocumentListener
– Methods that the Listener should implement are:
• void changedUpdate(DocumentEvent de) : Called when the
style of some of the text in the listened-to document changes.
• void insertUpdate(DocumentEvent de): Called when text is
inserted into the listened-to document.
• void removeUpdate(DocumentEvent de): Called when text is
removed from the listened-to document.

7/7/2024 68
– To get the document that generated the event, you can use
DocumentEvent’s getDocument method.
– object.getDocument().addDocumentListener(this);
– Note that DocumentEvent does not inherit from EventObject
like the other event classes. Thus it does not inherit the
getSource() method.
– Must import javax.swing.event package

7/7/2024 69
• ItemEvent
– Source that create ItemEvent
• JCheckBox, JRadioButton, JComboBox.
– JCheckBox and JRadioButton have two state SELECTED and
DESELECTED
getStateChange() = = e.SELECTED
– Listener interface that the Listener class must implement is
ItemListener
– Method that the Listener class should implement is
public void itemStateChange(ItemEvent ie);
– Methods
• (event object).getSource(); //returns the source object
• (event object).getStateChange() = = ItemEvent.SELECTED or
ItemEvent.DESELECTED

7/7/2024 70
• MouseEvent: There are two types of Listener interfaces
– MouseListener: There are five methods to be implemented
public void mouseClicked(MouseEvent me);
public void mouseEntered(MouseEvent me);
public void mouseExited(MouseEvent me);
public void mouseReleased(MouseEvent me);
public void mousePressed(MouseEvent me);
– MouseMotionListener:
public void mouseMoved(MouseEvent me);
public void mouseDragged(MouseEvent me);

7/7/2024 71
• WindowEvent
– WindowListener : There are 7 methods to be implemented
windowClosing(WindowEvent)
windowOpened(WindowEvent)
windowIconified(WindowEvent)
windowDeiconified(WindowEvent)
windowClosed(WindowEvent)
windowActivated(WindowEvent)
windowDeactivated(WindowEvent)

7/7/2024 72
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
class BackColor extends JFrame implements ActionListener{
JButton btnCyan;
JButton btnBlack;
JButton btnCancel;
BackColor(String str){
btnCyan = new JButton(“Cyan”);
btnBlack = new JButton(“Black”);
btnCancel = new JButton(“Exit”);
Container cp = getContentPane();
setSize(200, 300);
cp.setLayout(new FlowLayout());
cp.add(btnCyan);
7/7/2024 cp.add(btnBlack); 73
cp.add(btnCancel);
btnCancel.addActionListener(this);
btnBlack.addActionListener(this);
btnCyan.addActionListener(this);
}
public void actionPerformed(ActionEvent ae){
if(ae.getSource() == btnCyan)
getContentPane().setBackground(Color.cyan);
else if(ae.getSource() == btnBlack)
getContentPane().setBackground(Color.black);
else{
dispose();
System.exit(0);
}
}
7/7/2024 74
public static void main(String args[]){
BackColor b = new BackColor(“My Frame”);
b.setVisible(true);
}
}

7/7/2024 75
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
class Calculator extends JFrame{
JButton btn[]=new JButton[16];
JTextField txtResult;
Calculator(){
String caption[]={"7", "8", "9", "/", "4", "5", "6", "*","1",
"2", "3", "-", "0", "=",".","+"};
for(int i=0;i<16;i++)
btn[i]=new JButton(caption[i]);
txtResult=new JTextField();
MyListener ml=new MyListener();
for(int i=0;i<16;i++)
btn[i].addActionListener(ml);
7/7/2024 76
Container cp=getContentPane();
cp.setLayout(new BorderLayout());
cp.add(txtResult,BorderLayout.NORTH);
JPanel jp=new JPanel();
cp.add(jp,BorderLayout.CENTER);
jp.setLayout(new GridLayout(4,4));
for(int i=0;i<16;i++)
jp.add(btn[i]);
pack();
}
public static void main(String args[]){
Calculator cl=new Calculator();
cl.setVisible(true);
}
}
7/7/2024 77
class MyListener implements ActionListener{
public void actionPerformed(ActionEvent ae){
txtResult.setText(ae.getActionCommand());
}
}
}

7/7/2024 78
• Ways to define a Listener class
– By making the class that creates source components a
listener class
class MyClass extends JFrame implements ActionListener{
MyClass(){
.
.
.
<source>.addActionListener(this);
...
}
public void actionPerformed(ActionEvent ae){}
}

7/7/2024 79
– Defining a separate Listener class
class MyClass extends Jframe {
MyClass(){
.
.
.
MyHandler mh = new MyHandler();
<source>.addActionListener(mh);
...
}
}
class MyHandler implements ActionListener, ItemListener{
...
public void actionPerformed(ActionEvent ae){. . .}
public void itemStateChanged(ItemEvent ie){. . .}
7/7/2024 } 80
– Define Inner Class
class MyClass extends Jframe {
MyClass(){
.
.
.
MyHandler mh = new MyHandler();
<source>.addActionListener(mh);
...
}
private class MyHandler implements ActionListener{
public void actionPerformed(ActionEvent ae){. . .}
}
}
• An Inner class is allowed to directly access its outer class’s
7/7/2024 variables and methods. 81
– Define Anonymous Inner classes
class MyClass extends JFrame{
...
MyClass() {
...
<source>.addActionListener(new ActionListener(){
public void actioPerformed(ActionEvent ae){
...
}
} );
<source>.addWindowListener(new WindowAdapter(){
public void WindowClosing(WindowEvent ae){
dispose();
System.exit(0);
}
7/7/2024 }); 82
}}
Menu
• Java provides several classes:
– JMenuBar, JMenu, JMenuItem, JCheckBoxMenuItem, and
JRadioButtonMenuItem —to implement menus in a frame
• The JMenuBar Class
– holds menus
– the menu bar can only be added to a frame
– For example:
JFrame f = new JFrame();
f.setSize(300, 200);
f.setVisible(true);
JMenuBar mb = new JMenuBar(); f.setJMenuBar(mb);

7/7/2024 83
• The Menu Class
– You attach menus onto a JMenuBar
– For example:
JMenu fileMenu = new JMenu("File");
JMenu helpMenu = new JMenu("Help");
mb.add(fileMenu);
mb.add(helpMenu);
• The JMenuItem Class
– You add menu items on a menu
fileMenu.add(new JMenuItem("new"));
fileMenu.add(new JMenuItem("open"));
fileMenu.add(new JMenuItem("-"));
fileMenu.add(new JMenuItem("print"));
fileMenu.add(new JMenuItem("exit"));
fileMenu.addSeparator();
7/7/2024 84
• Submenus
– You can add submenus into menu items
– For example:
JMenu hardwareHelpSubMenu = new JMenu("Hardware");
helpMenu.add(softwareHelpSubMenu);
helpMenu.add(hardwareHelpSubMenu);
softwareHelpSubMenu.add(new JMenuItem("Unix"));
softwareHelpSubMenu.add(new JMenuItem("NT"));
softwareHelpSubMenu.add(new JMenuItem("Win95"));

7/7/2024 85

You might also like