0% found this document useful (0 votes)
51 views64 pages

CH 1

Uploaded by

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

CH 1

Uploaded by

Tade Mf
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd

Mekdela Amba

University
Department of
Software engineering
Advanced
programming(SEng6132)
Chapter 1
AWT and Swing
Topic we discussed
1.1. Concepts of AWT and Swing
1.2. Event Handling
1.1. Concepts of AWT
and Swing
We are going to discuss AWT and Swing.
Java GUI
A graphical user interface (GUI) presents a user-
friendly mechanism for interacting with an application.
It gives an application a distinctive “look” and “feel.”
Providing different applications with consistent,
intuitive user interface components allows users to be
somewhat familiar with an application, so that they can
learn it more quickly and use it more productively. GUIs
are built from GUI components. These are sometimes
called controls or widgets.
A GUI component is an object with which the user
interacts via the mouse, the keyboard or another form
of input, such as voice recognition.

Cont...
Java has two GUI packages,
1. Abstract Windows Toolkit (AWT) - first (original)
2. Swing - newer
AWT
When java was introduced, the GUI classes were
bundled in a library known as Abstract Windows
Toolkit (AWT).
 It is Java’s original set of classes for building GUIs. It
uses peer components of the OS;
It is heavyweight and uses the native operating
system's window routines so the visual effect is
dependent on the run-time system platform.
Swing
AWT is a collection of GUI components (widgets) and
other related services required for GUI programming in
Java.
It designed to solve AWT’s problems (since Java 2). It is
99% java;
It is lightweight components as drawing of components
is done in java.
Swing GUI components allow you to specify a uniform
look-and-feel for your application across all platforms. It
also lays out consistently on all Oss. It has much bigger
set of built-in components and uses AWT event
handling.
Cont...
Swing is built “on top of” AWT, so you need to import
AWT and use a few things from it.
Swing is more flexible and better looking. Swing and
AWT are incompatible. Thus, you can use either, but
you can’t mix them.
Basic components/controls are practically the same in
both. For example:
AWT: Button b = new Button ("OK");
Swing: JButton b = new JButton("OK");
Swing vs AWT
AWT Swing
First Java GUI library A newer, more robust, and
simple graphical user flexible library .
interfaces lightweight components
heavyweight components. complex GUI projects.
platform dependent platform independent
execute slow Execute fast
does not support MVC Support MVC pattern
pattern
Does not require more
require more memory
memory space
space
Java GUI API
Java GUI APIs are categorized into three groups.
These are
1. Container class,
2. Component classes and
3. Helper class.
GUI Container classes
A GUI is built by putting components/controls into
containers. Thus, container is used to group
components.
Frames, Panels and applets are examples of
containers. Important Container classes are JFrame,
JApplet, JDialog and JPanel.

