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

Unit 3 - GUI Components II - Swing - Components

Uploaded by

Shravani Salunke
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)
27 views

Unit 3 - GUI Components II - Swing - Components

Uploaded by

Shravani Salunke
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/ 91

Advanced Java Programming

Unit III

GUI Components – II
Swing Components
Graphical User Interfaces
• Designing graphical application is an excellent example of the use of inheritance,
abstract classes, and interfaces.

• Developing graphical user interfaces isn't similar to anything else in software


engineering. There are no simple, bulletproof guidelines that lead to any sort of
enlightenment. In practice, we are not able to create the perfect GUI.

• Every program that presents a Swing GUI contains at least one top-level Swing
CONTAINER. For most programs, the top-level Swing containers are instances
of JFrame, JDialog, or (for applets) JApplet. Each JFrame object implements a single main
window, and each JDialog implements a secondary window, usually a temporary
window to receive an additional information from the user (JOptionPane is an
example of JDialog).
Continued…
• Each JApplet object implements an applet's display area within a browser
window. A top-level Swing container provides the support for painting and event
handling.

• A container class is used to hold other COMPONENTS. The role of containers is


to determine how the components are organized and displayed.

• The component classes are JButton, JLabel, JTextField, JTextArea,


JRadioButton, JComboBox, JList, JMenuBar and few more.

• In addition to this there are the HELPER classes, like Font, Color, Graphics and
more.
JButton
• The JButton class is used to create a labelled button that has platform
independent implementation.
• A button is a component the user clicks to trigger a specific action.
• A Java application can use several types of buttons, including command buttons,
check boxes, toggle buttons and radio buttons.
• Following Figure shows the inheritance hierarchy of the Swing buttons we cover
in this chapter. As you can see, all the button types are subclasses of
AbstractButton (package javax.swing), which declares the common features of
Swing buttons. In this section, we concentrate on buttons that are typically used
to initiate a command.

• JButton class declaration for javax.swing.JButton class.


public class JButton extends AbstractButton implements Accessible
Swing button hierarchy
Commonly used Constructors: JButton

Constructor Description

JButton() It creates a button with no text and icon.


JButton(String s) It creates a button with the specified text.
JButton(Icon i) It creates a button with the specified icon object.
Commonly used Methods of AbstractButton class
Methods Description

void setText(String s) It is used to set specified text on button


