Java Unit 5
Java Unit 5
Event Handling
1) Two Event Handling Mechanisms
2) The Delegation Event Model
a. Events
b. Event Sources
c. Event Listeners
3) Event Classes
4) Sources of Events
5) Event Listener Interfaces
6) Adapter Classes
Swings
1) The Origin of Swing
2) Swing is built on the AWT
3) Two Key Features of Swing
4) Swing Components and Containers
5) A Simple Swing Application
6) Event Handling
7) Create a Swing Applet
8) Exploring Swing
Two Event Handling Mechanisms
MenuItem
Selected
Combo box item selected ActionEvent Action Listener void actionPerformed(ActionEvent ae) void
itemStateChanged(ItemEvent ie)
ItemEvent ItemListener
List Item Selected ListSelectionE vent ListSelectionListene r void valueChanged(ListSelectionEvent le)
RadioButton Selected ActionEvent Action Listener void actionPerformed(ActionEvent ae) void
itemStateChanged(ItemEvent ie)
ItemEvent ItemListener
Check Box Selected ActionEvent Action Listener void actionPerformed(ActionEvent ae) void
itemStateChanged(ItemEvent ie)
ItemEvent ItemListener
Scroll Bar Repositioned AdjustmentEve nt AdustmentListener void
adjustmentValueeChanged(AdjustmetEvent ae)
Window Changed WindowEvent WindowListener void windowAcitivated(WindowEvent we) void
windowClosed(WindowEvent we) void
windowClosing(WindowEvent we) void
windowdeactivated(WindowEvent we) void
windowDeiconified(WindowEvent we) void
windowIconified(WindowEvent we) void
windowOpened(WindowEvent we)
Focus Changed FocusEvent FocusListener void focusLost(FocusEvent fe) void
focusGain(FocusEvent fe)
Key Pressed KeyEvent KeyListener void keyPressed(KeyEvent ke) void
keyReleased(KeyEven tke) void
keyTyped(KeyEvent ke)
Mouse clicked MouseEvent MouseListener void mouseClicked(MouseEvent me) void
mouseEntered(MouseEvent me) void
mouseExited(MouseEvent me)
•Adapter
An Adapter
Classesclass provides an empty implementation of all
methods in an event listener interface.
• Adapter classes are useful when you want to receive and
process only some of the events that are handled by a
particular event listener interface.
• Commonly used Listener interfaces implemented by Adapter
Classes are
Adapter Class Listener Interface
ComponentAdapter ComponentListener
CaontainerAdapter ContainerListener
FocusAdapter FocusListener
KeyAdapter KeyListener
MouseAdapter MousrListener
MouseMotionAdapter MouseMotionListener
WindowAdapter WindowListener
SWING
8) Exploring Swing
1) The origin of swing
Swing is a set of classes that provide more powerful and flexible GUI
Components than AWT(Abstract Window Toolkit).
Swing is a package which contains classes related to
graphical components like text box, check box, radio button
etc…
awt (abstract window toolkit) is also such package.
So, awt and swing both are packages which contain classes
for creating Graphical User Interface .
The appearance of graphical components , that are created
using awt package will not look consistent because the look
and feel of the components depends on the os on which the
application is executed.
To overcome this limitation, java soft people introduced
swing package , through which the components look and feel
does not vary from os to os.
2) SWING IS BUILT ON THE AWT
1) Components
In general, Swing components are derived from JComponent
class.
JComponent provides the functionality that is common to all
components.
All of Swing’s components are represented by classes defined
within the package javax.swing. Notice that all component
classes begin with the letter J.
4) Components and containers
2) Containers
Swing defines two types of Containers.
2.1) Top-level containers (or) Heavy Weight Containers
2.2) Non Top-level Containers (or) Light Weight
Containers
4) Components and containers
import java.awt.*;
import javax.swing.*;
class Demo2 extends JFrame
{
JLabel i1,i2;
JTextField t1,t2;
Container con;
ButtonGroup rbg;
Demo2()
{
setSize(400,400);
con=getContentPane();
con.setLayout(new FlowLayout(FlowLayout.LEFT));
i1=new JLabel("Name");
t1=new JTextField(10);
i2=new JLabel("DOB");
t2=new JTextField(10);
rbg=new ButtonGroup();
JRadioButton rb1=new JRadioButton("male");
JRadioButton rb2=new JRadioButton("female");
con.add(i1);
con.add(t1);
con.add(i2);
con.add(t2);
rbg.add(rb1);
rbg.add(rb2);
con.add(rb1);
con.add(rb2);
JButton b1=new JButton("Save");
con.add(b1);}}
5) A Simple Swing Application
class Demo3
{
public static void main(String args[])
{
Demo2 ob=new Demo2();
ob.setTitle("trail box");
ob.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
ob.setVisible(true);
}
}
6) EVENT HANDLING
import javax.swing.*;
import java.applet.*;
/*
<applet code=Demo1 width=200 height=200>
</applet> */
public class Demo1 extends JApplet implements ActionListener
{
JButton b1,b2;
public void init()
{
b1 = new JButton("Alpha");
b2 = new JButton("Beta");
b1.addActionListener(this);
b2.addActionListener(this);
add(b1);
add(b2);
}
public void actionPerformed(ActionEvent ae)
{
if (ae.getSource() == b1)
showStatus("Alpha is pressed");
else
showStatus("Beta is pressed"); }
}
}
6) EVENT HANDLING
7) CREATE A SWING APPLET
import java.awt.*;
import javax.swing.*;
import java.applet.*;
/*
<applet code=AppletDemo width=300 height=300>
</applet> */
public class AppletDemo extends JApplet
{
public void paint(Graphics g)
{
g.drawString("Hello , This is a Simple Applet Program", 20,20);
}
8) Exploring Swing
JTextField
OUTPUT:
Exploring Swing
c) The swing Buttons
Jbutton
• The JButton is a concrete
subclass of AbstractButton
which is a subclass of
JComponent. The
counterpart of JButton in
AWT is Button. Perphaps
the most widely used
control is the push button.
• A Push button is a
component that contains a
label and that generates
an event when it is
pressed.
• JButton defines four
constructors
JButton() \\ constructs a button with no label.
JButton(String Str) \\ constructs a button with a specified label.
JButton(Icon i) \\ constructs a button with the icon I as button
JButton(String str, icon i) \\ constructs a button with the icon I
as button and the string as Label
• JButton has several methods. Some of them are
void setText(String str) \\ sets the buttons label to the
specified string
Exploring Swing
import java.awt.*;
import javax.swing.*;
class Btn extends JFrame
{
JButton b1,b2,b3,b4,b5;
Btn()
{
setSize(400,350);
Container con=getContentPane();
con.setLayout(new FlowLayout(FlowLayout.LEFT));
Icon Img1=new ImageIcon(“new.jpg”);
Icon Img2=new ImageIcon(“save.jpg”);
Icon img3=new ImageIcon(“open.jpg”);
Icon img4=new ImageIcon(“back.jpg”);
Icon Img5=new ImageIcon(“forward.jpg”);
b1=new JButton(“New”,Img1);
b2=new JButton(“Save”,Img2);
b3=new JButton(“open”,Img3);
b4=new JButton(“Back”,Img4);
b5=new JButton(“Forward”,Img5);
b1.setToolTipText(“New”);
b2.setForeground(Color.red);
b3.setMnemonic(‘c’); // Shortcut key for save Button(ALT+C)
con.add(b1);
con.add(b2);
con.add(b3);
con.add(b4);
con.add(b5);
}
}
Exploring Swing
Class JButtonDemo
{
public static void main(String args[])
{
Btn ob=new Btn();
ob.setTitle(“JButton in JFrame”);
ob.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
ob.setVisible(true);
}
}
OUTPUT:
Exploring Swing
JRadioButton
Radio buttons are like check boxes.
In Radio button, the selection is displayed in a round graphics.
Radio buttons are generally used to represent a collection of mutually
exclusive options i.e, out of several options,only one will be selected
state and all the remaining are in deselected state.
The radio buttons are created using JRadioButton class, which is
subclass of JToggleButton.
The JRadioButton must be placed in a Button Group.
The Button group is created using the ButtonGroup class which has no
argument constructor.
After creating JRadioButton, the radio buttons are to be placed to the
ButtonGroup using add() method.
If the JRadio buttons are not grouped using Buttongroup, then each radio
button will behave exactly like JCheckBox.
JRadioButton generates ActionEvent, ItemEvent and ChangeEvent
Exploring Swing
JCheckBox
The JCheckBox class provides the functionality of a check box. Its
immediate superclass is JToggleButton, which provides support for two-
state buttons.
JCheckBox defines the following constructors
JCheckBox() //Creates an initially unselected check box button with
no text, no icon.
JCheckBox(Icon icon)//Creates an initially unselected check box
with an icon.
JCheckBox(String text)//Creates an initially unselected check box
with text.
JCheckBox(Icon icon, boolean selected)//Creates a check box
with an icon and specifies whether or not it is initially selected.
Exploring Swing
import java.awt.*; import javax.swing.*;
class Check extends JFrame
{
JCheckBox r,s,m;
JLabel l1,l2;
Check()
{ setSize(600,300);
Container c = getContentPane();
c.setLayout(new FlowLayout());
l1 = new JLabel("Hobbies");
r = new JCheckBox("Reading");
s = new JCheckBox("Singing");
m = new JCheckBox("Listening Music");
c.add(l1);
c.add(r);
c.add(s);
c.add(m);
}
}
class JCheckBoxDemo
{
public static void main(String args[])
{
Check ob = new Check(); ob.setTitle("JCheckBox in Jframe");
ob.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
ob.setVisible(true);
}
}
Exploring Swing
OUTPUT
Exploring Swing
JComoBox
• The user can select a single item only. A combo box is a visual Swing
graphical component that gives popup list when clicked.
• It is the combination of JList and JTextField.
• In Combo box, only one item is visible at a time. A Popup menu
displays the choices a user can select from.
• In JList, the items cannot be edited, but in combo box, the items can
be edited by setting the JComboBox editable.
• JCombobox defines the following constructors
JComboBox() \\ Creates empty Combo Box
JComboBox(object[] arr) \\ Creates a combo box taking
the items from the specified
Object Array
String
1 =(“India”,”America”,”germany”);
st
Eg:
JComboBoxbox=newJComboBox(1st);
JComboBox(Vector v)\\ Creates a combo box taking the
items from the specified vector
Exploring Swing
JComboBox has so many methods. Some of them are
Void addItem(Object obj) \\ adds the specified object to the list
Eg:box.addItem(“Japan”);
Object getSelectItem() \\Returns the currently selected item
Eg: Object obj=box.getSelectedItem();
Int getSelectIndex() \\ Returns the index of item in the list
Eg: int I=box.getSelectedIndex();
Int getItemCount() \\ Returns the number of items in the list
Eg: int I=box.getItemCount();
Boolean isEditable() \\ Returns a Boolean specifying whether the
combobox items are
Editable or not
Eg: Boolean x=box.isEditable();
Void removeItem(Object ob) \\ Removes the specified item from
the list
Eg: box.removeItem(“germany”);
Exploring Swing
import java.awt.*;
import javax.swing.*;
class cmbbox extends JFrame
{
JComboBox box1,box2;
String str[]={"Andhra Pradesh","Tamil Nadu","Karnataka"};
cmbbox()
{
Container c=getContentPane();
c.setLayout(new FlowLayout());
box1=new JComboBox();
box2=new JComboBox(str);
JLabel I1=new JLabel("Countries");
JLabel I2=new JLabel("States");
box1.addItem("India");
box1.addItem("germany");
box1.addItem("Japan");
c.add(I1);
c.add(box1);
c.add(I2);
c.add(box2);
}
}
class JComboDemo
{
public static void main(String args[])
{
cmbbox ob=new cmbbox(); ob.setTitle("JComboBox in JFrame"); ob.setSize(400,300);
ob.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); ob.setVisible(true);
}
}
Exploring Swing