Frame
A resizable, movable window with title bar and close
button. Usually it contains JPanels. It is a container
that holds other Swing user-interface components in
Java GUI application.
Jpanel
JPanel is a region internal to a JFrame or another
JPanel. It is used for grouping components together.
JPanel is optionally bounded by a visible border . It
lives inside some enclosing Container. Panels can be
nested, that is, you can place panels inside a
container that includes a panel. In fact, every frame
has at least one pane, the default “Content Pane”.
GUI Component classes
GUI Components or Controls (also known as
"widgets") are the basic user interface elements the
user interacts with. These include labels, buttons and
text fields.
The visual arrangement of the components depends
on the container's layout (which are part of helper
classes).
The following are list of controls in the javax.swing
package
Cont...
Input Components
Buttons ( JButton, JRadioButtons, JCheckBox)
Text (JTextField, JTextArea)
Menus (JMenuBar, JMenu, JMenuItem)
Sliders (JJSlider
JComboBox (uneditable) (JComboBox)
List (Jlist )
Cont...
Information Display Components
JLabel
Progress bars (JProgressBar)
Tool tips (using JComponent's setToolTipText(s) method)
Choosers
File chooser (JFileChooser)
Color chooser (JColorChooser)
Cont...
More complex displays
Tables (JTable)
Trees (JTree)
GUI helper classes
Helper classes are used to describe the properties of
GUI components.
It encompasses the classes for graphics context, colors,
fonts and dimension.
Graphics: It is an abstract class that provides a graphical
context for drawings strings, lines, and simple shapes.
Cont....
Color: It deals with the colors of GUI components.
For example, we can specify background colors in
components like JFrame and JPanel while we can
specify colors of lines, shapes and etc.
Font: It specifies fonts for the text and drawings on
GUI components. Font is available on the java.awt
package.
Develop GUI
Application
JFrame
 It is like the main window of the GUI application using
swing. Created by 2 different ways.
 By extending JFrame class and by Instantiating The JFrame
Class.
 Frame is a window that is not contained inside another
window.
 Applications with a GUI typically use at least one frame.
 It used to create windows. It has two constructor namely
JFrame() and JFrame(String title).
 To create window with title are
JFrame frame = new JFrame(“My First JFrame”);
Cont…
Some method of JFrame are the following:-
setSize(width, height) //specify the width and the height frame.
setLocation(x, y) //specify the upper and left corner of location
of frame. Short cut(setBounds(x, y, w, h)
add() to add button, input and other to frame.
setVisible(visible, Boolean) // say true to display the frame.
setDefaultCloseOperation(mode: int) // specify the opration
when the frame is closed. To specify there are 3
choice(JFrame.EXIT_ON_CLOSE,
JFrame.HIDE_ON_CLOSE,
JFrame.DO_NOTHING_ON_CLOSE).
Sample of code
package helloworld;
import javax.swing.*;
/** * @author Administrator
*/
public class Helloworld {
/**
* @param args the command line arguments
*/
public static void main(String[] args) {
// TODO code application logic here
////create a JFrame object
JFrame f = new JFrame("Advanced programming JFrame example");
f.setBounds(40, 80, 200, 200); //set the size(width, height) and the location(x, y)
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.setVisible(true); //make the frame visible
}
}
JButton
 The JButton class is used to create a labeled button that has platform independent
implementation.
 It has the following constructor(JButton(), JButton(Icon icon), JButton(String text) and
JButton(String text, Icon icon))
 It has the following method(setText(String text) , getText(),etc)
setEnabled(boolean b) )
 To create JButton
JButton btn = new Jbutton()
button.setText(“Click Here”); or
JButton button= new JButton(“Click Here");
Sample of code
import javax.swing.*;
public class ButtonExample {
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);
}
}
JLabel
 A label is a display area for a short text(a non-editable), an image, or both.
 A JLabel component can be created using one of the following constructors(JLabel(),
JLabel(String text), JLabel(Icon icon) etc)
 JLabel component has various methods including the following:(getText(),
setText(String), getIcon(), setIcon(Icon icon))
 To create JLabel with text
JLabel label = new Jlabel(“First name”)
Sample of code
import javax.swing.*;
class LabelExample
{
public static void main(String args[])
{
JFrame f= new JFrame("Label Example");
JLabel l1,;
l1=new JLabel("First name:");
l1.setBounds(50,50, 100,30);
f.add(l1);
f.setSize(300,300);
f.setLayout(null);
f.setVisible(true);
}
}
JTextField
 A text field is a box that contains a line of text. The user can type text into the box and
the program can get it and then use it as data. The program can write the results of a
calculation to a text field. Text fields are useful in that they enable the user to enter in
variable data (such as a name or a description).
 JTextField is swing class for an editable text display.
 Its component are (JTextField(), JTextField(int columns), JTextField(String text),
JTextField(String text, int columns))
 And have a method in JTextField (getText(), setText(String text), setEditable(boolean
editable) etc)
 To create JTextField without text
JTextField Fname= new JTextField();
Sample of code
import javax.swing.*;
// Main class TextFieldExample
class TextFieldExample
{
public static void main(String args[])
{
// Creating a JFrame object with title "TextField Example."
JFrame f= new JFrame("TextField Example");
// Creating two JTextField objects
JTextField t1;
// Initializing the first JTextField with default text "Welcome to Javatpoint."
t1 = new JTextField("Welcome to Javatpoint.");
// Setting the position and size of the first JTextField
t1.setBounds(50,100, 200,30);
// Initializing the second JTextField with default text "AWT Tutorial"
// Setting the position and size of the second JTextField
// Adding JTextFields to the JFrame
f.add(t1); // Setting the size of the JFrame
f.setSize(400,400);
// Setting layout to null to use absolute positioning
f.setLayout(null);
// Making the JFrame visible
f.setVisible(true);
}
}
JPasswordField
 Allows the editing of a single line of text where the view indicates something
was typed, but does not show the original characters.
 The object of a JPasswordField class is a text component specialized for
password entry. It allows the editing of a single line of text.
 It has the following constructer(JPasswordField(), JPasswordField(int columns),
JPasswordField(String text), JPasswordField(String text, int columns))
 JPasswordField with text can be created by
JPasswordField pass = new JPasswordField(“Enter password);
Sample of code
import javax.swing.*;
public class PasswordFieldExample {
public static void main(String[] args) {
JFrame f=new JFrame("Password Field Example");
JPasswordField value = new JPasswordField();
JLabel l1=new JLabel("Password:");
l1.setBounds(20,100, 80,30);
value.setBounds(100,100,100,30);
f.add(value); f.add(l1);
f.setSize(300,300);
f.setLayout(null);
f.setVisible(true);
}
}
JTextArea
 If you want to let the user enter multiple lines of text, you cannot use text fields
unless you create several of them. The solution is to use JTextArea class, which
enables the user to enter multiple lines of text.
 Its constructor includes(JTextArea(int rows, int columns), JTextArea(String s, int
rows, int columns) )
 To create JTextArea with row and column
JTextArea ta = new JTextArea(3, 5);
Sample of code
import javax.swing.*;
public class TextAreaExample
{
TextAreaExample(){
JFrame f= new JFrame();
JTextArea area=new JTextArea("Welcome to javatpoint");
area.setBounds(10,30, 200,200);
f.add(area);
f.setSize(300,300);
f.setLayout(null);
f.setVisible(true);
}
public static void main(String args[])
{
new TextAreaExample();
}
}
JCheckBox
 It is a widget that has two states. On and Off. It is a box with a label. If the
checkbox is checked, it is represented by a tick in a box
 JCheckBox component can be created using one of the following
constructors(JCheckBox(), JCheckBox(Icon icon), JCheckBox(Icon icon,
boolean selected), JCheckBox(String text) etc)
 To create JCheckBox with text and Boolean selected
JCheckBox check = new JCheckBox(“Blue”, true);
Sample of code
import javax.swing.*;
public class CheckBoxExample
{
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, 50,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 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.
 To create JRadioButton the following constructor are necessary
(JRadioButton(), JRadioButton(String s), JRadioButton(String s,
boolean selected))
 Method that used in JRadioButton are (setText(String s),
getText(), setEnabled(boolean b) etc).
Sample of code
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);
f.setVisible(true);
}
public static void main(String[] args) {
new RadioButtonExample();
}
}
Java JTable
 The JTable class is used to display data in tabular form. It is
