Contents
• Event Handling
• Delegation Event Model
Unit 4 • Event Classes
• Event Sources
• Event Listeners
• AWT: Frame Class
• AWT Controls
2 September 2021
1 2 September 2021 2
Contents Contents
• Swing – Architecture
• Components of swing
• Layout Managers
➢ JLabel ➢Flow Layout
➢ Jbutton
➢ JCheckBox ➢Grid Layout
➢ JRadioButton
➢ JList ➢Card Layout
➢ JComboBox
➢ JTextField
➢Border Layout
➢ JTextArea ➢Box Layout
➢ JPanel
➢ JFrame ➢Null Layout
2 September 2021 3 2 September 2021 4
Event Handling Event Handling
• Event is an object that describes a state • Events may also occur indirectly like
change in a source. 1. When a timer expires
• Generated as a consequence of a person 2. When a counter exceeds a value
interacting with the elements in a GUI. 3. A software or hardware failure occurs
• Example – Entering a character via keyboard, 4. When an operation is completed.
selecting an item from a list, clicking the
mouse etc.
2 September 2021 5 2 September 2021 6
Delegation Event Model Delegation Event Model
• Defines standard and consistent mechanisms • Listeners must register with a source in order
to generate and process events. to receive an event notification.
• Source generates an event and sends to one • The benefit is that notifications are sent only
or more listeners. to listeners that want to receive them.
• Listener simply waits until it receives an event.
• Once received, the listener processes the
event and then returns.
2 September 2021 7 2 September 2021 8
Event Sources Event Sources
• A source is an object that generates an event. • When an event occurs, all registered listeners
• Occurs when the internal state of that object are notified and receive a copy of the event
changes in some way. object.- Multicasting
• A source must register listeners in order for • Some sources allow only one listener to
the listeners to receive notifications about a register. When an event occurs, the registered
specific type of event. listener is notified. - Unicasting
2 September 2021 9 2 September 2021 10
Event Listeners Event Class
• A listener is an object that is notified when an 1. ActionEvent - Generated when a button is
event occurs. It has 2 requirements. pressed, a list item is double-clicked or a menu
item is selected.
1. It must have been registered with one or more
sources to receive notifications about specific 2. AdjustmentEvent – Generated when a scroll bar
is manipulated.
type of events.
3. ComponentEvent – Generated when a
2. It must implement methods to receive and component is hidden, moved, resized or
process these notifications. becomes visible.
• Methods that receive and process events are 4. ContainerEvent – Generated when a component
defined in a set of interfaces in java.awt.event is added or removed.
2 September 2021 11 2 September 2021 12
Event Class Event Class
5. FocusEvent – Generated when a component 8. KeyEvent – Generated when input is
gains or loses keyboard focus. received from the keyboard.
6. InputEvent – Abstract super class for all 9. MouseEvent – Generated when the mouse is
component input event classes. dragged, moved, clicked, pressed or released.
7. ItemEvent - Generated when a checkbox or Also generated when the mouse enters or
list item is clicked. Also occurs when a choice exits a component.
selection is made or a checkable menu item
is selected or deselected.
2 September 2021 13 2 September 2021 14
Event Class Event Listener Interface
10.TextEvent – Generated when the value of a
text area or text field is changed. 1. ActionListener – Defines one method to
receive action events.
11.WindowEvent – Generated when a window is
activated, closed, deactivated, deiconified, void actionPerformed(ActionEvent ae)
iconified, opened or quit. 2. AdjustmentListener – Defines one method to
receive adjustment events.
void adjustmentValueChanged(AdjustmentEvent
ae)
2 September 2021 15 2 September 2021 16
Event Listener Interface Event Listener Interface
3. ComponentListener – Defines 4 methods to 4. ContainerListener – Defines 2 methods to
recognize when a component is hidden, recognize when a component is added to or
moved, resized or shown. removed from a container.
void componentResized(ComponentEvent ce) void componentAdded(ContainerEvent ce)
void componentMoved(ComponentEvent ce) void componentRemoved(ContainerEvent ce)
void componentShown(ComponentEvent ce)
void componentHidden(ComponentEvent ce)
2 September 2021 17 2 September 2021 18
Event Listener Interface Event Listener Interface
5. FocusListener – Defines 2 methods to 6. ItemListener – Defines 1 method to recognize
recognize when a component loses or gains when the state of an item changes.
keyboard focus. void itemStateChanged(ItemEvent ie)
void focusGained(FocusEvent fe)
void focusLost(FocusEvent fe)
2 September 2021 19 2 September 2021 20
Event Listener Interface Event Listener Interface
7. KeyListener – Defines 3 methods to recognize 8. MouseListener – Defines 5 methods to recognize
when a key is pressed, released or typed. when a mouse is clicked, enters a component,
void keyPressed(KeyEvent ke) exits a component, is pressed or released.
void mouseClicked(MouseEvent me)
void keyReleased(KeyEvent ke)
void mouseEntered(MouseEvent me)
void keyTyped(KeyEvent ke)
void mouseExited(MouseEvent me)
void mousePressed(MouseEvent me)
void mouseReleased(MouseEvent me)
2 September 2021 21 2 September 2021 22
Event Listener Interface Event Listener Interface
9. MouseMotionListener – Defines 2 methods 10. TextListener – Defines 1 method to recognize
to recognize when a mouse is dragged or when a text value changes.
moved. void textChanged(TextEvent te)
void mouseDragged(MouseEvent me)
void mouseMoved(MouseEvent me)
2 September 2021 23 2 September 2021 24
Event Listener Interface Example Program
11. WindowListener – Defines 7 methods to recognize • Handling Mouse Events
when a window is activated, closed, deactivated,
iconified, deiconified, opened or quit. • Handling Keyboard Events
void windowActivated(WindowEvent we)
void windowClosed(WindowEvent we)
void windowClosing(WindowEvent we)
void windowDeactivated(WindowEvent we)
void windowIconified(WindowEvent we)
void windowDeiconified(WindowEvent we)
void windowOpened(WindowEvent we)
2 September 2021 25 2 September 2021 26
AWT: Frame Class AWT: Frame Class
• The Frame class is derived from the base class • We cannot specify the dimensions of the
Window. window. Instead we must set the size of the
window after it has been created.
• Constructors • setSize() – this method is used to set the
1. Frame() - Creates a standard window that dimensions of the window.
does not contain a title. void setSize(int newWidth,int newHeight)
2. Frame(String title) – Creates a standard Example
window with the title specified by title. Frame f=new Frame()
f.setSize(400,300);
2 September 2021 27 2 September 2021 28
AWT: Frame Class AWT: Frame Class
• Hiding and Showing a Window – After a frame • Setting a Window’s Title – We can change the
window has been created, it will not be visible title in a frame window using setTitle().
until we call setVisible().
void setVisible(boolean visibleFlag) void setTitle(String newTitle)
Example Example
Frame f=new Frame(); Frame f= new Frame();
f.setVisible(true); f.setTitle(“Java Window”);
The component is visible, if the argument is True.
Otherwise it is hidden.
2 September 2021 29 2 September 2021 30
AWT Controls 1. AWT Controls - Labels
1. Label • Labels are passive controls that do not support
any interaction with the user.
2. Button
Constructors
3. Checkbox 1. Label()
4. Choice 2. Label(String str)
5. List 3. Label(String str, int how)
6. TextField The value of how is one of the three constants:
Label.LEFT, Label.RIGHT or Label.CENTER
7. TextArea
Example Program
2 September 2021 31 2 September 2021 32
2. AWT Controls - Button 2. AWT Controls - Button
• Most widely used control. void setLabel(String str)
• Generates an event when it is pressed. String getLabel()
• Push buttons are objects of type Button
Example
Constructors
1. Button() Button b1 =new Button();
2. Button(String str) b1.setLabel(“OK”);
After a button is created, we can set the label by String lab=b1.getLabel();
calling setLabel() and retrieve its label by calling
getLabel()
2 September 2021 33 2 September 2021 34
2. AWT Controls - Button 3. AWT Controls - Checkbox
• Each time a button is pressed, an ActionEvent • A control that is used to turn an option on or
is generated. off.
• ActionListener interface defines the • Consists of a small box that can either
actionPerformed() method. contain a check mark or not.
• The label of the button that is pressed is • There is a label associated with each
obtained by calling getActionCommand(). Checkbox.
Example Program • They can be used individually or as a part of
a group.
2 September 2021 35 2 September 2021 36
3. AWT Controls - Checkbox 3. AWT Controls - Checkbox
Methods
Constructors 1. boolean getState() – retrieve the current state of a Checkbox.
1. Checkbox() boolean b=c1.getState()
2. Checkbox(String str) 1. void setState(boolean on) – to set the state of a Checkbox.
c1.setState(false)
3. Checkbox(String str, boolean on) 1. String getLabel() – obtains the current label associated with a
Checkbox.
4. Checkbox(String str, boolean on, String s=c1.getLabel()
CheckboxGroup cbgroup) 1. void setLabel(String str) - set the new label with the string passed.
c1.setLabel(“Tennis”)
5. Checkbox(String str, CheckboxGroup cbgroup,
boolean on)
2 September 2021 37 2 September 2021 38
3. AWT Controls - Checkbox 3. AWT Controls - Checkbox
Handling Checkboxes Methods Example
• Each time, a check box is selected or Checkbox cb = new Checkbox(“Course”, true);
deselected, an ItemEvent is generated. boolean b= cb.getState();
• This is send to ItemListener interface which cb.setState(false);
implements itemStateChanged() method. String s = cb.getLabel();
Example Program cb.setLabel(“Subject”);
2 September 2021 39 2 September 2021 40
4. AWT Controls - CheckboxGroup 5. AWT Controls – Choice Control
• Mutually exclusive check boxes in which one • Used to create a pop-up list of items.
and only one checkbox in the group can be • When the user clicks on it, the whole list of
checked at any one time. choices pops up.
• Hence they are called “Radio Buttons”. • Only one default constructor.
Methods
1. Checkbox getSelectedCheckbox()
2. void setSelectedCheckbox(Checkbox which)
Example Program
2 September 2021 41 2 September 2021 42
5. AWT Controls – Choice Control 5. AWT Controls – Choice Control
Methods Handling Choice Lists
1. void add(String name) – adds an item to the • Each time a choice is selected, an ItemEvent
choice control. is generated.
2. String getSelectedItem() – determines which • The ItemListener interface defines the
item is currently selected.
itemStateChanged() method.
3. int getSelectedIndex() – returns the index of
the item. Example Program
4. int getItemCount() – obtains the number of
items in the list.
2 September 2021 43 2 September 2021 44
6. AWT Controls – List 6. AWT Controls – List
• Provides a compact, multiple-choice, scrolling Methods
selection list.
• Allows multiple selection.
1. void add(String name) - name is the item added
Constructors
to the list.
1. List() – creates a List control that allows only one item 2. void add(String name, int index) – adds the item
to be selected at any one time. to the specified index.
2. List(int numRows) – numRows specifies the number 3. String getSelectedItem() – returns a string
of entries in the list that will always be visible.
containing the name of the item.
3. List(int numRows, boolean multipleSelect) - if
multipleSelect is True, then user can select two or 4. int getSelectedIndex() – returns the index of the
more items. item.
2 September 2021 45 2 September 2021 46
6. AWT Controls – List 6. AWT Controls – List
Methods Handling Lists
5. String[] getSelectedItems() – returns an array
containing the names of the currently selected • To process the events in a List, we need to
items. implement the ActionListener interface.
6. int[] getSelectedIndexes() – returns an array
containing the indexes of the currently selected
item.
7. int getItemCount() – obtain the number of items
in a list.
8. String getItem (int index) – index specifies the
index of the desired item.
2 September 2021 47 2 September 2021 48
7. AWT Controls – TextField 7. AWT Controls – TextField
• Single line text entry area. Handling TextField
Constructors 1. String getText() – To obtain the string currently
1. TextField() contained in the TextField.
2. TextField(int numChars) – creates a TextField 2. void setText(String str)– To set the text to a TextField.
numChars wide 3. String getSelectedText() – returns the selected Text.
3. TextField(String str) – creates a TextField and 4. void setEchoChar(char ch) – disable the echoing of
initializes that is str characters wide. characters.
4. TextField(String str, int numChars) - creates a 5. char getEchoChar() – ch specifies the character to be
TextField numChars wide and initializes that is echoed.
str characters wide. Example Program
2 September 2021 49 2 September 2021 50
8. AWT Controls – TextArea 8. AWT Controls – TextArea
Handling TextArea Constructors
• Used for handling multiline texts 4. TextArea(String str, int numLines, int numChars)
Constructors 5. TextArea(String str, int numLines, int numChars,
1. TextArea() int sBars) – sBars must be one of these values.
2. TextArea(int numLines, int numChars) – SCROLLBARS_BOTH(4),
numLines specifies the height, in lines of the SCROLLBARS_NONE(3),
TextArea and numChars specifies the width in SCROLLBARS_HORIZONTAL_ONLY(2),
characters. SCROLLBARS_VERTICAL_ONLY (1)
3. TextArea(String str) Example Program
2 September 2021 51 2 September 2021 52
SWINGS SWINGS - Architecture
• Swing is a set of classes that provides more
powerful and flexible components such as
buttons, checkboxes, labels etc.
• For example a button may have both an image
and a text string associated with it.
2 September 2021 53 2 September 2021 54
Components of SWING - JLabel Components of SWING - JTextField
• Swing labels are instances of the JLabel class. It • Swing version of TextField.
can display text and icon. • Constructors for JTextField
• Constructors for JLabel ✓JTextField()
✓ JLabel(Icon i)
✓JTextField(int cols)
✓ JLabel(String s)
✓JTextField(String s, int cols)
✓ JLabel(String s, Icon i, int align)
✓JTextField(String s)
• where s is the text and i is the icon for the label.
The align argument is either LEFT, RIGHT, CENTER, • where s is the string passed to the text field
LEADING or TRAILING. and cols is the number of cols in the text field.
2 September 2021 55 2 September 2021 56
Components of SWING - JTextArea Components of SWING - JButton
• Swing version of TextArea. • Swing version of Button. More powerful than buttons
• Constructors for JTextArea in AWT.
✓ JTextArea()-Constructs a new TextArea. • For example, we can place an icon on the swing button.
✓ JTextArea(int rows, int columns)-Constructs a new • Constructors for JButton
empty TextArea with the specified number of rows and ✓ JButton(Icon i)
columns. ✓ JButton(String s)
✓ JTextArea(String text)-Constructs a new TextArea with ✓ JButton(String s, Icon i)
the specified text displayed. • where s and i are the string and icon used for the
✓ JTextArea(String text, int rows, int columns)-Constructs button.
a new TextArea with the specified text and number of • On clicking the button, ActionEvent will be generated
rows and columns. which will be handled by ActionListener interface.
2 September 2021 57 2 September 2021 58
Components of SWING - JCheckBox Components of SWING - JRadioButton
• Swing version of Checkbox. • Swing version of RadioButton.
• It has two states either checked or unchecked. • The button has only two states
• Constructors for JCheckBox • Constructors for JRadioButton
✓ JCheckBox(Icon i) ✓ JRadioButton(Icon i)
✓ JCheckBox(Icon I, boolean state) ✓ JRadioButton(Icon i, boolean state)
✓ JCheckBox(String S) ✓ JRadioButton(String s)
✓ JCheckBox(String s, boolean state) ✓ JRadioButton(String s, boolean state)
✓ JCheckbox(String s, Icon i) ✓ JRadioButton(String s, Icon i)
✓ JCheckbox(String s, Icon i, boolean state) ✓ JRadioButton(String s, Icon i, boolean state)
• where s and i are the string and icon used for the button. • where s and i are the string and icon used for the button.
• When a check box is selected or deselected, an ItemEvent is • When a radio button is pressed, it generates ActionEvent that is
generated. This is handled by itemStateChanged() method of handled by actionPerformed() method of ActionListener interface.
ItemListener. The getItem() method gets the JCheckBox object that The getActionCommand() method gets the text that is associated
generated the event. with a radio button.
2 September 2021 59 2 September 2021 60
Components of SWING - JComboBox Components of SWING - JList
• Swing version of Combo box. • Swing version of List.
• A combo box normally displays one entry. • Displays a list of objects and allows the user to select one or more
items.
• It also displays a drop-down list that allows a user to select • Constructors for JList
a different item.
✓ JList()-Constructs a JList with an empty, read-only, model.
• Constructors for JComboBox ✓ JList(Object[] listData)- Constructs a JList that displays the elements
✓ JComboBox() in the specified array.
✓ JComboBox(Vector v) • JList generates a ListSelectionEvent when the user makes or
• Here v is a vector that initializes the combo box. Items are changes a selection.
added to the combo box using addItem() method. The • Also generated when the user deselects an item.
syntax of addItem() is as follows. • It is handled by implementing ListSelectionListener. This listener
specifies only one method, called valueChanged( ), which is shown
➢ void addItem(Object obj) below.
• where obj is the object added to the combo box. • void valueChanged(ListSelectionEvent le)
2 September 2021 61 2 September 2021 62
Components of SWING - JList Components of SWING - JFrame
• JList allows the user to select multiple ranges of items within the
list. • Swing version of Frame.
• We can change this behavior by calling setSelectionMode( ) which is
defined by JList. The syntax is shown below. • Top-level window with a title and a border.
• void setSelectionMode(int mode)
• mode specifies the selection mode. It must be one of these values
• Constructors for JFrame
SINGLE_SELECTION,
MULTIPLE_INTERVAL_SELECTION.
SINGLE_INTERVAL_SELECTION or ✓JFrame()-Constructs a new frame that is
• The default is the MULTIPLE_INTERVAL_SELECTION. It lets the user initially invisible.
to select multiple ranges of items within a list.
• With SINGLE_INTERVAL_SELECTION, the user can select a range of ✓JFrame(String title)-Creates a new, initially
items.
• With SINGLE_SELECTION, the user can select only a single item. invisible Frame with the specified title.
2 September 2021 63 2 September 2021 64
Components of SWING - JPanel Layout Managers
• Swing version of Panel. • A Layout Manager automatically arranges the
• A Container is a component that can contain other SWING
components. controls within a window.
• A container provides a space where a component can be located
• For example, JPanel, JFrame and JWindow are Containers.
1. Flow Layout
• JPanel is the simplest container. It provides space in which any 2. Border Layout
other component can be placed, including other panels.
• Constructors for JPanel 3. Grid Layout
✓ JPanel()-Creates a new JPanel with a flow layout.
✓ JPanel(LayoutManager layout)-Creates a JPanel with the specified
4. Card Layout
layout manager. 5. Box Layout
6. Null Layout
2 September 2021 65 2 September 2021 66
Layout Managers Layout Managers
1. FlowLayout 2. BorderLayout
• Default layout manager • Implements a common layout style for top-level
• Components are laid from upper left corner, left to right and top windows.
to bottom.
Constructors • Four sides are referred to as north, south, east and
1. FlowLayout() – creates a default layout which centers components west.
and leaves five pixels of space between each component. • Middle area is called the center.
2. FlowLayout(int how) – Specify how each line is aligned. Constructors
(FlowLayout.LEFT,
FlowLayout.CENTER, 1. BorderLayout() – creates a default layout.
FlowLayout.RIGHT) 2. BorderLayout(int horz, int vert) – Specify the
3. FlowLayout(int how, int horz, int vert) - specify the horizontal and horizontal and vertical space left between the
vertical space left between components in horz and vert components in horz and vert respectively.
Example Program
2 September 2021 67 2 September 2021 68
Layout Managers Layout Managers
2. BorderLayout 3. GridLayout
• Defines the following constants that specify the • Lays out components in a two-dimensional grid.
regions. Constructors
1. GridLayout() – creates a single-column grid layout.
1. BorderLayout.CENTER 2. GridLayout(int numRows, int numColumns) – creates
2. BorderLayout.EAST a grid layout with the specified number of rows and
columns.
3. BorderLayout.NORTH
3. GridLayout(int numRows, int numColumns, int horz,
4. BorderLayout.SOUTH int vert) – allows to specify the horizontal and vertical
5. BorderLayout.WEST space left between components in horz and vert
respectively.
Example Program
2 September 2021 69 2 September 2021 70
Layout Managers Layout Managers
3. GridLayout 4. CardLayout
• numRows or numColumns can be zero. • Unique among other layout managers in that
• Specifying numRows as zero allows for it stores several different layouts.
unlimited-length columns. • Each layout can be thought of as a separate
• Specifying numColumns as zero allows for index card in a deck that can be shuffled so
unlimited length rows. that any card is on top at a given time.
Example Program
2 September 2021 71 2 September 2021 72
Layout Managers Layout Managers
4. CardLayout 4. CardLayout
• After creating a deck, the program activates a card by
Constructors calling one of the following methods.
1. void first(Container deck) – first card will be shown.
1. CardLayout() – creates a default card layout 2. void last(Container deck)- last card will be shown.
2. CardLayout(int horz, int vert)- specify the 3. void next(Container deck) – next card will be shown.
4. void previous(Container deck) – previous card will be
horizontal and vertical space between the shown.
components. 5. void show(Container deck, String cardName) – displays
the card whose name is passed in the cardName.
Example Program
2 September 2021 73 2 September 2021 74
Layout Managers Layout Managers
5. BoxLayout 6. NullLayout
• The BoxLayout is used to arrange the • Rather than using a layout manager that controls the size
and position of all components in a container, we can set
components either vertically or horizontally. the layout manager to null.
• For this purpose, BoxLayout provides four • Each component then controls its own position and size
constants. They are X_AXIS, Y_AXIS, LINE_AXIS using its bounds.
and PAGE_AXIS. The following shows the • Creating a container without a layout manager involves
constructor for the BoxLayout class. the following steps.
• BoxLayout(Container c, int axis)- creates a box 1. Set the container’s layout manager to null by calling
setLayout(null).
layout that arranges the components with the 2.Call the Component class’s setBounds() method for
given axis. each of the container’s children.
Example Program Example Program
2 September 2021 75 2 September 2021 76
End of Unit 4
2 September 2021 77