KEMBAR78
Chap3 Guiandeventdrivenprogramming | PDF | Graphical User Interfaces | System Software
0% found this document useful (0 votes)
33 views97 pages

Chap3 Guiandeventdrivenprogramming

Chapter 3 discusses Graphical User Interface (GUI) and event-driven programming in Java, focusing on the Java API for GUI, including AWT, Swing, and JavaFX. It outlines the main elements of GUI applications, such as containers, components, events, and listeners, and provides examples of creating user interfaces using JFrame and JPanel. The chapter also covers various Swing components like JButton, JLabel, and JTextField, detailing their constructors and common methods.

Uploaded by

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

Chap3 Guiandeventdrivenprogramming

Chapter 3 discusses Graphical User Interface (GUI) and event-driven programming in Java, focusing on the Java API for GUI, including AWT, Swing, and JavaFX. It outlines the main elements of GUI applications, such as containers, components, events, and listeners, and provides examples of creating user interfaces using JFrame and JPanel. The chapter also covers various Swing components like JButton, JLabel, and JTextField, detailing their constructors and common methods.

Uploaded by

Mukesh Periasamy
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 97

Chapter 3

(Part 1)

Graphical User Interface


&
Event-Driven Programming
GUI & event-driven programming
Topics covered for this lesson:

✓ Java API for GUI


✓ Swing vs AWT
✓ Elements of GUI Applications
✓ User interfaces using frames,
panels, and simple GUI
components
Java API for GUI
The Java API (Application Program Interface, Application
Programming Interface, or Application Programmer interface)
consists of numerous classes and interfaces grouped into more than
a dozen of packages
There are currently three sets of Java APIs for GUI programming: AWT
(Abstract Windowing Toolkit), Swing and JavaFX:

1. AWT API was introduced in JDK 1.0. Most of the AWT components have
become obsolete and should be replaced by newer Swing components.

2.
Swing API, a much more comprehensive set of graphics libraries that
enhances the AWT, was introduced as part of Java Foundation Classes
(JFC) after the release of JDK 1.1. JFC consists of Swing, Java2D,
Accessibility, Internationalization, and Pluggable Look-and-Feel Support
APIs. JFC has been integrated into core Java since JDK 1.2.

3. JavaFX, which was integrated into JDK 8, is Java API for desktop
applications, and rich web applications that can run across a wide
variety of devices.
Java API for GUI

Swing vs. AWT

• Java 1.0 was introduced with a class library called


Abstract Window Toolkit (AWT)
• used for basic user interface
• delegated creation and behavior of interface elements to the
native GUI tookit on the target platform
• Example: Windows vs. Solaris vs. Macintosh, etc..

• Downside of AWT:
• Worked well for simple applications but difficult to write high-
quality portable graphics
• Different platforms had different bugs
Java API for GUI

Swing vs. AWT


• In 1996 Sun worked with Netscape to create Swing
• In Swing user interface elements are painted onto blank
windows
• Swing is not a complete replacement of AWT. Instead it works
with AWT.
• Swing simply gives you more capable user interface
components.
• However, even though AWT components are still available, you
will rarely use them.
Java API for GUI
Swing
• Reasons to choose Swing:
• much richer and more convenient set of user interface
elements
• depends far less on the underlying platform so it is less
vulnerable to platform-specific bugs
• gives a consistent user experience across platforms
• Easier to use than AWT.
Java GUI API hierarchy
Elements of GUI applications
Elements of GUI applications

GUI gives an application a distinctive “look-and-feel.”

3 Main elements of GUI applications:


1. GUI Container and Component
2. Event
3. Listener
Elements of GUI applications
1. GUI Container and Components
• An object that defines a screen
element to display information or
allow the user to interact with
program in a certain way

• Example of GUI Container include


frame and panel
• Example of GUI Components include
push buttons, text fields, labels,
scroll, bars and menus
Elements of GUI applications

2. Event
• Object that represents some occurrence in
which we may be interested
• Event correspond to user actions, such as
pressing a mouse button or typing a key on the
keyboard
• Most GUI components generate events to
indicate a user action related to that
component
• For example, a component representing a
button will generate an event to indicate that
it has been pushed
Elements of GUI applications