composed of rows and columns.
 The following constructor are used to create
 JTable(JTable() - Creates a table with empty cells.
 JTable(Object[][] rows, Object[] columns) - Creates a table with
the specified data
Example:- JTable table = new Jtable(data, column);
Sample of code
import javax.swing.*;
public class TableExample {
JFrame f;
TableExample(){
f=new JFrame();
String data[][]={ {"101","Amit","670000"},
{"102","Jai","780000"},
{"101","Sachin","700000"}};
String column[]={"ID","NAME","SALARY"};
JTable jt=new JTable(data,column);
jt.setBounds(30,40,200,300);
JScrollPane sp=new JScrollPane(jt);
f.add(sp);
f.setSize(300,400);
f.setVisible(true);
}
public static void main(String[] args) {
new TableExample();
}
}
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.
 The constructor are
 (JComboBox() - Creates a JComboBox with a default data model.
 JComboBox(Object[] items) etc) - Creates a JComboBox that contains
the elements in the specified array
 Some method are (addItem(Object anObject), removeItem(Object
anObject), removeAllItems() etc)

 It look like
Sample of code
import javax.swing.*;
public class ComboBoxExample {
JFrame f;
ComboBoxExample(){
f=new JFrame("ComboBox 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 ComboBoxExample();
}
}
JFileChooser
 FileChooser is a class that is present in the java Swing package.
 JFileChooser contains many elements that assist in building a graphical user
Interface in java.
 JFileChooser is a simple and successful method for inciting the client to pick
a file or a directory.
 The Constructors that Present in Java JFileChooser Class are
(JFileChooser(), JFileChooser(File currentDirectory) and other)
Sample of code
// program to demonstrate the JFileChooser(File currentDirectory) cons
tructor
// importing the required packages
import java.io.*;
importjavax.swing.*;
importjava.awt.event.*;
importjavax.swing.filechooser.*;
classHelloWorld
{
public static void main(String[] args) {
// creating object to the JFileChooser class
JFileChooser
jf = new JFileChooser("c:"); // parameterised constructor JFileChooser(
File currentDirectory) is called.
jf.showSaveDialog(null); // opening the saved dialogue
}
}
Java JOptionPane
 In Java, JOptionPane is a part of the Java Swing library. It helps us to
create dialog boxes such as message dialogs, conformation dialogs, input
dialogs, and options dialogs In this article, we are going to explore some
constructors, methods, and some examples of JOptionPane.
 It has the following constructor
 JOptionPane() - This is the default constructor for JOptionPane.It is
used to create a JOptionPane with no options and message.
 JOptionPane(Object message) - It creates a message dialog with a
specified message.
 JOptionPane(Object message, int messageType) - It creates a message
dialog with a specified message and its Type.
Cont…
 It have different method
 createDialog(String title) - It helps us to create JDialog with a specified
title but without any parent.
 showMessageDialog(Component parentComponent, Object
message) - This method displays a message dialog with the specified
message.
 showInputDialog(Component parentComponent, Object message) -
This method displays an input dialog with the specified message.
 setOptionType(int optionType) - This method allows you to set the
option type for the dialog.
 and other
Cont…
 Field of JOptionPane are
 ERROR_MESSAGE - A Constant code displaying an error message
icon.
 INFORMATION_MESSAGE - A Constant code displaying
information message icon
 WARNING_MESSAGE - A Constant code for displaying Warning
message icon.
 YES_NO_OPTION - A constant for creating a dialog with “Yes” and
“No” options.
 YES_NO_CANCEL_OPTION - A constant for creating a dialog with
“Yes,” “No,” and “Cancel” options.
 OK_CANCEL_OPTION - A constant for creating a dialog with “OK”
and “Cancel” options.
Sample of code
import javax.swing.*;
// Respond based on user's choice
import java.awt.event.ActionEvent;
if (response == JOptionPane.YES_OPTION) {
import java.awt.event.ActionListener;
JOptionPane.showMessageDialog(frame, "You chose YES!");
public class JOptionPaneWithButtonExample {
} else {
public static void main(String[] args) {
JOptionPane.showMessageDialog(frame, "You chose NO.");
// Create a JFrame (main window)
}
JFrame frame = new JFrame("JOptionPane with Button Example");
}
// Create a JButton
});
JButton button = new JButton("Click me for confirmation");
// Set up the JFrame layout
// Add ActionListener to the button
frame.setSize(300, 200); // Set the window size
button.addActionListener(new ActionListener() {
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); // Exit on
@Override close
public void actionPerformed(ActionEvent e) { frame.setLayout(null); // Set layout manager to null for absolute positioning
// Show a confirmation dialog when the button is clicked button.setBounds(50, 70, 200, 30); // Set button position and size
int response = JOptionPane.showConfirmDialog( frame.add(button); // Add button to frame
frame, // Parent component (the frame) // Make the frame visible
"Do you want to proceed?", // Message to display frame.setVisible(true);
"Confirmation", // Title of the dialog }
JOptionPane.YES_NO_OPTION, // Options (YES and }
NO)

JOptionPane.QUESTION_MESSAGE // Icon type


(Question icon)

);
Creating Menu Driven Java Application:
 JMenuBar

 It is used to display menubar on the window or frame. It may have several


menus.
 It is used to create the menu bar.
 Menu bar is created using the constructor JMenubar().
 For example, we may create a menu bar as follows.
JMenuBar jmb = new JMenuBar();
 Once a menu bar is created, the menu bar is going to be embedded onto the
container frame using the method setJMenuBar(JMenuBar mbr).
 JMenu:
 It is used to create menu or submenus. The constructor JMenu(String name) can be used to create a
menu/submenu.
For example, JMenu fileMenu = new JMenu(“File”).
Cont…
 Creating submenu under a menu: It is possible to have a menu under another menu,
that is, creating a submenu under a menu. First, the submenu will be created using the
JMenu constructor. Then, we will use the method add(JMenu menu) to add the
submenu under a menu. Let u observe the complete code of the following example and
notice how a submenu is added to a menu.
 The object of JMenu class is a pull down menu component which is displayed from the
menu bar
 Once menus are created using JMenu, these menus can be added onto the menu bar
using the function add(JMenu menu).
 JMenuItem
 This component is used to add menu items under menu components. The constructor
JMenuItem(String item) is used to create such items. Once the items are created the
method add(JMenuItem item) can be used to add the item to a menu component.
Sample of code
import java.awt.*;
import javax.swing.*; menu.add(item1);
public class Main { menu.add(item2);
public static void main(String args[]) {
menu.add(item3);
JMenu menu, submenu, edit, view, go, run;
JMenuItem item1, item2, item3, item4, item5; submenu.add(item4);
JFrame jframe = new JFrame("Menu and MenuItem example"); submenu.add(item5);
JMenuBar mb = new JMenuBar(); menu.add(submenu);
JLabel jlabel = new JLabel("Advanced Programming");
jlabel.setBounds(50, 100, 400, 100); mb.add(menu);
jlabel.setFont(new Font("Poppins", Font.PLAIN, 30)); mb.add(edit);
menu = new JMenu("File"); mb.add(view);
edit = new JMenu("Edit"); mb.add(go);
view = new JMenu("View"); mb.add(run);
go = new JMenu("Go"); jframe.add(jlabel);
run = new JMenu("Run"); jframe.setJMenuBar(mb);
submenu = new JMenu("Preferences"); jframe.setSize(800, 400);
item1 = new JMenuItem("New File ..."); jframe.setLayout(null);
item2 = new JMenuItem("Open Folder"); jframe.setVisible(true);
item3 = new JMenuItem("Save"); }
item4 = new JMenuItem("Profile"); };
item5 = new JMenuItem("Setting");
Layout Management
 LayoutManager is responsible for the components’ layout in GUI applications
 LayoutManager is an interface and it is implemented by all the layout manager classes.
The following are LayoutManager
1. FlowLayout
 The Simplest layout manager (the default one)Components are placed left to right in the
order in which they were added. When one row is filled, a new row is started.
 To arrange the components in a line, one after another.
 It has the following constructor
 FlowLayout(): creates a flow layout with centered alignment and a default 5 unit
horizontal and vertical gap.
 FlowLayout(int align) creates a flow layout with the given alignment and a default 5 unit
horizontal and vertical gap.
 FlowLayout(int align, int hgap, int vgap)creates a flow layout with the given alignment
and the given horizontal and vertical gap. The following are field of FlowLayout(LEFT,
RIGHT, CENTER, LEADING and TRAILING)
Sample of code
import java.awt.*;
import javax.swing.*;
public class
BorderLayoutDemo {
public stati c void main(String args[])
{ JFrame jframe = new JFrame(
Advanced Programming FlowLayout!"
);
JButton jbtn1 = new JButton("Button1");
JButton jbtn2 = new JButton("Button2");
JButton jbtn3 = new JButton("Button3");
JButton jbtn4 = new JButton("Button4");
JButton jbtn5 = new JButton("Button5");
JButton jbtn6 = new JButton("Button6");

jframe.setLayout(new FlowLayout());
jframe.setLayout(new
FlowLayout(FlowLayout.LEFT));
jframe.setLayout(new
FlowLayout(FlowLayout.RIGHT));
// jframe.setLayout(new
FlowLayout(FlowLayout.LEADING));
// jframe.setLayout(new
FlowLayout(FlowLayout.TRAILING));
// jframe.setLayout(new FlowLayout(FlowLayout.CENTER));
jframe.setLayout(new FlowLayout(FlowLayout.CENTER,
20, 20)); jframe.add(jbtn1);
jframe.add(jbtn2);
jframe.add(jbtn3);
jframe.add(jbtn4);
jframe.add(jbtn5);
jframe.add(jbtn6);
jframe.setSize(500, 500);
jframe.setVisible(true);
}
};
2. GridLayout
 The GridLayout manager divides the container up into a given number of rows