String getText() It is used to return the text of the
button.
void setEnabled(boolean b) It is used to enable or disable the
button.
void setIcon(Icon b) It is used to set the specified Icon on the
button.
Icon getIcon() It is used to get the Icon of the button.
void setMnemonic(int a) It is used to set the mnemonic on the
button.
void addActionListener(ActionListener a) It is used to add the action listener to
this object.
Java JButton Example
import javax.swing.*;
public class ButtonExample //Program
{ public static void main(String[] args)
{ JFrame f=new JFrame("Button Example");
JButton b=new JButton("Click Here");
b.setBounds(50,100,95,30);
f.add(b);
f.setSize(400,400);
f.setLayout(null);
f.setVisible(true);
}
}
Java JButton Example with ActionListener
import java.awt.event.*;
import javax.swing.*;
public class ButtonExampleActionListener //Program
{ public static void main(String[] args)
{ JFrame f=new JFrame("Button Example");
final JTextField tf=new JTextField(); tf.setBounds(50,50, 200,20);
JButton b=new JButton("Click Here"); b.setBounds(50,100,95,30);
b.addActionListener (new ActionListener() {
public void actionPerformed(ActionEvent e)
{ tf.setText("Welcome to SMS AJP classroom.");
}
});
f.add(b);f.add(tf); f.setSize(400,400); f.setLayout(null); f.setVisible(true);
}
}
Example of displaying image on the button
import javax.swing.*;
public class ImageOnButtonExample //Program
{ ImageOnButtonExample()
{ JFrame f=new JFrame("Image on Button Example");
JButton b=new JButton(new ImageIcon("Register.png"));
b.setBounds(100,100,350,100); f.add(b); f.setSize(600,400);
f.setLayout(null); f.setVisible(true);
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
public static void main(String[] args)
{ new ImageOnButtonExample();
}
}
Java JLabel
• The object of JLabel class is a component for placing text in a
container. It is used to display a single line of read only text. The text
can be changed by an application but a user cannot edit it directly. It
inherits JComponent class.
• JLabel class declaration (javax.swing.JLabel class):
public class JLabel extends JComponent implements SwingConstants, Accessible
Commonly used Constructors
Constructor Description
JLabel() Creates a JLabel instance with no image
and with an empty string for the title.
JLabel(String s) Creates a JLabel instance with the
specified text.
JLabel(Icon i) Creates a JLabel instance with the
specified image.
JLabel(String s, Icon i, Creates a JLabel instance with the
int horizontalAlignment) specified text, image, and horizontal
alignment.
Commonly used Methods
Methods Description
String getText() It returns the text string that a
label displays.
void setText(String text) It defines the single line of text
this component will display.
void setHorizontalAlignment(int It sets the alignment of the
alignment) label's contents along the X axis.
Icon getIcon() It returns the graphic image that
the label displays.
int getHorizontalAlignment() It returns the alignment of the
label's contents along the X axis.
Java JLabel Example
import javax.swing.*;
class LabelExample //Program
{ public static void main(String args[])
{ JFrame f= new JFrame("Swing Label Example");
JLabel l1,l2;
l1=new JLabel("First Label.");
l1.setBounds(50,50, 100,30);
l2=new JLabel("Second Label.");
l2.setBounds(50,100, 100,30);
f.add(l1); f.add(l2);
f.setSize(300,300);
f.setLayout(null);
f.setVisible(true);
}
}
Java JLabel Example with ActionListener
import javax.swing.*;
import java.awt.*; //Program
import java.awt.event.*;
public class LabelExampleActionListener extends Frame implements ActionListener
{ JTextField tf; JLabel l; JButton b;
LabelExampleActionListener()
{ tf=new JTextField(); tf.setBounds(50,50, 150,20);
l=new JLabel(); l.setBounds(50,100, 250,20);
b=new JButton("Find IP"); b.setBounds(50,150,95,30);
b.addActionListener(this); add(b);add(tf);add(l);
setSize(400,400); setLayout(null); setVisible(true);
}
public void actionPerformed(ActionEvent e)
{ try
{ String host=tf.getText();
String ip=java.net.InetAddress.getByName(host).getHostAddress();
l.setText("IP of "+ host +" is: "+ ip);
}
catch(Exception ex)
{ System.out.println(ex); }
}
public static void main(String[] args)
{ new LabelExampleActionListener();
}
}
Java JFrame
• A frame, implemented as an instance of the JFrame class, is a free standing
window that has decorations such as a border, a title, and buttons for closing and
iconifying the window. Applications with a GUI typically use at least one frame.
• The javax.swing.JFrame class is a type of container which inherits the
java.awt.Frame class. JFrame works like the main window where components like
labels, buttons, textfields are added to create a GUI.
• Unlike Frame, JFrame has the option to hide or close the window with the help of
setDefaultCloseOperation(int) method.
• Nested Class

Modifier and Type Class Description

protected class JFrame.AccessibleJFrame This class implements accessibility


support for the JFrame class.
Fields
Modifier and Type Field Description

protected AccessibleContext accessibleContext The accessible context property.

static int EXIT_ON_CLOSE The exit application default


window close operation.

protected JRootPane rootPane The JRootPane instance that


manages the contentPane and
optional menuBar for this
frame, as well as the glassPane.

protected boolean rootPaneCheckingEnabled If true then calls to add and


setLayout will be forwarded to
the contentPane.
Constructors
Constructor Description

JFrame() It constructs a new frame that is initially invisible.

JFrame(GraphicsConfiguration gc) It creates a Frame in the specified


GraphicsConfiguration of a screen device and a blank
title.

JFrame(String title) It creates a new, initially invisible Frame with the


specified title.

JFrame(String title, It creates a JFrame with the specified title and the
GraphicsConfiguration gc) specified GraphicsConfiguration of a screen device.
Useful Methods
Modifier and Type Method Description

protected void addImpl(Component comp, Adds the specified child


Object constraints, int index) Component.
protected JRootPane createRootPane() Called by the constructor methods
to create the default rootPane.
protected void frameInit() Called by the constructors to init
the JFrame properly.
void setContentPane(Containe It sets the contentPane property
contentPane)
static void setDefaultLookAndFeelDecorated Provides a hint as to
(boolean whether or not newly
defaultLookAndFeelDecorated) created JFrames should
have their Window
decorations (such as
borders, widgets to close
the window, title...)
provided by the current look
and feel.
void setIconImage(Image image) It sets the image to be
displayed as the icon for this
window.
void setJMenuBar(JMenuBar menubar) It sets the menubar for this
frame.
void setLayeredPane(JLayeredPane It sets the layeredPane
layeredPane) property.
JRootPane getRootPane() It returns the rootPane object
for this frame.
TransferHandler getTransferHandler() It gets the transferHandler
property.
JFrame Example
import java.awt.FlowLayout;
import javax.swing.JButton;
import javax.swing.JFrame; //Program
import javax.swing.JLabel;
import javax.swing.JPanel;
public class JFrameExample
{ public static void main(String s[])
{ JFrame frame = new JFrame("JFrame Example");
JPanel panel = new JPanel(); panel.setLayout(new FlowLayout());
JLabel label = new JLabel("JFrame By Example"); JButton button = new JButton(); button.setText("Button");
panel.add(label); panel.add(button); frame.add(panel); frame.setSize(300, 300);
frame.setLocationRelativeTo(null); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
}
}
JCheckbox
• The JCheckBox class is used to create a checkbox. It is used to turn an
option on (true) or off (false). Clicking on a CheckBox changes its state
from "on" to "off" or from "off" to "on ".It inherits JToggleButton
class.

• JCheckBox class declaration


• Let's see the declaration for javax.swing.JCheckBox class.

public class JCheckBox extends JToggleButton implements Accessible


Commonly used Constructors
Constructor Description

JJCheckBox() Creates an initially unselected check box button


with no text, no icon.
JChechBox(String s) Creates an initially unselected check box with
text.
JCheckBox(String text, boolean Creates a check box with text and specifies
selected) whether or not it is initially selected.
JCheckBox(Action a) Creates a check box where properties are taken
from the Action supplied.
Commonly used Methods
Methods Description

AccessibleContext It is used to get the AccessibleContext


getAccessibleContext() associated with this JCheckBox.
protected String paramString() It returns a string representation of this
JCheckBox.
Java JCheckBox Example
import javax.swing.*;
public class CheckBoxExample //Program
{ CheckBoxExample()
{ JFrame f= new JFrame("CheckBox Example");
JCheckBox checkBox1 = new JCheckBox("C++");
checkBox1.setBounds(100,100, 50,50);
JCheckBox checkBox2 = new JCheckBox("Java", true);
checkBox2.setBounds(100,150, 60,50);
f.add(checkBox1); f.add(checkBox2); f.setSize(400,400); f.setLayout(null);
f.setVisible(true);
}
public static void main(String args[])
{ new CheckBoxExample();
}
}
Java JCheckBox Example with ItemListener
import javax.swing.*;
import java.awt.event.*;
public class CheckBoxExampleItemListener //Program
{ CheckBoxExampleItemListener()
{ JFrame f= new JFrame("CheckBox Example with ItemListener");
final JLabel label = new JLabel(); label.setHorizontalAlignment(JLabel.CENTER);
label.setSize(400,100); JCheckBox checkbox1 = new JCheckBox("C++");
checkbox1.setBounds(150,100, 50,50); JCheckBox checkbox2 = new JCheckBox("Java");
checkbox2.setBounds(150,150, 50,50); f.add(checkbox1); f.add(checkbox2); f.add(label);
checkbox1.addItemListener(new ItemListener() {
public void itemStateChanged(ItemEvent e)
{ label.setText("C++ Checkbox: "
+ (e.getStateChange()==1?"checked":"unchecked"));
}
});
checkbox2.addItemListener(new ItemListener()
{ public void itemStateChanged(ItemEvent e)
{ label.setText("Java Checkbox: "
+ (e.getStateChange()==1?"checked":"unchecked"));
}
});
f.setSize(400,400);
f.setLayout(null);
f.setVisible(true);
}
public static void main(String args[])
{ new CheckBoxExampleItemListener();
}
}
Java JCheckBox Example: Food Order
import javax.swing.*;
import java.awt.event.*; //Program
public class CheckBoxExampleFood extends JFrame implements ActionListener
{ JLabel l; JCheckBox cb1,cb2,cb3; JButton b;
CheckBoxExampleFood()
{ l=new JLabel("Food Ordering System"); l.setBounds(50,50,300,20);
cb1=new JCheckBox("Pizza @ 100"); cb1.setBounds(100,100,150,20);
cb2=new JCheckBox("Burger @ 30"); cb2.setBounds(100,150,150,20);
cb3=new JCheckBox("Tea @ 10"); cb3.setBounds(100,200,150,20);
b=new JButton("Order"); b.setBounds(100,250,80,30); b.addActionListener(this);
add(l); add(cb1); add(cb2); add(cb3);add(b);
setSize(400,400); setLayout(null); setVisible(true);
setDefaultCloseOperation(EXIT_ON_CLOSE);
}
public void actionPerformed(ActionEvent e)
{ float amount=0; String msg="";
if(cb1.isSelected())
{ amount+=100; msg="Pizza: 100\n";
}
if(cb2.isSelected())
{ amount+=30; msg+="Burger: 30\n";
}
if(cb3.isSelected())
{ amount+=10; msg+="Tea: 10\n";
}
msg+="-----------------\n";
JOptionPane.showMessageDialog(this,msg+"Total: "+amount);
}
public static void main(String[] args)
{ new CheckBoxExampleFood();
}
}
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.
• JRadioButton class declaration
• Let's see the declaration for javax.swing.JRadioButton class.
public class JRadioButton extends JToggleButton implements Accessible
Commonly used Constructors
Constructor Description
JRadioButton() Creates an unselected radio button with
no text.
JRadioButton(String s) Creates an unselected radio button with
specified text.
JRadioButton(String s, Creates a radio button with the
boolean selected) specified text and selected status.
Commonly used Methods
Methods Description

void setText(String s) It is used to set specified text on button.


String getText() It is used to return the text of the button.
void setEnabled(boolean b) It is used to enable or disable the button.
void setIcon(Icon b) It is used to set the specified Icon on the
button.
Icon getIcon() It is used to get the Icon of the button.
void setMnemonic(int a) It is used to set the mnemonic on the
button.
void It is used to add the action listener to this
addActionListener(ActionListener a) object.
Java JRadioButton Example
import javax.swing.*;
public class RadioButtonExample
{ JFrame f;
RadioButtonExample()
{ f=new JFrame();
JRadioButton r1=new JRadioButton("A) Male"); JRadioButton r2=new JRadioButton("B) Female");
r1.setBounds(75,50,100,30); r2.setBounds(75,100,100,30);
ButtonGroup bg=new ButtonGroup(); bg.add(r1); bg.add(r2);
f.add(r1); f.add(r2); f.setSize(300,300); f.setLayout(null); //try adding f.add(bg)……..
f.setVisible(true);
}
public static void main(String[] args)
{ new RadioButtonExample();
}
}
Java JRadioButton Example with ActionListener
import javax.swing.*;
import java.awt.event.*;
class RadioButtonExampleAL extends JFrame implements ActionListener
{ JRadioButton rb1,rb2; JButton b;
RadioButtonExampleAL()
{ rb1=new JRadioButton("Male"); rb1.setBounds(100,50,100,30);
rb2=new JRadioButton("Female"); rb2.setBounds(100,100,100,30);
ButtonGroup bg=new ButtonGroup(); bg.add(rb1);bg.add(rb2);
b=new JButton("click"); b.setBounds(100,150,80,30);
b.addActionListener(this); add(rb1); add(rb2); add(b);
setSize(300,300); setLayout(null);
setVisible(true);
}
public void actionPerformed(ActionEvent e)
{ if(rb1.isSelected())
{ JOptionPane.showMessageDialog(this,"You are Male.");
}
if(rb2.isSelected())
{ JOptionPane.showMessageDialog(this,"You are Female.");
}
}
public static void main(String args[])
{ new RadioButtonExampleAL();
}
}
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.
• JComboBox class declaration
• Let's see the declaration for javax.swing.JComboBox class.
public class JComboBox extends JComponent implements ItemSelectable, ListD
ataListener, ActionListener, Accessible
Commonly used Constructors
Constructor Description

JComboBox() Creates a JComboBox with a default data


model.
JComboBox(Object[] items) Creates a JComboBox that contains the
elements in the specified array.
JComboBox(Vector<?> items) Creates a JComboBox that contains the
elements in the specified Vector.
Commonly used Methods
Methods Description

void addItem(Object anObject) It is used to add an item to the item


list.
void removeItem(Object anObject) It is used to delete an item to the
item list.
void removeAllItems() It is used to remove all the items
from the list.
void setEditable(boolean b) It is used to determine whether the
JComboBox is editable.
void addActionListener(ActionListener a) It is used to add the ActionListener.
void addItemListener(ItemListener i) It is used to add the ItemListener.
Java JComboBox Example
import javax.swing.*;
import java.awt.*;
public class JComboBoxExample
{ JFrame f;
JComboBoxExample()
{ f=new JFrame("JComboBox Example");
String country[]={"India","Aus","U.S.A","England","Newzealand"};
JComboBox cb=new JComboBox(country); cb.setBounds(50, 50,90,20);
f.add(cb); f.setLayout(null); f.setSize(400,500);
f.setVisible(true);
}
public static void main(String[] args)
{ new JComboBoxExample();
}
}
Agenda
• Java JComboBox Example with ActionListener
• Java JList
• Java JList Example with ActionListener
• Multiple Selection List
• Events (…Covered in AWT…)
• Java Event classes and Listener interfaces
• Java Event Handling code (3 programs)
• ItemListener and ActionListener
• Event-listener interface and an event-adapter class
• Java Adapter Classes
• Demo programs
Java JComboBox Example with ActionListener
import javax.swing.*;
import java.awt.event.*;
public class JComboBoxExampleAL
{ JFrame f;
JComboBoxExampleAL()
{ f=new JFrame("JComboBox Action Listener Example");
final JLabel label = new JLabel();
label.setHorizontalAlignment(JLabel.CENTER);
label.setSize(400,100);
JButton b=new JButton("Show"); b.setBounds(200,100,75,20);
String languages[]={"C","C++","C#","Java","PHP"};
final JComboBox cb=new JComboBox(languages);
cb.setBounds(50, 100,90,20); f.add(cb); f.add(label); f.add(b);
f.setLayout(null); f.setSize(450,350); f.setVisible(true);
b.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e)
{ String data = "Programming language Selected: "
+ cb.getItemAt(cb.getSelectedIndex());
label.setText(data);
}
});
}
public static void main(String[] args)
{ new JComboBoxExampleAL();
}
}
Java JList
• The object of JList class represents a list of text items. The list of text items can be
set up so that the user can choose either one item or multiple items. It inherits
JComponent class.
• JList class declaration
• Let's see the declaration for javax.swing.JList class.
• public class JList extends JComponent implements Scrollable, Accessible
• Commonly used Constructors:

