Chapter 6
GUI and Event Driven Programming
Object Oriented Programming 5/13/2024
Introduction
2
Working with GUI is always a fascinating task to
the end users as well as interface designers.
GUI-based applications provide click and execute
environment that make applications more
entertaining and interesting.
Java allows programmers to create various
graphical components such as window, frame,
panel, button, text field, text area, radio button,
check box, drop down list, etc.
Object Oriented Programming 5/13/2024
Cont’
3
A graphical user interface (GUI) presents a user-
friendly mechanism for interacting with an
application.
A window is a container that holds other
components.
In GUI, terminology, a container that can be
displayed as a window is knows as a frame.
GUIs are built from GUI components.
These are sometimes called controls or widgets.
Object Oriented Programming 5/13/2024
Cont’
4
Components are graphic elements that can be
displayed on the screen and that can interact with
the user.
For example, buttons, labels,textfields, checkboxes,
radio buttons are all examples of components which are
represented by classes JButton, Jlabel, JTextField,
JCheckbox, JRadioButtons respectively.
Some components (such as buttons, labels) cannot
stand alone and require some other special
components to contain them.
These special components are called containers.
Examples of such containers are, window, panel,…
Object Oriented Programming 5/13/2024
Cont’
5
A Window container is a top-level display-surface
without any borders and menu bar.
However, a window itself cannot directly contain non-
container components such as buttons, textboxes etc.
It must contain either a frame, dialog, (or another window),
which can directly contain other components.
The Frame class is a sub-class of Window. A Frame
object is a special Window with border, title, the
content display area and an optional menu bar.
A Frame often provides the primary window for a GUI-based
application.
A GUI-based application typically creates an instance
of Jframe/Frame or any of its sub-class created
extending it.
Object Oriented Programming 5/13/2024
Cont’
6
A Dialog is a top-level window typically used as a
pop-up window and to take some form of input from
the user.
It comes with a border, a title-bar (containing an icon, a
title and a close button) and a content display area.
A panel (represented by JPanel/ Panel class) is a
higher-level container, which is a borderless
transparent rectangular box used to organize a set of
related components in pattern such as grid or flow.
A panel itself is not a visible component. It merely
provides some space where we can attach any other
components, including other panels.
Object Oriented Programming 5/13/2024
Creating container
7
Before creating and placing any component, we
must create a container.
Typically, we create an instance of JFrame/Frame
class.
What is the difference between:
JFrame and Frame?
JPanel and Panel?
JButton and Button?
JLabel and Label?
Ingeneral, JComponent and Component ?
Object Oriented Programming 5/13/2024
GUI-Based Input/Output with JOptionPane
8
Most applications you use on a daily life use windows or
dialog boxes/dialogs to interact with the user.
For example, an e-mail program allows you to type and read
messages in a window the program provides.
Dialog boxes are windows in which programs display
important messages to the user.
Java‟s JOptionPane class from package javax.swing
provides prebuilt dialog boxes for both input & output.
These are displayed by invoking static JOptionPane methods
Object Oriented Programming 5/13/2024
Cont’
9
Example: Simple addition application that uses two
input dialogs to obtain integers from the user and a
message dialog to display the sum of the integers the
user enters.
Object Oriented Programming 5/13/2024
The Source code
10
Object Oriented Programming 5/13/2024
Cont’
11
Though it‟s possible to perform input and output using
the JOptionPane dialogs, most GUI applications require
more elaborate user interfaces.
So, the remainder of this chapter discusses many GUI
components that enable application developers to create
robust GUIs.
Object Oriented Programming 5/13/2024
AWT vs Swing
12
When Java was introduced, the GUI classes were
bundled in a library known as the Abstract Windows
Toolkit (AWT).
AWT is fine for developing simple graphical user interfaces,
but not for developing comprehensive GUI projects.
Besides, AWT is prone to platform-specific bugs
because its peer-based approach relies heavily on the
underlying platform.
The AWT user-interface components were replaced by a
more robust, versatile, and flexible library known as
Swing components. Swing components are less
dependent on the target platform and use less of the
native GUI resource.
Object Oriented Programming 5/13/2024
Swing GUI Components
13
JCheckBoxMenuItem
JMenuItem JMenu
AbstractButton JButton JRadioButtonMenuItem
JToggleButton JCheckBox
JRadioButton
JComponent JEditorPane
JTextComponent JTextField JPasswordField
JTextArea
JLabel JList JComboBox JPanel JOptionPane JScrollBar JSlider
JTabbedPane JSplitPane JLayeredPane JSeparator JScrollPane JRootPane
JToolBar JMenuBar JPopupMenu JFileChooser JColorChooser JToolTip
JTree JTable JTableHeader JInternalFrame JProgressBar JSpinner
Object Oriented Programming 5/13/2024
AWT components
14
AWTEvent Container Panel Applet
Font Button Window Frame
FontMetrics Label Dialog FileDialog
TextField
Object Color TextComponent
TextArea
Graphics List
Component Choice
CheckBox
LayoutManager CheckBoxGroup
Canvas
MenuComponent MenuItem Menu
MenuBar
Scrollbar
Object Oriented Programming 5/13/2024
The Swing Class
15
In this course, we use the swing classes for all of the graphical
components that we create in our GUI from:
import javax.swing.*;
Example
import javax.swing.JFrame;
import javax.swing.JLabel;
We also use some AWT classes to determine fonts, layouts, events,
..from import java.awt.*;
Example
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Font;
import java.awt.event.*;
Object Oriented Programming 5/13/2024
Creating Frames
16
Frame is the basis to contain other user interface
components in Java GUI applications.
For Swing GUI programs, use JFrame class to create
Frame. Example-1: Empty Frame
Object Oriented Programming 5/13/2024
Cont’
17
Example-2: Titled Frame
Object Oriented Programming 5/13/2024
Cont’
18
Example-3: Optional(1)
Object Oriented Programming 5/13/2024
Cont’
19
Example-3: Optional(2)
Object Oriented Programming 5/13/2024
Adding Components to a Frame
20
Swing provides numerous GUI components that can be
added to a window. Some basic Swing GUI components are:
Jlabel: Displays uneditable text and/or icons.
JTextField: Typically receives input from the user.
Jbutton: Triggers an event when clicked with the mouse.
JCheckBox: Specifies an option that can be selected or not
JComboBox: A drop-down list of items from which the
user can make a selection.
Jlist: A list of items from which the user can make a
selection by clicking on any one of them.
Jpanel: An area in which components can be placed and
organized.
Object Oriented Programming 5/13/2024
Adding Components into a Frame…
21
// Add a Button into the urframe inside yourFrame method
frame.getContentPane().add(new JButton("OK"));
// Optional: use the following code Title Bar
Content Pane
Object Oriented Programming 5/13/2024
Adding more components into Frame…
22
// Add a Label into the urframe inside yourFrame
method and look at the output.
The constructor JLabel overrides Jbutton.
Object Oriented Programming 5/13/2024
Cont’
23
// Add a TextFiled into the urframe inside yourFrame
method and look at the output.
The constructor JTextField overrides Jbutton and JLabel.
How to solve such problem? How to solve such problem?
How to Solve such problems?
Object Oriented Programming 5/13/2024
Layout Managers
24
A Layout manger is an object that governs the
positions and size of components in a container.
Java‟s layout managers provide a level of
abstraction to automatically map your user interface
on all window systems.
The UI components are placed in containers.
Each container has a layout manager to arrange the UI
components within the container.
Layout managers are set in containers using the
setLayout(LayoutManager) method in a container.
Object Oriented Programming 5/13/2024
Cont’
25
Three common Layout Managers
FlowLayout
GridLayout
BorderLayout
To use any of this classes you should have the
following import statement:
import java.awt.*;
The layout manager & the container work together.
Object Oriented Programming 5/13/2024
FlowLayout
26
With the FlowLayout layout manager,
components are placed in a container from left to
right in the order in which they‟re added.
When no more components can fit on the current
line, they continue to display left to right on the next
line.
If the container is resized, a FlowLayout reflows the
components, possibly with fewer or more rows
based on the new container width.
Object Oriented Programming 5/13/2024
Cont’
27
You add a layout manager to a container, such as a
content pane or a panel by calling the setLayout
method and passing a reference to a layout object as
an argument.
Example
JPanel panel = new JPanel();
Panel.setLayout(new BorderLayout());
Once you establish a layout manager for a container , the
layout manager governs the position and size of the
component that are added to the container.
Object Oriented Programming 5/13/2024
FlowLayoutDemo.java
28
Object Oriented Programming 5/13/2024
GridLayout
29
The GridLayout layout manager divides the
container into a grid so that components can be
placed in rows and columns.
Every Component in a GridLayout has the same
width and height.
Components are added to a GridLayout starting at
the top-left cell of the grid and proceeding left to
right until the row is full.
Then the process continues left to right on the next
row of the grid, and so on.
Object Oriented Programming 5/13/2024
Example
30
Modify FlowLayoutDemo.java
Change f.setLayout(new FlowLayout());
By
1. f.setLayout(new GridLayout());
2. f.setLayout(new GridLayout(5,1));
3. f.setLayout(new GridLayout(1,5));
4. f.setLayout(new GridLayout(5,1,5,5));
Run and see the output for each line of code(1-4)
Object Oriented Programming 5/13/2024
Cont’
31
3
4
Object Oriented Programming 5/13/2024
BorderLayout
32
The BorderLayout Components are added to a
manager divides the BorderLayout by using the add
method. add(Component,
container into five
constraint),
regions:
where constraint is
East
South
• BorderLayout.EAST,
West • BorderLayout.SOUTH,
North • BorderLayout.WEST,
Center • BorderLayout.NORTH, or
• BorderLayout.CENTER.
Object Oriented Programming 5/13/2024
BorderLayoutDemo.java
33
Object Oriented Programming 5/13/2024
…
34
Object Oriented Programming 5/13/2024
Content Panes and Panels
35
A content pane is a container that is part of every JFrame
object.
You can not see the content pane and it does not have a
border, but any component that is to be displayed in a
JFrame must be added to its content pane.
A panel is also a container that can hold components, unlike
Jframe object they can not be displayed by themselves.
Panels are commonly used to hold and organize collections
of related components.
With swing, you create panels with JPanel class.
Object Oriented Programming 5/13/2024
Panel example 1
36
Create a panel to hold the label, text field and
button and then add the panel to the JFrames
object content pane.
TextFiled
Label Button
Object Oriented Programming 5/13/2024
currencyConverter.java
37
Object Oriented Programming 5/13/2024
Panel Example 2
38
Write a java program based on the following
requirements:
Create a frame with BoderLayout manager
The frame contains a text field at north and a panel at
center.
The panel also has a GridLayout manager and
contains 15 buttons:
The first 9 buttons are labeled 1 to 9
The 10th button is labeled by 0
The last 5 (11-15) buttons are labeled by +,-,*,/ and =
respectively
Object Oriented Programming 5/13/2024
PanelDemo.java
39
Object Oriented Programming 5/13/2024
…
40
Object Oriented Programming 5/13/2024
Borders
41
You can set a border on any object of the
JComponent class.
Swing has several types of borders. To create a titled
border, use
new TitledBorder(String title).
To create a line border, use new LineBorder(Color
color, int width), where width specifies the thickness
of the line.
For example, the following code displays a titled
border on a panel:
JPanel panel = new JPanel();
panel.setBorder(new TitleBorder(“My Panel”));
Object Oriented Programming 5/13/2024
Example
42
Add the following line of code on
currencyConverter.java
p.setBorder(new LineBorder(yellow,3));
Object Oriented Programming 5/13/2024
The Color Class
43
You can set colors for GUI components by using the
java.awt.Color class.
Colors are made of red, green, and blue components,
each of which is represented by a byte value that
describes its intensity, ranging from 0 (darkest
shade) to 255 (lightest shade).This is known as the
RGB model.
Color c = new Color(r, g, b);
Example: Color c = new Color(228, 100, 255);
Object Oriented Programming 5/13/2024
Standard Colors
44
13 standard colors (black, blue, cyan, darkGray, gray,
green, lightGray, magenta, orange, pink, red, white,
yellow) are defined as constants in java.awt.Color.
The standard color names are constants, but they are
named as variables with lowercase for the first word and
uppercase for the first letters of subsequent words. Thus
the color names violate the Java naming convention.
Since JDK 1.4, you can also use the new constants:
BLACK, BLUE, CYAN, DARK_GRAY, GRAY, GREEN,
LIGHT_GRAY, MAGENTA, ORANGE, PINK, RED,
WHITE, and YELLOW.
Object Oriented Programming 5/13/2024
Setting Colors
45
You can use the following methods to set the
component‟s background and foreground colors:
setBackground(Color c)
setForeground(Color c)
Example:
b1.setBackground(Color.yellow);
b2.setForeground(Color.red);
Object Oriented Programming 5/13/2024
Cont’
46
Add the following code on BorderLayoutDemo.java
Object Oriented Programming 5/13/2024
Cont’
47
Add the following line of code to BorderLayoutDemo.java
Object Oriented Programming 5/13/2024
Some user interface components-JButton
48
A button is a component that triggers an action event when
clicked.
Swing provides regular buttons, toggle buttons, check box
buttons, and radio buttons.
JButton inherits AbstractButton and provides several
constructors to create buttons.
Object Oriented Programming 5/13/2024
Cont’
49
JButton Properties:
JButton constructors: • text
• JButton() • icon
• JButton(String text) • mnemonic
• JButton(String text, Icon • horizontalAlignment
icon)
• verticalAlignment
• JButton(Icon icon)
• horizontalTextPosition
• verticalTextPosition
• iconTextGap
Object Oriented Programming 5/13/2024
ButtonsDemo.java
50
import java.awt.BorderLayout;
import java.awt.GridLayout;
import javax.swing.*;
public class ButtonDemo extends JFrame {
private final JButton[] buttons;
private final JRadioButton[] rb;
private final JCheckBox[] cb;
private final JPanel p1;
public ButtonDemo() {
super(" Button Demo");
buttons = new JButton[5];
rb = new JRadioButton[2];
cb = new JCheckBox[3];
p1 = new JPanel();
//p1.setLayout(new GridLayout(1, buttons.length));
p1.setLayout(new GridLayout(1, rb.length));
//p1.setLayout(new GridLayout(1, cb.length));
Object Oriented Programming 5/13/2024
…
51
// for (int count = 0; count < buttons.length; count++) {
// buttons[count] = new JButton("B " + (count + 1));
// p1.add(buttons[count]);
// add(p1, BorderLayout.NORTH); // add panel to JFrame
// }
for (int count = 0; count < rb.length; count++) {
rb[count] = new JRadioButton("RB " + (count + 1));
p1.add(rb[count]);
add(p1, BorderLayout.SOUTH); }// add panel to JFrame
//
// for (int count = 0; count < cb.length; count++) {
// cb[count] = new JCheckBox("CB " + (count + 1));
// p1.add(cb[count]);
// add(p1, BorderLayout.CENTER); // add panel to JFrame
// }
Object Oriented Programming
}} 5/13/2024
52
class test extends JFrame {
public static void main(String args[]) {
ButtonDemo demo = new ButtonDemo();
demo.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
demo.setSize(450, 200);
demo.setVisible(true);
}
}
Object Oriented Programming 5/13/2024
53
If you uncomment each part of the above commented code,
you will have the following:
Object Oriented Programming 5/13/2024
JLabel
54
A label is a display area for a short text, an image, or both.
JLabel inherits all the properties from JComponent and
has many properties similar to the ones in JButton, such
as:
text, icon, horizontalAlignment, verticalAlignment,
horizontalTextPosition, verticalTextPosition, and iconTextGap
Example
JLabel jlbl = new JLabel("Grapes", icon,
SwingConstants.CENTER);
// Set label's text alignment and gap between text and icon
jlbl.setHorizontalTextPosition(SwingConstants.CENTER);
jlbl.setVerticalTextPosition(SwingConstants.BOTTOM);
jlbl.setIconTextGap(5);
Object Oriented Programming 5/13/2024
JTextField
55
A text field is an input area where the user can type in
characters. Text fields are useful in that they enable the user
to enter in variable data (such as a name or a description).
Methods
getText(): Returns the string from the text field.
setText(String text): Puts the given string in the text field.
setEditable(boolean editable):Enables or disables the
text field to be edited. By default, editable is true.
setColumns(int):Sets the number of columns in this text field.
The length of the text field is changeable.
Object Oriented Programming 5/13/2024
Demo.java
56
import java.awt.*;
import javax.swing.*;
public class Demo {
public static void main(String[] args) {
JFrame frame = new JFrame("JLabel and JTextField");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(350, 250);
frame.setVisible(true);
JLabel nameLabel = new JLabel();
JLabel idLabel = new JLabel();
JTextField name= new JTextField(20);
JTextField id= new JTextField(20);
nameLabel.setText(" Your Name:");
nameLabel.setFont(new Font("Tahoma", 1, 18));
nameLabel.setForeground(new Color(51, 51, 255));
Object Oriented Programming 5/13/2024
…
57
idLabel.setText("Your ID:");
idLabel.setFont(new Font("Tahoma", 1, 18));
idLabel.setForeground(new Color(204, 0, 204));
JPanel p=new JPanel();
p.add(nameLabel);
p.add(name);
p.add(idLabel);
p.add(id);
frame.add(p);
}
}
Object Oriented Programming 5/13/2024
JTextArea
58
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, which enables the user to enter
multiple lines of text.
Object Oriented Programming 5/13/2024
TextArea Demo
59
Object Oriented Programming 5/13/2024
JPasswordField
60
The JPasswordField ass represents special text fields
(usually used to get passwords) where input
characters are suppressed for security reason.
Each character entered can be replaced by an echo
character.
Object Oriented Programming 5/13/2024
JPassWordDemo.java
61
Object Oriented Programming 5/13/2024
JTable
62
The JTable class lets us create a tabular grid of data.
It has many constructors and methods to customize
its rendering and editing. Fortunately, it provides
defaults for these features so that simple tables can
be set up easily.
For example, the following program creates a table of 4
rows and 3 columns.
Object Oriented Programming 5/13/2024
JTabelDemo.java
63
value, row, col
Object Oriented Programming 5/13/2024
JComboBox
64
A JComboBox object represents a pop-up menu of
items, one of which may be chosen at any time.
The current choice is displayed as the title of the
menu.
Clicking on the choice causes a menu to appear with
the current choice highlighted.
To add an item to a JComboBox jcbo, use
jcbo.addItem(Object item)
To get an item from JComboBox jcbo, use
jcbo.getItem()
Object Oriented Programming 5/13/2024
JcomboBoxDemo.java
65
Object Oriented Programming 5/13/2024
JCheckBox
66
A Checkbox object can be in either of the two states:
“on” (true) or “off” (false).
It has a small rectangular area which remains empty
for “off” state and shows a small tick mark (√) for
“on” state.
Clicking on a check box toggles its state.
The following program creates four check boxes in a
gridlayout.
Object Oriented Programming 5/13/2024
checkBoxDemo.java
67
Object Oriented Programming 5/13/2024
JMenuBar Demo
68
Object Oriented Programming 5/13/2024
Creating Multiple Windows
69
Object Oriented Programming 5/13/2024
70
Event Handling in java
Object Oriented Programming 5/13/2024
Introduction
71
A user interacts with an application‟s GUI to indicate the
tasks that the application should perform.
For example, when you write an e-mail in an e-mail application,
clicking the Send button tells the application to send the e-mail
to the specified e-mail addresses.
GUIs are event driven. When the user interacts with a
GUI component, the interaction is known as an event.
Drives the program to perform a task.
Some common user interactions that cause an
application to perform a task include clicking a button,
typing in a text field, selecting an item from a menu,
closing a window and moving the mouse.
Object Oriented Programming 5/13/2024
Cont’
72
The code that performs a task in response to an event
is called an event handler, and the process of
responding to events is known as event handling.
Event handling is fundamental to Java programming because it is
used to create event driven programs.
Example
GUI based windows application
Web Application
Applets
Object Oriented Programming 5/13/2024
Cont’
73
Event model is based on the three components:
Event, Event Source and Event Listener
An event is a change in the state of an object
It describes the change in state of source.
Events are generated as result of user interaction
with the graphical user interface components.
Example
Clicking on a button, moving the mouse, entering a
character through keyboard, selecting an item from
list..etc.
With event-driven programming, events are detected
by a program and handled appropriately.
Object Oriented Programming 5/13/2024
Cont’
74
An event source is an object that causes and
generates an event.
It generates an event when the internal state of the
object is changed.
The sources are allowed to generate several types of
events.
A source must register a listener to receive
notifications for a specific event.
Each event contains its registration method
Object Oriented Programming 5/13/2024
Cont’
75
Examples of Sources:
buttons, checkboxes, list, menu-item, choice, scrollbar,
text components, windows, etc., to generate events.
Listeners: Listeners are used for handling the
events generated from the source.
Each of these listeners represents interfaces that are
responsible for handling events.
To perform Event Handling, we need to register the
source with the listener.
Object Oriented Programming 5/13/2024
Cont’
76
Some Event Source and their description
Button: Generates action events when the button is
pressed.
Check box: Generates item events when the check box
is selected or deselected.
Menu: item Generates action events when a menu item
is selected; generates item events when a checkable menu
item is selected or deselected.
Scroll bar: Generates adjustment events when the scroll
bar is manipulated.
Text components Generates text events when the user
enters a character.
Window Generates window events when a window is
Object Oriented Programming 5/13/2024
77
What will happen when the event occurs?
In event handling, there should be also a response.
Response example:
Print out the message
Opening new window
Play sound
Display image
Registering the Source With Listener
Different Classes provide different registration methods.
Syntax: addTypeListener()
where Type represents the type of event.
Object Oriented Programming 5/13/2024
Event types
78
Foreground Events
Events which require the direct interaction of user. They
are generated as consequences of a person interacting
with the graphical components in GUI.
For example, clicking on a button, moving the mouse, entering
a character through keyboard, selecting an item from list,
scrolling the page etc.
Background Events
Events that require the interaction of end user are
known as background events.
Operating system interrupts, hardware or software failure,
timer expires, an operation completion are the example of
background events.
Object Oriented Programming 5/13/2024
Event Handling Steps
79
1 Prepare to accept events - import package
java.awt.event
2 Start listening for events - include appropriate
methods
3 Respond to events - implement appropriate abstract
method
The methods that receive and process events are
defined in a set of interfaces, such as those found in
java.awt.event package.
Object Oriented Programming 5/13/2024
80
The common interface that all event listener interfaces
must extend is EventListener.
For example, to listen for ActionEvents the class must
implement the interface ActionListener, that in turn is an
implementation of EventListener.
Three important parts to handle events:
public class MyClass implements ActionListener
someComponent.addActionListener(aMyClass)
public void actionPerformed(ActionEvent e){}
Object Oriented Programming 5/13/2024
Demo1
81
Object Oriented Programming 5/13/2024
What is the output?
82
Before Button click
After Button click
Object Oriented Programming 5/13/2024
Explanation
83
First extend the class with JFrame and implement the
respective listener(Line #5)
Create Text-Field and Button components(L#8&9)
Registered the button component with respective event. i.e.
ActionEvent by addActionListener()(Line #11)
In the end, implement the abstract method(Line #18)
Object Oriented Programming 5/13/2024
Demo2
84
Object Oriented Programming 5/13/2024
…
85
Before Button click
After Button click
Object Oriented Programming 5/13/2024
AddtionDemo.java
86
Object Oriented Programming 5/13/2024
87
Object Oriented Programming 5/13/2024
CurrencyConvertor.java
88
public class CurrencyConverter extends JFrame implements
ActionListener {
private JPanel p;
private JLabel messageLabel, label;
private JTextField currencyTextField;
private JButton calcButton;
CurrencyConverter() {
setTitle("ETB->USD Converter");
setSize(400, 300);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
myPanel();
add(p); // add the panel to the frame's content pane.
setVisible(true);
}
Object Oriented Programming 5/13/2024
…
89
private void myPanel() {
label = new JLabel("Enter currency in ETB");
messageLabel = new JLabel();
messageLabel.setForeground(Color.blue);
messageLabel.setFont(new Font("Thahoma", 1, 26));
currencyTextField = new JTextField(10);
calcButton = new JButton("Convert");
calcButton.addActionListener(this);
p = new JPanel();
p.add(label);
p.add(currencyTextField);
p.add(calcButton);
p.add(messageLabel);
p.setBorder(new LineBorder(RED, 3));
}
Object Oriented Programming 5/13/2024
…
90
public void actionPerformed(ActionEvent e) {
final double rate = 0.019;
String inputETB;
double outputUSD;
inputETB = currencyTextField.getText();
outputUSD = Double.parseDouble(inputETB) * rate;
messageLabel.setText(outputUSD + "");
}
public static void main(String[] args) {
new CurrencyConverter();
}
}
Object Oriented Programming 5/13/2024
…
91
Object Oriented Programming 5/13/2024
Login.java
92
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class Login extends JFrame{
private static JLabel passlabel, userlabel,correct,err;
private static JTextField usernametxt;
private static JButton button;
private static JPasswordField passwordtxt;
private static JPanel panel;
public Login() {
panel = new JPanel();
userlabel = new JLabel(" Enter Username");
passlabel = new JLabel(" Enter Password");
err=new JLabel();
err.setForeground(Color.RED);
err.setFont(new Font("Thahoma",1,20) );
correct=new JLabel();
Object Oriented Programming 5/13/2024
…
93
correct.setForeground(Color.BLUE);
correct.setFont(new Font("Thahoma",1,20));
usernametxt = new JTextField(15);
passwordtxt = new JPasswordField(15);
button = new JButton("Login");
button.setForeground(Color.WHITE);
button.setBackground(Color.BLUE);
panel.add(userlabel);
panel.add(usernametxt);
panel.add(passlabel);
panel.add(passwordtxt);
panel.add(button);
panel.add(correct);
panel.add(err);
Object Oriented Programming 5/13/2024
…
94
button.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
String Username = usernametxt.getText();
String Password1 = passwordtxt.getText();
if (Username.equals("admin") && Password1.equals("123")) {
correct.setText("Login Successful");
} else {
err.setText("Username or Password mismatch ");
} }});
setTitle("Login Page");
setSize(400, 300);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
add(panel);
setVisible(true); }
Object Oriented Programming 5/13/2024
…
95
public static void main(String[] args) {
new Login(); }
What if Username=admin and Password=123 ?
What if Username=admins and Password= any random input ?
Object Oriented Programming 5/13/2024
96
Let‟s modify the login page by adding another button „Sign up”
like the following:
Activity
• Assume a user has no account. A new user want to create an account by clicking
the Sign up button. To do so, the Sign up page should be linked with the login
page. Develop this page and link with the login page.
• First Name, Last Name and email are additional attributes for the page
Object Oriented Programming 5/13/2024
Signup.java
97
public class Signup extends JFrame {
private static JLabel passlabel, userlabel, fnamelabel, lnamelabel,
emaillabel, validator, err;
private static JTextField usernametxt, fnametxt, lnametxt, emailtxt;
private static JPasswordField passwordtxt;
private static JButton signup;
private static JPanel panel;
Signup() {
panel = new JPanel();
fnamelabel = new JLabel(" Enter First Name");
lnamelabel = new JLabel(" Enter Last Name");
emaillabel = new JLabel(" Enter Email ");
userlabel = new JLabel(" Enter Username");
passlabel = new JLabel(" Enter Password");
Object Oriented Programming 5/13/2024
98
err = new JLabel();
err.setForeground(Color.red);
err.setFont(new Font("Thahoma", 1, 20));
validator = new JLabel();
validator.setForeground(Color.BLUE);
validator.setFont(new Font("Thahoma", 1, 20));
fnametxt = new JTextField(15);
lnametxt = new JTextField(15);
emailtxt = new JTextField(15);
usernametxt = new JTextField(15);
passwordtxt = new JPasswordField(15);
signup = new JButton("Sign up");
signup.setForeground(Color.white);
signup.setBackground(Color.BLUE);
Object Oriented Programming 5/13/2024
99
panel.add(fnamelabel);
panel.add(fnametxt);
panel.add(lnamelabel);
panel.add(lnametxt);
panel.add(emaillabel);
panel.add(emailtxt);
panel.add(userlabel);
panel.add(usernametxt);
panel.add(passlabel);
panel.add(passwordtxt);
panel.add(signup);
panel.add(validator);
panel.add(err);
Object Oriented Programming 5/13/2024
100
signup.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
String fname = fnametxt.getText();
String lname = lnametxt.getText();
String email = emailtxt.getText();
String Username = usernametxt.getText();
String PW = passwordtxt.getText();
if (fname.equals("") || lname.equals("")) {
if (email.equals("") || Username.equals("")) {
if (PW.equals("")) {
err.setText("fill all required data ");
}}
} else {
validator.setText("sign up Successfully");
} });
Object Oriented Programming 5/13/2024
101
setTitle(“Sign Up Page");
setSize(500, 400);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
//panel.setLayout(null);
add(panel);
setVisible(true);
}
public static void main(String[] args) {
new Signup();
}
Object Oriented Programming 5/13/2024
102
Object Oriented Programming 5/13/2024
103
Now add the following code some where in the Login class‟s
constructor.
• If you click Sign up button from the Login Page , the Sign up page will open
automatically.
Object Oriented Programming 5/13/2024
Drag and Drop approach to design GUI
104
Drag and Drop is the mechanism to transfer data to
an application. This approach allows you to transfer
data by dragging a component(the drag source) and
drop it on to another component(drop target).
Java Palette provide us user-friendly and quick
access to commonly used components available for
drag and dropping to forms.
Under this palette, there are different swing groups:
Containers, Controls, Menus and windows (revise the
introductory part of this chapter)
You can use AWT as needed.
Object Oriented Programming 5/13/2024
Cont’
105
Object Oriented Programming 5/13/2024