Chapter - 1 Final
Chapter - 1 Final
Advanced
Advanced Programming
Programming
(SENG2083)
Mr. Addisu M. (Asst. Prof) G3 SE - Regular
1
Chapter 1
Advanced Programming
Panels, Window, Frame
Implementation of JFrame and Adding
Component
Event Handling
3
Jun 23, 2024
Introduction to GUI (Graphical User Interface)
GUI (Graphical User Interface) – visual interface to program
built from GUI components (buttons, scrollbars, menus, labels,
text fields, etc)
GUI component – an object with which the user interacts via
mouse or keyboard
gives an application a distinctive “look and feel”
Advanced Programming
appearance and how user interacts with the program are know
as the program “look and feel”
Classes that are used to create GUI components are part of
java.awt or javax.swing package
Both these packages provide rich set of user interface components
4
GUI vs Non-GUI
Advanced Programming
Non-GUI support classes – provide services and
perform necessary functions for GUI classes
do not produce any visual output
Example: Layout managers & Event handling
5
GUI Components
Advanced Programming
Called Heavyweight components called lightweight components
Swing GUI component classes are
Prefix J is not used here
named with a prefixed J
E.g.: Button, Label, TextField E.g.: JButton, JLabel, JTextField
Advanced Programming
happen, an event handler is called
GUI is built of graphical elements called components, such
as buttons, scrollbars, and text fields, labels etc
7
What is AWT?
Advanced Programming
i.e. components are displayed according to the view of OS
its components are often called Heavy Weight Components
(HWC) as they rely on local platform’s OS
its components are using resources of underlying OS
8
What is AWT?
Advanced Programming
set of classes and Interfaces which are required to develop GUI
components together are called as ‘Toolkit’.
GUI components will be used to design GUI programs
Writing a program to display the created GUI components on the
windows is called as ‘windowing’
9
Hierarchy of AWT & Swing Classes
Advanced Programming
Component classes, and
Helper classes
11
Container Classes
Advanced Programming
Note:
A container itself is a component, therefore we can add a
container inside container
• four types of containers :
1. Window 3. Frame
2. Panel 4. Dialog 12
Container Classes
Advanced Programming
Create an instance of Window class to create this container
Constructor: public Window(Frame parent);
Parent frame window is necessary because only objects of
the Frame class or it’s subclasses contain the functionality
needed to implement an independent application window
13
Container ClassesA
Advanced Programming
can have other components like button, text field, etc
Implements MenuContainer interface. Hence capable of working
with MenuBar objects
Constructor:
public Frame() :-Creates an untitled frame window
public Frame(String title) :-String argument used as frame’s window
title 14
Container Classes
Advanced Programming
can be created in two ways:
Create the object of Frame by Instantiating Frame class
Ex: Frame f = new Frame();
Create the object of any class that extends Frame class
(inheritance)
Ex: class MyFrame extends Frame 15
Container Classes
Advanced Programming
fm.setSize(300, 300); //setting frame size.
fm.setVisible(true); //set frame visibilty true
}
public static void main(String args[]) {
Testawt ta = new Testawt();
}
}
16
Container Classes
Advanced Programming
setTitle("StudyTonight"); //setting title
setLayout(new FlowLayout());//set default layout
//arranging components in a line, one after another(in a flow)
setVisible(true); //set frame visibilty true
}
public static void main (String[] args) {
Testawt ta = new Testawt(); //creating a frame.
}
}
17
Container Classes
Advanced Programming
You can add the following method also for resizing the frame
setResizable(true);
• Panel
doesn't contain title bar, border or menu bar
generic container for holding components like button, text field etc
An instance of Panel class creates a container, in which we can add
components 18
Container Classes
Advanced Programming
panel.setBounds(40,80,200,200);
panel.setBackground(Color.gray);
Button b1=new Button("Button 1");
b1.setBounds(50,100,80,30);
b1.setBackground(Color.yellow);
Button b2=new Button("Button 2");
b2.setBounds(100,100,80,30); 19
Container Classes
Advanced Programming
}
public static void main(String args[])
{
new PanelExample();
}
} 20
Component Classes
Advanced Programming
the screen
Both Component & JComponent are abstract classes
• In order to place every component in a particular
position on a screen, we need to add them to a
container
21
Component Classes
Advanced Programming
Button b = new Button(String label);
b = new Button(“OK”); //create the components
b.setBounds(100,100,80,40); //(x, y, w, h) set boundaries
this.add(b); //adding the component to the frame
22
Component Classes
Advanced Programming
allow the user to enter some text.
Creation of TextField: TextField tf = new TextField(size);
Checkbox:
allows to select any # of options from group of options
Creation of checkbox: Checkbox cb = new Checkbox();
23
Component Classes
Advanced Programming
class called “CheckboxGroup”
Creation of RadioButton:
CheckboxGroup cbg = new CheckboxGroup();
Checkbox rb = new Checkbox(Label, cbg, boolean);
mal = new Checkbox (“Male", cbg, true);
femal = new Checkbox (“Female", cbg, false);
add (mal); add (femal); 24
Helper Classes
Advanced Programming
Dimension, and LayoutManager
• not sub-classes of Component
• used to describe the properties of GUI components
25
What is Swing?
Advanced Programming
called as light weight components which improve performance
of the application because amount of resources required is very
minimum
Not depend on OS – manipulated & displayed completely in Java
allow programmer to specify a uniform look and feel across all
platforms - appearance and how user interacts with program
Consistent appearance for the components in different platform 26
Container classes
Advanced Programming
when running an application
• JDialog – resembles a small frame that pops up in front
of the application’s window
used to communicate with user, by displaying certain messages
and waiting for user’s response via buttons
27
Container classes
Advanced Programming
components.
• ff code is used to populate a container with
components:
topLevelContainer.add(anyComponent)
28
Methods of Swing classes
Advanced Programming
void setLocation(intx, inty)
void setBounds(intx, inty, intw, inth)
void setFont(Font f)
void setBackground (Color c)
void setVisible(boolean b) 29
Anatomy of an Application GUI
JPanel containers
JPanel
JButton
Advanced Programming
JButton JLabel
JLabel
30
Frame
Advanced Programming
have to set its size before using it
default visibility status is false (i.e. not visible)
have to set its visibility to true
default layout manager is BorderLayout
can change that if needed 31
Frame
Advanced Programming
variables as parameter:
DISPOSE_ON_CLOSE: to close the current frame but doesn’t terminate
the application
DO_NOTHING_ON_CLOSE: to ignore the closing operation
EXIT_ON_CLOSE: to exit appln (close all frame & terminate appln)
HIDE_ON_CLOSE: to just hide the frame (default behavior)
The above variables are defined in interface WindowConstants 32
Frame
Advanced Programming
public First() {
jf = new JFrame("MyWindow");//Creating with title
JButton btn = new JButton("Say Hello");//Creating Button
jf.add(btn); //adding button to frame
jf.setLayout(new FlowLayout());//setting layout
33
Frame
Advanced Programming
}
public static void main(String[] args) {
new First();
}
}
34
Frame
Advanced Programming
public Second() {
setTitle("MyWindow"); //setting title of frame
JLabel lb = new JLabel("Welcome to My Second Window");
//Creating a label named Welcome to My Second Window
add(lb); //adding label to frame.
setLayout(new FlowLayout()); //setting layout using FlowLayout
object 35
Frame
Advanced Programming
}
public static void main(String[] args) {
new Second();
}
}
36
Frame
Advanced Programming
setSize(int width, int height);
setVisible(true);
When you create components like Buttons, TextFields, etc, you
need to add it to the frame by using the method
add(Component's Object);
You can add the following method also for resizing frame
37
setResizable(true);
Dialog
Advanced Programming
message or something they enter into a text area
a perfect tool for collecting or displaying important
information
• Java provides several classes to create dialog boxes
classes include JOptionPane, JDialog, and JFrame
39
Dialog
Advanced Programming
It provides standard dialog boxes, it has many options allowing you
to tweak its behavior
• INFORMATION_MESSAGE - default
• ERROR_MESSAGE
• WARNING_MESSAGE
• QUESTION_MESSAGE
• PLAIN_MESSAGE 40
Dialog
Advanced Programming
JOptionPane.ERROR_MESSAGE);
}
public static void main(String[] args) {
new JOptionPaneApp();
}
Example 41
}
Dialog
Advanced Programming
JOptionPane.showMessageDialog(null, “Thank you!!!");
}
else { // choice == NO_OPTION or CANCEL_OPTION
JOptionPane.showMessageDialog(null, “Please, get ready!");
} Example 42
Menubar, Menu, MenuItem
Advanced Programming
Commonly Used Constructor(s): JMenuBar()
Commonly Used Method(s):
JMenuadd(JMenum)
Int getMenuCount()
JMenu getMenu(int index)
• Creation of menu bar: JMenuBar mbar = new JMenuBar(); 43
Menubar, Menu, MenuItem
Advanced Programming
Commonly Used Constructor(s):
JMenuItem() , JMenuItem(String label)
JMenuItem(String label, intmnemonic)
Commonly Used Method(s):
void setActionCommand(String command) void setLabel(String label)
String getActionCommand() String getLabel()
void addActionListener(ActionListeneral)
void removeActionListener(ActionListeneral) 44
Menubar, Menu, MenuItem
Advanced Programming
a1 = new JMenuItem("Cut");
a2 = new JMenuItem("Copy");
menu.add(a1);
menu.add(a2);
m1.add(menu);
f.setJMenuBar(m1); Example 45
Label
Advanced Programming
Icon & str icon and text used for label
To obtain an icon, and object of ImageIcon class has to be
passed as an argument to the Icon parameter.
Align horizontal alignment of the text/and or icon
must be one of the following values: LEFT, RIGHT,
CENTER 46
Button
Advanced Programming
Creation of JButton: JButton jb = new JBtton(label);
Event Generated:
when button is pressed ActionEvent object is generated
To deal with the event, implement ActionListener interface,
register the listener and define the method public void
actionPerformed(ActionEvent) 47
Checkboxes
Advanced Programming
Event Generated:
It generates one item event and one action event per click
Usually, you listen only for item events, since they let you
determine whether the click selected or deselected check box
Creates ItemEvent Object;
Register with ItemListener interface;
Implement void itemStateChanged() 48
Checkboxes
Advanced Programming
JCheckBox(String, Icon) Creates an initially unselected check box with the specified
text and icon.
JCheckBox(String, Icon, Creates a check box with text and icon, and specifies
boolean) whether or not it is initially selected.
JCheckBox() Creates an initially unselected check box button with no text,
no icon.
49
RadioButtons
Advanced Programming
JRadioButton jrb = new JRadioButton(Label,boolean);
• ButtonGroup: used to place multiple buttons into a single
group in which only one button at a time can be selected
Creation of ButtonGroup:
ButtonGroup bg = new ButtonGroup();
use its add method to include JRadioButton objects in group
bg.Add(jrb); 50
ComboBox
Advanced Programming
drop-down list) through the JComboBox class
Constructors: JComboBox() & JComboBox(Object[])
Items are added to list of choices via addItem( ) method,
jcb.addItem(item);
obj is the object to be added to the combo box
• Creation of JComboBox: JComboBox jcb = new JComboBox(); 51
ComboBox
Advanced Programming
void actionPerformed(ActionEvent)
ItemEvent Add an item listener to the combo box. The
listener's itemStateChanged() method is
ItemListener
called when the selection state of any of the
addITemListener combo box's items change
void itemStateChanged()
52
TextField
Advanced Programming
JTextField address = new JTextField(60);
JPanel p=new JPanel();
p.add(firstName);
p.add(surName);
p.add(address);
53
PasswordField
Advanced Programming
JPanel p=new JPanel();
p.add(list);
55
Event Handling
Advanced Programming
clicking the button o choosing an item from a menu
Press a button o Selecting an item form a list etc
• import Statements: to use events, you must import:-
• import java.awt.*; AWT
• import java.awt.event.*;
• import javax.swing.*;
• import javax.swing.event.*;
Swing 56
Event Handling
Advanced Programming
4. Now the method will get executed and returned
Event handling – mechanism that controls event and decides
what should happen if an event occurs
activity of capturing events and take appropriate action as
per requirements (e.g. Print a message)
have the code (known as event handler) that is executed
when an event occurs 57
Event Handling
Advanced Programming
Triggering a source fires an event to all its listener(s), and
invoke an appropriate event handler of the listener(s) 58
Event Handling
Advanced Programming
which can listen to the events that are generated
After the listener listens to the generated event, it
delegates (passes) the event information to one of the
method available in that listener
This process is called as “Event Delegation Model” 59
Event Handling
Advanced Programming
60
Event Handling
Advanced Programming
61
Event Handling
Advanced Programming
allowed to generate several different types of events
When an event occurs, all registered listeners are
notified and receive a copy of the event object
In all cases, notifications are sent to listeners that
register to receive them
62
Event Handling
Advanced Programming
movements, button clicks and keystrokes) or by internal
program activities (timer)
The component that creates an event and fires it is called
event source object or source component
Firing an event means to create an event and delegate
listener to handle the event
E.g., button is source object for button clicking action event 63
Event Handling
Advanced Programming
object that is invoked when an event triggers
must be registered with an event source object, and it
must be an instance of an corresponding event-handling
(event-listener) interface - ActionListener interface
listener interface contains the method(s), known as the event
handler(s), for processing the event 64
Event Handling
Advanced Programming
• Note: a single event source can have multiple listeners
listening for its events
registration method form: addTypeListener(TypeListener el)
Type: name of event & el: reference to event listener
ActionListener interface contains the actionPerformed method
for processing the event
ActionEvent object is passed as parameter to actionPerformed() 65
Event Handling
Advanced Programming
jbtOK.addActionListener(listener1);
}
Register Listener
public void actionPerformed(ActionEvent e) {
textField.setText ("Hello World");
}
Process Event 66
Event Handling
Advanced Programming
• When OK button is clicked,
actionPerformed(ActionEvent) method in
OKListenerClass is invoked to process the event
67
Event Handling
Advanced Programming
key on component addKeyListener() keyPressed(), keyReleased(),
keyTyped()
mouse on component addMouseListener() mouseClicked(), mousePressed(),
mouseReleased(), …
mouse on component addMouseMotionListener() mouseMoved(), mouseDragged()
windowClosing(WindowEvent e),
Frame addWindowListener() windowActivated(),
windowOpened(),..
68
Event Handling
Advanced Programming
Click a radio button JRadioButton ItemEvent, ActionEvent
Press return on a text field JTextField ActionEvent
Select a new item JComboBox ItemEvent, ActionEvent
Window opened, closed, etc. Window WindowEvent
Mouse pressed, released, etc. Component MouseEvent
Key released, pressed, etc. Component KeyEvent
69
Event Handling
Advanced Programming
three approaches for performing event handling:
1.Within Class – implemented in single class
2.Other Class – implemented using another class
3.Anonymous Class – implemented in an inner class which does
not contains any name
70
Event Handling
Advanced Programming
textField = new TextField ();
textField.setBounds (60, 50, 170, 20);
Button button = new Button ("Show");
button.setBounds (90, 140, 75, 40);
button.addActionListener (this);
add (button); add (textField); 71
Event Handling
Advanced Programming
textField.setText ("Hello World");
}
public static void main (String args[]) {
new EventHandling ();
}
}
After Clicking, text field value is set to Hello World! 72
Event Handling
Advanced Programming
tf.setBounds(60,50,170,20); setSize(300,300);
Button b = new Button("click me"); setLayout(null);
setVisible(true);
b.setBounds(100,120,80,30);
}
Outer o = new Outer(this); public static void main(String args[]){
b.addActionListener(o); new MyClass();
add(b); }
add(tf); } 73
Event Handling
Advanced Programming
this.obj = obj;
}
public void actionPerformed(ActionEvent e){
obj.tf.setText("Hello, outher here.");
}
} 74
How to build a GUI
Advanced Programming
chose layout manager
Write some Listeners and attach them to your Components
Interacting gets a Component causes an Event to occur
listener gets a message when an interacting event occurs, and
executes some code to deal with it
Display your window
75
How to build a GUI
Advanced Programming
//size of the frame width and height
myFr.setSize(500,500);
myFr.setVisible(true);
//this v.impt visibility
myFr.setDefaultCloseOperation(Jframe.EXIT_ON_CLOSE);
}
}
76
How to build a GUI
Advanced Programming
So, now we are able to add component
in that area of frame 77
How to build a GUI
Advanced Programming
Container c = myFr.getContentPane();
c.setLayout(new FlowLayout());
Advanced Programming
//Adding component to container
c.add(tf);
c.add(b1);
79
How to build a GUI
Advanced Programming
Output
80
Jun 23, 2024
The End!
Questions, Ambiguities,
Advanced Programming
Doubts, … ???
81