3. Listener
• An object that is “waiting” for an event to
occur and that can respond in some way
when it does

• The programmer must carefully establish


the relationship among the listener, the
event it listens for and the component
that will generate the event
Elements of GUI applications
Containers and Components

1. Component: Components are elementary GUI entities,


such as Button, Label, and TextField.

2. Container: Containers, such as Frame and Panel, are


used to hold components in a specific layout (such
as FlowLayout or GridLayout). A container can also hold
sub-containers.
Elements of GUI applications
Containers and Components

(Sub-container/
inner container)

• In a GUI program, a component must be kept in a


container.
• You need to identify a container to hold the components.
• Every container has a method called
add(Component_object).
Elements of GUI applications

Java Swing Containers

• A special type of component that is used to hold


and organize other components.
• 2 main types of Sing Containers:
1. Frames (JFrame)
2. Panels (JPanel)
Elements of GUI applications

Swing Containers & Components


3 Basic Steps to Create GUI

Creating GUI:
1. Define and set up GUI components.

2. Create listener objects and establish the


relationship between the listeners and the
components which generate the events of
interest

3. Define event by activating GUI components


Swing Container
- JFrame -
User interfaces using frames
Frame

• A frame is a base window on which other


components rely, such as menu bar, panels,
labels, text fields, buttons, etc..
• Almost every Swing application starts with
JFrame window.
• JFrame is a Swing’s top-level container that
renders a window on screen.
User interfaces using frames
Frame
JFrame Class These are methods available in Jframe class.

javax.swing.JFrame
+JFrame() Creates a default frame with no title.
+JFrame(title: String) Creates a frame with the specified title.
+setSize(width: int, height: int): void Specifies the size of the frame.
+setLocation(x: int, y: int): void Specifies the upper-left corner location of the frame.
+setVisible(visible: boolean): void Sets true to display the frame.
+setDefaultCloseOperation(mode: int): void Specifies the operation when the frame is closed.
+setLocationRelativeTo(c: Component): Sets the location of the frame relative to the specified component.
void If the component is null, the frame is centered on the screen.
+pack(): void Automatically sets the frame size to hold the components in the
frame.
User interfaces using frames
Frame
Creating a JFrame window

import javax.swing.*;

public class DemojFrame {


public static void main(String[] args) {
JFrame frame = new JFrame("Jframe Window");
frame.setSize(400, 300);
frame.setVisible(true);
frame.setDefaultCloseOperation(
JFrame.EXIT_ON_CLOSE);
}
}
User interfaces using frames
Using Panels as Sub-Containers
• Panels act as sub-containers for grouping user
interface components.

• It is recommended that you place the user


interface components in panels and place the
panels in a frame. You can also place panels in a
panel.

• To add a component to JFrame, you actually add


it to the content pane of JFrame. To add a
component to a panel, you add it directly to the
panel using the add method.
Using Panels as Sub-Containers
JPanel
The JPanel is a partitioning container class.
It provides space in which an application can attach any other
component.
It inherits the JComponents class.
Example:
frame
A textfield
p2
A button 12
buttons p1
How to use JFrame?

1. Association
2. Association Inside Constructor
3. Inheritance
Java Swing: JFrame
Swing Example: 1. Association
import javax.swing.*;