and columns. All sections of the grid are equally sized and as large as possible.
 GridLayout can be set using one of the constructors
 GridLayout(): creates a grid layout with one column per component in a row.
 GridLayout(int rows, int columns): creates a grid layout with the given rows and
columns but no gaps between the components
 GridLayout(int rows, int columns, int hgap, int vgap): creates a grid layout with
the given rows and columns along with given horizontal and vertical gaps.
Sample of code
import java.awt.*; import
javax.swing.*;
public class BorderLayoutDemo {
public stati c void main(String
args[ ] ) {

JFrame jframe = new JFrame(


"Advanced Programming
BorderLayout!"
);

JButton jbtn1 = new JButt on("Butt on1");


JButton jbtn2 = new JButt on("Butt on2");
JButton jbtn3 = new JButt on("Butt on3");
JButton jbtn4 = new JButt on("Butt on4");
JButton jbtn5 = new JButt on("Butt on5");
JButton jbtn6 = new JButt on("Butt on6");

jframe.setLayout(new GridLayout());
jframe.setLayout(new GridLayout(2,3));
jframe.setLayout(new GridLayout(3,2,20,20));

jframe.add(jbtn1);
jframe.add(jbtn2);
jframe.add(jbtn3);
jframe.add(jbtn4);
jframe.add(jbtn5);
jframe.add(jbtn6);

jframe.setSize(500, 500);
jframe.setVisible(true);

}
}
3. BorderLayout
 The BorderLayout manager divides the window into five areas: East, South, West,