Constructor Description

JList() Creates a JList with an empty, read-only, model.


JList(ary[] listData) Creates a JList that displays the elements in the
specified array.
JList(ListModel<ary> dataModel) Creates a JList that displays elements from the
specified, non-null, model.
Commonly used Methods
Methods Description

Void It is used to add a listener to the list, to be


addListSelectionListener(ListSelectionListener notified each time a change to the selection
listener) occurs.
int getSelectedIndex() It is used to return the smallest selected cell
index.
ListModel getModel() It is used to return the data model that holds
a list of items displayed by the JList
component.
void setListData(Object[] listData) It is used to create a read-only ListModel from
an array of objects.
Java JList Example
import javax.swing.*;
public class JListExample
{ JListExample()
{ JFrame f= new JFrame();
DefaultListModel<String> l1 = new DefaultListModel<>();
l1.addElement("Comp"); l1.addElement("Chem");
l1.addElement("Extc"); l1.addElement("Poly");
JList<String> list = new JList<>(l1);
list.setBounds(100,100, 75,75); f.add(list); f.setSize(400,400);
f.setLayout(null); f.setVisible(true);
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
public static void main(String args[])
{ new JListExample();
}
}
Java JList Example with ActionListener
import javax.swing.*;
import java.awt.event.*;
public class JListExampleAL
{ JListExampleAL()
{ JFrame f= new JFrame(); final JLabel label = new JLabel(); label.setSize(500,100);
JButton b=new JButton("Show"); b.setBounds(200,150,80,30);
final DefaultListModel<String> l1 = new DefaultListModel<>(); l1.addElement("C");
l1.addElement("C++"); l1.addElement("Java"); l1.addElement("PHP");
final JList<String> list1 = new JList<>(l1); list1.setBounds(100,100, 75,75);
DefaultListModel<String> l2 = new DefaultListModel<>(); l2.addElement("Turbo C++");
l2.addElement("Struts"); l2.addElement("Spring"); l2.addElement("YII");
final JList<String> list2 = new JList<>(l2); list2.setBounds(100,200, 75,75);
f.add(list1); f.add(list2); f.add(b); f.add(label);
f.setSize(450,450); f.setLayout(null); f.setVisible(true);
b.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e)
{ String data = "";
if (list1.getSelectedIndex() != -1)
{ data = "Programming language Selected: " + list1.getSelectedValue();
label.setText(data);
}
if(list2.getSelectedIndex() != -1)
{ data += ", FrameWork Selected: ";
for(Object frame :list2.getSelectedValuesList()) { data += frame + " "; }
}
label.setText(data);
}
});
}
public static void main(String args[])
{ new JListExampleAL();
}
}
Multiple Selection List
• A multiple-selection list enables the user to select many items from a JList. A
SINGLE_INTERVAL_SELECTION list allows selecting a contiguous range of items. To
do so, click the first item, then press and hold the Shift key while clicking the last
item in the range. A MULTIPLE_INTERVAL_SELECTION list allows continuous range
selection as described for a SINGLE_INTERVAL_SELECTION list. Such a list allows
miscellaneous items to be selected by pressing and holding the Ctrl key
(sometimes called the Control key) while clicking each item to select. To deselect
an item, press and hold the Ctrl key while clicking the item a second time.