public class SwingAssociation {


public static void main(String[] args) {
JFrame f= new JFrame();

f.setSize(400,500);
f.setLayout(null);
f.setVisible(true);
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
}
Java Swing: JFrame
Swing Example:
2. Association Inside Constructor
import javax.swing.*;

public class SwingInConstructor {


private JFrame f;
SwingInConstructor(){
f = new JFrame();

f.setSize(400,500);
f.setLayout(null);
f.setVisible(true);
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}

public static void main(String[] args) {


new SwingInConstructor();
}
}
Java Swing: JFrame
Swing Example:
3. Inheritance
import javax.swing.*;

public class SwingByInheritance extends JFrame{

SwingByInheritance(){
setSize(400,500);
setLayout(null);
setVisible(true);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}

public static void main(String[] args) {


new SwingByInheritance();
}
}
Swing Components
GUI & event-driven programming
Overview of Swing components
Basic Swing GUI components
Common Features of Swing Components
The get and set methods for these data fields are provided in
the class, but omitted in the UML diagram for brevity.
java.awt.Component
-font: java.awt.Font The font of this component.
-background: java.awt.Color The background color of this component.
-foreground: java.awt.Color The foreground color of this component.
-preferredSize: Dimension The preferred size of this component.
-visible: boolean Indicates whether this component is visible.
+getWidth(): int Returns the width of this component.
+getHeight(): int Returns the height of this component.
+getX(): int getX() and getY() return the coordinate of the component’s
+getY(): int upper-left corner within its parent component.

java.awt.Container
+add(comp: Component): Component Adds a component to the container.
+add(comp: Component, index: int): Component Adds a component to the container with the specified index.
+remove(comp: Component): void Removes the component from the container.
+getLayout(): LayoutManager Returns the layout manager for this container.
+setLayout(l: LayoutManager): void Sets the layout manager for this container.
+paintComponents(g: Graphics): void Paints each of the components in this container.

The get and set methods for these data fields are provided in
the class, but omitted in the UML diagram for brevity.
javax.swing.JComponent
-toolTipText: String The tool tip text for this component. Tool tip text is displayed when
the mouse points on the component without clicking.
-border: javax.swing.border.Border The border for this component.
Creating GUI
Objects
Components

// Create a button with text OK


JButton jbtOK = new JButton("OK");

// Create a label with text "Enter your name: "


JLabel jlblName = new JLabel("Enter your name: ");

// Create a text field with text "Type Name Here"


JTextField jtfName = new JTextField("Type Name Here");

// Create a check box with text bold


JCheckBox jchkBold = new JCheckBox("Bold");

// Create a radio button with text red


JRadioButton jrbRed = new JRadioButton("Red");

// Create a combo box with choices red, green, and blue


JComboBox jcboColor = new JComboBox(new String[]{"Red",
"Green", "Blue"});
Overview of Swing components
Button
A button is a component that triggers an action event when clicked.
Swing provides regular buttons, toggle buttons, check box
buttons, and radio buttons

The common features of these buttons are generalized in


javax.swing.AbstractButton
GUI & event-driven programming

Swing component: JButton


The JButton class is used to create a labeled
button that has platform independent
implementation.

The following are JButton constructors:


Constructor Description
JButton() It creates a button with no text and icon.

JButton(String s) It creates a button with the specified text.

JButton(Icon i) It creates a button with the specified icon object.


GUI & event-driven programming

Swing component: JButton


JButton inherits AbstractButton class.

The following are Commonly used Methods of AbstractButton


class
Methods Description
void setText(String s) It is used to set specified text on button.
String getText() It is used to return the text of the button.
void setEnabled(boolean b) It is used to enable or disable the button.
void setIcon(Icon b) It is used to set the specified Icon on the button
Icon getIcon() It is used to get the Icon of the button
void setMnemonic(int a) It is used to set the mnemonic on the button
GUI & event-driven programming
Swing component: JButton
Example:

import javax.swing.*;
public class JButtonExample {
public static void main(String[] args) {
JFrame f = new JFrame("JButton 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);
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
}
GUI & event-driven programming

Swing component: JLabel


The object of JLabel class is a component for placing text in
a container.
It is used to display a single line of read only text.
The text can be changed by an application but a user
cannot edit it directly.

The following are JLabel constructors:


Constructor Description
JLabel() Creates a JLabel instance with no content.

JLabel(String s) Creates a JLabel instance with the specified text.

JLabel(Icon i) Creates a JLabel instance with the specified image.

JLabel(String s, Icon i, Creates a JLabel instance with the specified text, image,
int horizontalAlignment) and horizontal alignment.
GUI & event-driven programming

Swing component: JLabel


JLabel inherits JComponent class.

The following are Commonly used Methods of JComponent class

Methods Description
String getText() It returns the text string that a label
displays.
void setText(String text) It defines the single line of text this
component will display.
void setHorizontalAlignment(int It sets the alignment of the label's contents
alignment) along the X axis.
Icon getIcon() It returns the graphic image that the label
displays
int getHorizontalAlignment() It returns the alignment of the label's
contents along the X axis
GUI & event-driven programming
Swing component: JLabel
Example:
import javax.swing.*;
class LabelExample {
public static void main(String args[]) {

JFrame f= new JFrame(“JLabel Example");

JLabel l1,l2;
l1 = new JLabel("First Label.");
l1.setBounds(50,50, 100,30);
l2 = new JLabel("Second Label.");
l2.setBounds(50,100, 100,30);

f.add(l1);
f.add(l2);

f.setSize(300,300);
f.setLayout(null);
f.setVisible(true);
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
}
GUI & event-driven programming

Swing component: JTextField


The object of a JTextField class is a text component that
allows the editing of a single line text.

The following are JTextField constructors:


Constructor Description
JTextField() Creates a new TextField.

JTextField(String text) Creates a new TextField initialized with the


specified text.
JTextField(String text, int Creates a new TextField initialized with the
columns) specified text and columns.
JTextField(int columns) Creates a new empty TextField with the specified
number of columns.
GUI & event-driven programming

Swing component: JTextField


JTextField inherits JTextComponent class.

The following are Commonly used Methods of JTextComponent


class
Methods Description
void addActionListener It is used to add the specified action
(ActionListener l) listener to receive action events from
this textfield.
Action getAction() It returns the currently set Action for this
ActionEvent source, or null if no Action is
set.
void setFont(Font f) It is used to set the current font.
void removeActionListener It is used to remove the specified action
(ActionListener l) listener so that it no longer receives
action events from this textfield
GUI & event-driven programming
Swing component: JTextField
Example:
import javax.swing.*;

class TextFieldExample {
public static void main(String args[]) {
JFrame f = new JFrame("JTextField Example");

JTextField t1,t2;
t1 = new JTextField("Insert Your name here.");
t1.setBounds(50,100, 200,30);
t2 = new JTextField("Enter your address here");
t2.setBounds(50,150, 200,30);
f.add(t1); f.add(t2);
f.setSize(400,400);
f.setLayout(null);
f.setVisible(true);
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
}
GUI & event-driven programming

Swing component: JTextArea


The object of a JTextArea class is a multi line region that
displays text. It allows the editing of multiple line text.

The following are JTextArea constructors:


Constructor Description
JTextArea() Creates a text area that displays no text initially.

JTextArea(String s) Creates a text area that displays specified text initially.

JTextArea(int row, int Creates a text area with the specified number of rows and
column) columns that displays no text initially.
JTextArea(String s, int Creates a text area with the specified number of rows and
row, int column) columns that displays specified text.
GUI & event-driven programming

Swing component: JTextArea


JTextArea inherits JTextComponent class.

The following are Commonly used Methods of JTextComponent


class
Methods Description
void setRows(int rows) It is used to set specified number of rows.

void setColumns(int cols) It is used to set specified number of columns.

void setFont(Font f) It is used to set the specified font.

void insert(String s, int It is used to insert the specified text on the specified
position) position.
void append(String s) It is used to append the given text to the end of the
document.
GUI & event-driven programming
Swing component: JTextArea
Example:
import javax.swing.*;

public class TextAreaExample{


TextAreaExample(){
JFrame f= new JFrame();
JTextArea area = new JTextArea("Your text will appear here");
area.setBounds(10,30, 200,200);
f.add(area);
f.setSize(300,300);
f.setLayout(null);
f.setVisible(true);
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}

public static void main(String args[]){


new TextAreaExample();
}
}
GUI & event-driven programming

Swing component: JPasswordField


The object of a JPasswordField class is a text component
specialized for password entry.
It allows the editing of a single line of text.

The following are JPasswordField constructors:


Constructor Description
JPasswordField() Constructs a new JPasswordField, with null starting
text string, and 0 column width.
JPasswordField(int columns) Constructs a new empty JPasswordField with the
specified number of columns.
JPasswordField(String text) Constructs a new JPasswordField initialized with
the specified text.
JPasswordField(String text, Construct a new JPasswordField initialized with the
int columns) specified text and columns.
GUI & event-driven programming
Swing component: JPasswordField
Example:

import javax.swing.*;

public class PasswordFieldExample {


public static void main(String[] args) {
JFrame f = new JFrame("JPasswordField Example");
JPasswordField value = new JPasswordField();
JLabel lb1 = new JLabel("Password:");
lb1.setBounds(20,100, 80,30);
value.setBounds(100,100,100,30);
f.add(value); f.add(lb1);
f.setSize(300,300);
f.setLayout(null);
f.setVisible(true);
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
}
GUI & event-driven programming

Swing component: JCheckBox


The JCheckBox class is used to create a checkbox.
It is used to turn an option on (true) or off (false).
Clicking on a CheckBox changes its state from "on" to "off"
or from "off" to "on ".

The following are JCheckBox constructors:


Constructor Description
JJCheckBox() Creates an initially unselected check box button
with no text, no icon.
JChechBox(String s) Creates an initially unselected check box with text.

JCheckBox(String text, Creates a check box with text and specifies


boolean selected) whether or not it is initially selected.
JCheckBox(Action a) Creates a check box where properties are taken
from the Action supplied.
GUI & event-driven programming

Swing component: JCheckBox


JCheckBox inherits JToggleButton class.

The following are Commonly used Methods of JToggleButton


class
Methods Description
AccessibleContext It is used to get the AccessibleContext
getAccessibleContext() associated with this JCheckBox.
protected String It returns a string representation of this
paramString() JCheckBox.
GUI & event-driven programming
Swing component: JCheckBox
Example:

import javax.swing.*;

public class CheckBoxExample {


CheckBoxExample(){
JFrame f= new JFrame(“JCheckBox Example");
JCheckBox checkBox1 = new JCheckBox("C++");
checkBox1.setBounds(100,100, 50,50);
JCheckBox checkBox2 = new JCheckBox("Java", true);
checkBox2.setBounds(100,150, 100,50);
f.add(checkBox1);
f.add(checkBox2);
f.setSize(400,400);
f.setLayout(null);
f.setVisible(true);
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}

public static void main(String args[]) {


new CheckBoxExample();
}
}
GUI & event-driven programming

Swing component: JRadioButton


The JRadioButton class is used to create a radio button.
It is used to choose one option from multiple options.
It should be added in ButtonGroup to select one radio
button only.

The following are JRadioButton constructors:


Constructor Description
JRadioButton() Creates an unselected radio button with no text.

JRadioButton(String s) Creates an unselected radio button with specified


text.
JRadioButton(String s, Creates a radio button with the specified text and
boolean selected) selected status.
GUI & event-driven programming

Swing component: JRadioButton


JRadioButton inherits JToggleButton class.

The following are Commonly used Methods of JToggleButton


class
Methods Description
void setText(String s) It is used to set specified text on button.
String getText() It is used to return the text of the button.
void setEnabled(boolean b) It is used to enable or disable the button.
void setIcon(Icon b) It is used to set the specified Icon on the button
Icon getIcon() It is used to get the Icon of the button.
void setMnemonic(int a) It is used to set the mnemonic on the button.
void addActionListener It is used to add the action listener to this
(ActionListener a) object.
GUI & event-driven programming
Swing component: JRadioButton
Example:
import javax.swing.*;

public class RadioButtonExample {


JFrame f;
RadioButtonExample(){
f = new JFrame();
JRadioButton r1= new JRadioButton("Male");
JRadioButton r2= new JRadioButton("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);
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}

public static void main(String[] args) {


new RadioButtonExample();
}
}
GUI & event-driven programming

Swing component: 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 following are JComboBox constructors:


Constructor Description
JComboBox() Creates a JComboBox with a default data model.

JComboBox(Object[] items) Creates a JComboBox that contains the elements


in the specified array.
JComboBox(Vector<?> items) Creates a JComboBox that contains the elements
in the specified Vector.
GUI & event-driven programming

Swing component: JComboBox


JComboBox inherits JComponent class.

The following are Commonly used Methods of JComponent class

Methods Description
void addItem(Object It is used to add an item to the item list.
anObject)
void removeItem(Object It is used to delete an item to the item list
anObject)
void removeAllItems() It is used to remove all the items from the list.
void setEditable(boolean b) It is used to determine whether the JComboBox
is editable.
void addActionListener It is used to add the ActionListener.
(ActionListener a)
void addItemListener It is used to add the ItemListener.
(ItemListener i)
GUI & event-driven programming
Swing component: JComboBox
Example:

import javax.swing.*;

public class ComboBoxExample {


JFrame f;
ComboBoxExample(){
f= new JFrame("JComboBox Example");
String country[]={"Malaysia","Singapore","Thailand","Indonesia"};
JComboBox cb= new JComboBox(country);
cb.setBounds(50, 50,90,20);
f.add(cb);
f.setLayout(null);
f.setSize(400,500);
f.setVisible(true);
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}

public static void main(String[] args) {


new ComboBoxExample();
}
}
GUI & event-driven programming

Swing component: JOptionPane


The JOptionPane class is used to provide standard dialog
boxes such as message dialog box, confirm dialog box and
input dialog box.
These dialog boxes are used to display information or get
input from the user.

The following are JOptionPane constructors:


Constructor Description
JOptionPane() It is used to create a JOptionPane with a test
message.
JOptionPane(Object message) It is used to create an instance of JOptionPane to
display a message.
JOptionPane(Object message, It is used to create an instance of JOptionPane to
int messageType display a message with specified message type
and default options.

https://docs.oracle.com/en/java/javase/22/docs/api/java.desktop/javax/swing/JOptionPane.html
GUI & event-driven programming

Swing component: JOptionPane


JOptionPane inherits JComponent class.

The following are Commonly used Methods of JComponent class

Methods Description
JDialog createDialog(String It is used to create and return a new
title) parentless JDialog with the specified title.
static void showMessageDialog It is used to create an information-message
(Component parentComponent, dialog titled "Message".
Object message)
static void showMessageDialog It is used to create a message dialog with
(Component parentComponent, given title and messageType.
Object message, String title,
int messageType)
GUI & event-driven programming

Swing component: JOptionPane


Cont…
The following are Commonly used Methods of JComponent class

Methods Description
static int showConfirmDialog It is used to create a dialog with the options Yes,
(Component parentComponent, No and Cancel; with the title, Select an Option.
Object message)
static String It is used to show a question-message dialog
showInputDialog (Component requesting input from the user parented to
parentComponent, Object
parentComponent.
message)
void setInputValue(Object It is used to set the input value that was
newValue) selected or input by the user.
GUI & event-driven programming
Swing component: JOptionPane
Example: showMessageDialog()

import javax.swing.*;

public class OptionPaneExample {


JFrame f;
OptionPaneExample(){
f=new JFrame();
JOptionPane.showMessageDialog(f,"Hello, Student!");
}

public static void main(String[] args) {


new OptionPaneExample();
}
}
GUI & event-driven programming
Swing component: JOptionPane
Example: showMessageDialog()

import javax.swing.*;

public class OptionPaneExample {


JFrame f;
OptionPaneExample(){
f=new JFrame();
JOptionPane.showMessageDialog (f, "Successfully Updated.",
"Alert",JOptionPane.WARNING_MESSAGE);
}
public static void main(String[] args) {
new OptionPaneExample();
}
}
GUI & event-driven programming
Swing component: JOptionPane
Example: showInputDialog()

import javax.swing.*;

public class OptionPaneExample {


JFrame f;
OptionPaneExample(){
f= new JFrame();
String name = JOptionPane.showInputDialog(f,"Enter Name");
}

public static void main(String[] args) {


new OptionPaneExample();
}
}
GUI & event-driven programming
Swing component: JOptionPane
Example: showConfirmDialog()

import javax.swing.*;
import java.awt.event.*;
public class OptionPaneExample extends WindowAdapter{
JFrame f;
OptionPaneExample(){
f= new JFrame();
f.addWindowListener(this);
f.setSize(300, 300);
f.setLayout(null);
f.setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE);
f.setVisible(true);
}
public void windowClosing(WindowEvent e) {
int a = JOptionPane.showConfirmDialog(f,"Are you sure?");
if(a==JOptionPane.YES_OPTION){
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
}
public static void main(String[] args) {
new OptionPaneExample();
}
}
GUI & event-driven programming

Swing component: JMenuBar, JMenu & JMenuItem


The JMenuBar class is used to display menubar on the
window or frame. It may have several menus.

The object of JMenu class is a pull down menu component


which is displayed from the menu bar. It inherits the
JMenuItem class.

The object of JMenuItem class adds a simple labeled menu


item. The items used in a menu must belong to the
JMenuItem or any of its subclass.
Example:
import javax.swing.*;
class MenuExample{
JMenu menu, submenu;
JMenuItem i1, i2, i3, i4, i5;
MenuExample(){
JFrame f= new JFrame("Menu and MenuItem Example");
JMenuBar mb = new JMenuBar();
menu = new JMenu("Menu");
submenu = new JMenu("Sub Menu");
i1 = new JMenuItem("Item 1");
i2 = new JMenuItem("Item 2");
i3 = new JMenuItem("Item 3");
i4 = new JMenuItem("Item 4");
i5 = new JMenuItem("Item 5");
menu.add(i1); menu.add(i2); menu.add(i3);
submenu.add(i4); submenu.add(i5);
menu.add(submenu);
mb.add(menu);
f.setJMenuBar(mb);
f.setSize(400,400);
f.setLayout(null);
f.setVisible(true);
}
public static void main(String args[]){
new MenuExample();
}
}
User interfaces using frames
Layout Manager
• 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.
User interfaces using frames
Layout Manager
• Some of the mostly used layout in java are:
1. FlowLayout
2. GridLayout
3. BorderLayout
User interfaces using frames
Layout Manager
FlowLayout
• Default for JPanel . Places components sequentially (left to right) in the order
they were added. It is also possible to specify the order of the components by
using the Container method add , which takes a Component and an integer
index position as arguments.

GridLayout
• Arranges the components into rows and columns.

BorderLayout
• Default for JFrame. Arranges the components into five areas: NORTH ,
SOUTH , EAST , WEST and CENTER .
User interfaces using frames
Layout Manager
FlowLayout
The class FlowLayout set the layout of the components
in a left-to-right flow.

Example:
User interfaces using frames
Layout Manager
FlowLayout
These are methods available in FlowLayout class.

The get and set methods for these data fields are provided in
java.awt.FlowLayout the class, but omitted in the UML diagram for brevity.

-alignment: int The alignment of this layout manager (default: CENTER).


-hgap: int The horizontal gap of this layout manager (default: 5 pixels).
-vgap: int The vertical gap of this layout manager (default: 5 pixels).

+FlowLayout() Creates a default FlowLayout manager.


+FlowLayout(alignment: int) Creates a FlowLayout manager with a specified alignment.
+FlowLayout(alignment: int, hgap: Creates a FlowLayout manager with a specified alignment,
int, vgap: int) horizontal gap, and vertical gap.
FlowLayout Example
User interfaces using frames
Layout Manager
GridLayout
The GridLayout manages the components in the form of
a rectangular grid.

Example:
User interfaces using frames
Layout Manager
GridLayout
These are methods available in GridLayout class.
The get and set methods for these data fields are provided in
java.awt.GridLayout the class, but omitted in the UML diagram for brevity.

-rows: int The number of rows in this layout manager (default: 1).
-columns: int The number of columns in this layout manager (default: 1).
-hgap: int The horizontal gap of this layout manager (default: 0).
-vgap: int The vertical gap of this layout manager (default: 0).

+GridLayout() Creates a default GridLayout manager.


+GridLayout(rows: int, columns: int) Creates a GridLayout with a specified number of rows and columns.
+GridLayout(rows: int, columns: int, Creates a GridLayout manager with a specified number of rows and
hgap: int, vgap: int) columns, horizontal gap, and vertical gap.
GridLayout Example
User interfaces using frames
Layout Manager
BorderLayout
The borderlayout arranges the components to fit in the
five regions: east, west, north, south, and center.

Example:
User interfaces using frames
Layout Manager
BorderLayout
These are methods available in BorderLayout class.

The get and set methods for these data fields are provided in
java.awt.BorderLayout the class, but omitted in the UML diagram for brevity.

-hgap: int The horizontal gap of this layout manager (default: 0).
-vgap: int The vertical gap of this layout manager (default: 0).

+BorderLayout() Creates a default BorderLayout manager.


+BorderLayout(hgap: int, vgap: int) Creates a BorderLayout manager with a specified number of
horizontal gap, and vertical gap.
BorderLayout Example
User Interfaces
Color Class
▪ 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
Syntax:
Color c = new Color(r, g, b);

r, g, and b specify a color by its red, green, and blue components

Example: Color c = new Color(228, 100, 255);


User Interfaces
font Class
▪ The Font class states fonts, which are used to render text
in a visible way.
▪ The package containing the font class is in java.awt.Font

Syntax:
Font myFont = new Font(name, style, size);

Example:
Font myFont = new Font("SansSerif ", Font.BOLD, 16);
Font myFont = new Font("Serif", Font.BOLD+Font.ITALIC, 12);
Chapter 3
(Part 2)
Graphical User Interface
&
Event-Driven Programming
Topics covered:
✓ Event-driven programming
✓ Event handling
o Event
o Source
o Listener
We wonder how to make the
button calculate the BMI when it is
clicked?

✓ Answer: Event-driven Programming


Event-driven programming

Procedural vs. Event-Driven


Programming

• In procedural programming code is


executed in procedural order.

• In event-driven programming, code is


executed upon activation of events.
Event-driven programming

What is an Event?
• An event can be defined as a type of
signal to the program that something has
happened.
• The event is generated
– by external user actions such as mouse
movements, mouse clicks, and
keystrokes, or
– by the operating system, such as a
timer
Event-driven programming

What is an Event?
• GUI components communicate with the
rest of the applications through events.
• The source of an event is the component
that causes that event to occur.
• The listener of an event is an object that
receives the event and processes it
appropriately.
GUI & event-driven programming

Handling Events
What is Event Handler?

The code that perform the task in response to an


event

What is Event Handling?

The mechanism to process events/overall process


of responding to events
Event-driven programming

Handling Events

The event-handling model of Java is based on the


concept known as the Delegation-based Event
Model

With this model, event handling is implemented by


two types of objects:
– event source objects
– event listener objects
The Event Handling Process
The Event Handling Process
The Event Handling Process
The Event Handling Process
Some common User Actions and Type of Event

Source Event Type


User Action Object Generated

Click a button JButton ActionEvent


Click a check box JCheckBox ItemEvent, ActionEvent
Click a radio button JRadioButton ItemEvent, ActionEvent
Press return on a text field JTextField ActionEvent
Select a new item JComboBox ItemEvent, ActionEvent
Select an item from a List JList ListSelectionEvent
Window opened, closed, etc. Window WindowEvent
Mouse pressed, released, etc. Any Component MouseEvent
Key released, pressed, etc. Any Component KeyEvent
Event-driven programming

Selected Event Handlers


Event Class Listener Interface Listener Methods (Handlers)
ActionEvent ActionListener actionPerformed(ActionEvent)
ItemEvent ItemListener itemStateChanged(ItemEvent)
WindowEvent WindowListener windowClosing(WindowEvent)
windowOpened(WindowEvent)
windowIconified(WindowEvent)
windowDeiconified(WindowEvent)
windowClosed(WindowEvent)
windowActivated(WindowEvent)
windowDeactivated(WindowEvent)
ContainerEvent ContainerListener componentAdded(ContainerEvent)
componentRemoved(ContainerEvent)
MouseEvent MouseListener mousePressed(MouseEvent)
mouseReleased(MouseEvent)
mouseClicked(MouseEvent)
mouseExited(MouseEvent)
mouseEntered(MouseEvent)
KeyEvent KeyListener keyPressed(KeyEvent)
keyReleased(KeyEvent)
keyTypeed(KeyEvent)
Event-driven programming

Java Event Handling code


We can put the event handling code into
one of the following places:
1. Within class
2. Other class
3. Anonymous class.
Java event handling within class
Java event handling by outer class
Java event handling by anonymous class

You might also like