North, and Center. At most five components can be added.
 It has two constructor
 BorderLayout():mcreates a border layout but with no gaps between the components.
 BorderLayout(int horizontalgap, int verticalgap): creates a border layout with the
given horizontal and vertical gaps between the components.
Sample of code
import java.awt.*; import
javax.swing.*;
public class
BorderLayoutDemo {
public stati c void
main(String args[]) {

JFrame jframe = new


JFrame("Advanced
Programming
BorderLayout!");
JButton jbtn1 = new
JButton("Region:NORTH"
);
JButton jbtn2 = new
JButton("Region:SOUTH")
;
JButton jbtn3 = new
JButton("Region:EAST");
JButton jbtn4 = new
JButton("Region:WEST");
JButton jbtn5 = new
JButton("Region:CENTER"
); jframe.setLayout(new
BorderLayout(20, 20));
jframe.add(jbtn1, BorderLayout.NORTH);
jframe.add(jbtn2, BorderLayout.SOUTH);
1.2. Event Handling
 Event Handling is the mechanism that controls the event then, decides
what should happen if an event occurs?
 Trigger during the user interact with GUI component. It occur
 when mouse hover, entered, exited
 Selection from CheckBox, RadioButton, ComboBox and other

Sample of code
JButton btn = new JButton(“Save”);
btn.addActionListener(new ActionListener())
public void actionperformed(ActionListener e){
system.out.print(“hellow”);
}
Cont…
Key Participants in event handling are
1. Source - an object that generates an event.
Occurs when an internal state of that object changes
in some way.
key in offering information about the event
occurred to handler
2. Listener - the event handler.
is an object that is notified when an event occurs.
is responsible for generating a response to an event .
Cont…
Event classes represent the event. Java provides various
Event classes
Event Class Description Listener
AWTEvent It is the root event class for all SWING events.
This class and its subclasses supercede the
original java.awt.Event class.
ActionEvent The ActionEvent is generated when the button ActionListener
is clicked or the item of a list is double-
clicked.
KeyEvent On entering the character the Key event is KeyListener
generated.
MouseEvent This event indicates a mouse action occurred in a MouseListener and
component. MouseMotionListener
WindowEvent The object of this class represents the change in WindowListener
the state of a window.
AdjustmentEvent The object of this class represents the AdjustmentListener
adjustment event emitted by Adjustable
objects.
ComponentEvent The object of this class represents the change in ComponentListener
the state of a window.
ContainerEvent The object of this class represents the change in ContainerListener
the state of a window.
PaintEvent The object of this class represents the change in PaintListener
the state of a window.
Reading assignment
The following are UI component

JList JSlider JRootPane


JScrollBar JDialog JEditorPane
JavaSpinner JSlider JScrollPane
JTextPane And so on
Lab Exercise
Check Password Confirmation?
Develop sign/in and signup form?
Develop simple calculator?
Develop notepad development
End of chapter
Any question ?

You might also like