• The application may use multiple-selection lists to copy items from one JList to
another. One list is a MULTIPLE_INTERVAL_SELECTION list and the other is a
SINGLE_INTERVAL_SELECTION list. When you execute the application, try using
the selection techniques described previously to select items in both lists.
Events
• Events are objects that encapsulate changes in state that are initiated by
the user. Generally, the user triggers events by pressing and releasing keys
on the keyboards…………
• The AWT API includes the package java.awt.event in which you will find
the classes from this API that encapsulate the events that relate to the GUI
components in your application or applet. All classes in this package that
define events are the subclasses of the class java.awt.event.AWTEvent
which is a subclass of java.util.EventObject. EventObject is the superclass
of all Java platform classes that define events, whether they are GUI events
or not.
• The Swing API separates its event related classes into a package called
javax.swing.event. It is worth noting that most Swing event classes are
direct subclasses of EventObject, not AWTEvent.
Java Event classes and Listener interfaces
• The java.awt.event package provides many event classes and Listener
interfaces for event handling.
Event Classes Listener Interfaces

ActionEvent ActionListener
MouseEvent MouseListener and MouseMotionListener
MouseWheelEvent MouseWheelListener
KeyEvent KeyListener
ItemEvent ItemListener
TextEvent TextListener
AdjustmentEvent AdjustmentListener
WindowEvent WindowListener
ComponentEvent ComponentListener
ContainerEvent ContainerListener
• Following steps are required to perform event handling:
1. Register the component with the Listener:
Registration Methods: For registering the component with the Listener, many classes provide the
registration methods. For example:
• Button
• public void addActionListener(ActionListener a){}
• MenuItem
• public void addActionListener(ActionListener a){}
• TextField
• public void addActionListener(ActionListener a){}
• public void addTextListener(TextListener a){}
• TextArea
• public void addTextListener(TextListener a){}
• Checkbox
• public void addItemListener(ItemListener a){}
• Choice
• public void addItemListener(ItemListener a){}
• List
• public void addActionListener(ActionListener a){}
• public void addItemListener(ItemListener a){}
Java Event Handling Code
• We can put the event handling code into one of the following places:
• Within class
• Other class
• Anonymous class
1) Java event handling by implementing ActionListener
• Program: AEvent.java
2) Java event handling by outer class
• Program AEvent2.java
3) Java event handling by anonymous class
• Program AEvent3.java
ItemListener and ActionListener
• Different GUI components have different events associated with it (
more or less and/or same or different , than/compared with other
GUI components). ItemListener and ActionListener are interfaces, and
when you invoke “add____Listener“ , it require you to pass along
appropriate interface (based on event applicable to GUI component).
• ItemListener is for drop downs or lists , and ActionListener is for
Actions (like clicking , although there is MouseListenter interface for
mouse events like mouse press/release/click/etc).
• An ItemEvent is fired even when the user deselects a check box by
selecting another JCheckBox (when in a ButtonGroup), however
ActionEvent is not generated like that instead ActionEvent only listens
whether an action is performed on the JCheckBox (to which the
ActionListener is registered only) or not. It does not know about
ButtonGroup and all other selection/deselection stuff.
• ItemListeners are notified whenever the state of the button is changed,
whether through a user interacting with the button or programmatically
(via the setSelected method). ActionListeners on the other hand will be
called when a user interacts with the button (but can be simulated
programmatically via the onClick method).

• Note that a user interacting with the button such as clicking or hitting the
space bar will also change the state of the button and raise an item event
as well as an action event. Generally, you will want to define either one or
the other, don't listen for both action events and item events on the
button.
Event-listener interface and an event-adapter class
• What is the relationship between an event-listener interface and an event-
adapter class?
An event-listener interface allows describing the methods which must be
implemented by one of the event handler for a specific event.
An event-adapter allows default implementations of an event-listener interface of a
specific event.
• What is the relationship between an event-listener interface and an event-
adapter class?
If an event listener is implemented directly by a class, all the methods within that
interface need to be implemented making the code unnecessarily large.
This issue can be solved using the adapter class.
To use an adapter, you create a subclass of it and override only the methods of
interest, rather than directly implementing all methods of the listener interface.
Agenda

• Java Adapter classes


Java Adapter Classes
• Java adapter classes provide the default implementation of
listener interfaces. If you inherit the adapter class, you will not be
forced to provide the implementation of all the methods of listener
interfaces. So it saves code.
• The adapter classes are found in java.awt.event, java.awt.dnd
and javax.swing.event packages. The Adapter classes with their
corresponding listener interfaces are given below.
java.awt.event Adapter classes
Adapter class Listener interface

WindowAdapter WindowListener

KeyAdapter KeyListener

MouseAdapter MouseListener

MouseMotionAdapter MouseMotionListener

FocusAdapter FocusListener

ComponentAdapter ComponentListener

ContainerAdapter ContainerListener

HierarchyBoundsAdapter HierarchyBoundsListener
java.awt.dnd Adapter classes

Adapter class Listener interface

DragSourceAdapter DragSourceListener
DragTargetAdapter DragTargetListener

javax.swing.event Adapter classes

Adapter class Listener interface

MouseInputAdapter MouseInputListener
InternalFrameAdapter InternalFrameListener
Java WindowAdapter Example
import java.awt.*;
import java.awt.event.*;
public class AdapterExample
{ Frame f;
AdapterExample()
{ f=new Frame("Window Adapter");
f.addWindowListener(new WindowAdapter(){
public void windowClosing(WindowEvent e) { f.dispose(); }
});
f.setSize(400,400); f.setLayout(null); f.setVisible(true);
}
public static void main(String[] args)
{ new AdapterExample();
}
}
java MouseAdapter Example
import java.awt.*;
import java.awt.event.*;
public class MouseAdapterExample extends MouseAdapter
{ Frame f;
MouseAdapterExample()
{ f=new Frame("Mouse Adapter"); f.addMouseListener(this);
f.setSize(300,300); f.setLayout(null); f.setVisible(true);
}
public void mouseClicked(MouseEvent e)
{ Graphics g=f.getGraphics(); //The getGraphics() method of Component class returns the object of Graphics.
g.setColor(Color.BLUE); g.fillOval(e.getX(), e.getY(),30,30);
}
public static void main(String[] args)
{ new MouseAdapterExample();
}
}
Java MouseMotionAdapter Example
import java.awt.*;
import java.awt.event.*;
public class MouseMotionAdapterExample extends MouseMotionAdapter
{ Frame f;
MouseMotionAdapterExample()
{ f=new Frame("Mouse Motion Adapter"); f.addMouseMotionListener(this);
f.setSize(400,300); f.setLayout(null); f.setVisible(true);
}
public void mouseDragged(MouseEvent e)
{ Graphics g=f.getGraphics(); g.setColor(Color.ORANGE);
g.fillOval(e.getX(),e.getY(),20,20);
}
public static void main(String[] args)
{ new MouseMotionAdapterExample();
}
}
Agenda
• WindowAdapter
• MouseAdapter
• MouseMotionAdapter
• Java KeyAdapter Example
• Key Event Handling
• Java KeyListener interface
• Java KeyListener interface - Example1 (key pressed/released/typed)
• Java KeyListener interface – Example2 (Count words and characters)
• Layout managers
Java KeyAdapter Example
import java.awt.*;
import java.awt.event.*;
public class KeyAdapterExample extends KeyAdapter
{ Label l; TextArea area; Frame f;
KeyAdapterExample()
{ f=new Frame("Key Adapter"); l=new Label(); l.setBounds(20,50,200,20); area=new TextArea();
area.setBounds(20,80,300, 300); area.addKeyListener(this); f.add(l);f.add(area); f.setSize(400,400);
f.setLayout(null); f.setVisible(true);
}
public void keyReleased(KeyEvent e)
{ String text=area.getText(); String words[]=text.split("\\s");
l.setText("Words: "+words.length+" Characters:"+text.length());
}
public static void main(String[] args) //Program
{ new KeyAdapterExample();
}
}
Key Event Handling
• This section presents the KeyListener interface for handling key
events. Key events are generated when keys on the keyboard are
pressed and released. A class that implements KeyListener must
provide declarations for methods keyPressed, keyReleased and
keyTyped, each of which receives a KeyEvent as its argument. Class
KeyEvent is a subclass of InputEvent. Method keyPressed is called in
response to pressing any key. Method keyTyped is called in response
to pressing any key that is not an action key. (The action keys are any
arrow key, Home, End, Page Up, Page Down, any function key, Num
Lock, Print Screen, Scroll Lock, Caps Lock and Pause.) Method
keyReleased is called when the key is released after any keyPressed or
keyTyped event.
Java KeyListener Interface
• The Java KeyListener is notified whenever you change the state of key.
It is notified against KeyEvent. The KeyListener interface is found in
java.awt.event package. It has three methods.
• Methods of KeyListener interface
• The signature of 3 methods found in KeyListener interface are given
below:
• public abstract void keyPressed(KeyEvent e);
• public abstract void keyReleased(KeyEvent e);
• public abstract void keyTyped(KeyEvent e);
Java KeyListener Example
import java.awt.*;
import java.awt.event.*;
public class KeyListenerExample extends Frame implements KeyListener
{ Label l; TextArea area;
KeyListenerExample()
{ l=new Label(); l.setBounds(20,50,100,20); area=new TextArea(); area.setBounds(20,80,300, 300);
area.addKeyListener(this); add(l);add(area); setSize(400,400); setLayout(null); setVisible(true);
}
public void keyPressed(KeyEvent e) { l.setText("Key Pressed"); }
public void keyReleased(KeyEvent e) { l.setText("Key Released"); }
public void keyTyped(KeyEvent e) { l.setText("Key Typed"); }
public static void main(String[] args) { new KeyListenerExample(); } //Program
}
KeyListener Example 2: Count Words & Characters
import java.awt.*;
import java.awt.event.*;
public class KeyListenerExample2 extends Frame implements KeyListener
{ Label l; TextArea area;
KeyListenerExample2()
{ l=new Label(); l.setBounds(20,50,200,20); area=new TextArea(); area.setBounds(20,80,300, 300);
area.addKeyListener(this); add(l);add(area); setSize(400,400); setLayout(null); setVisible(true);
}
public void keyPressed(KeyEvent e) {}
public void keyReleased(KeyEvent e) //Program
{ String text=area.getText(); String words[]=text.split("\\s");
l.setText("Words: "+words.length+" Characters:"+text.length());
}
public void keyTyped(KeyEvent e) {}
public static void main(String[] args)
{ new KeyListenerExample2();
}
}
END

Next…
Layout Managers

You might also like