You are on page 1of 60

GUI Programming

Dr. Mainak Biswas


An
Introduction
• A graphical user interface (GUI) presents a user-friendly
mechanism for interacting with an application. A GUI
(pronounced “GOO-ee”) gives an application a distinctive
“look and feel.” GUIs are built from GUI components. These
are sometimes called controls or widgets—short for window
gadgets. 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. Java’s so-called Swing GUI
components from the javax.swing package.
2
Content
s

1 Basic Concepts

2 AWT and Swing Control Components

3 Layout Manager

4 Event Handling

5 Other References
GUI?

 Graphical User Interface (pronounced "GOO-


ee“).
 Presents a user-friendly mechanism for
interacting with an application.
 Users can learn how to use an app quickly and use
it more productively.
 Ex: Internet Explorer, MS Word, JCreator…
 GUIs are built from GUI components (controls
or widgets-window gadget).
 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.
Abstract Window Toolkit (AWT) vs. Swing

 Similarities:
 Tools provided by Java for developing
interactive GUI applications
 Provides GUI components that can be used in
creating Java applications and applets
Simple GUI-Based Input/Output with
JOptionPane

Taking Input from User Using


Input Dialog Box

Converting
String
Into
integer
value
3
Output

7
Different JoptionPane
Message Icons

8
JOptionPane Message Icon
(cont)

9
JOptionPane Message Icon
(cont)

1
0
Abstract Window Toolkit (AWT) vs. Swing

 AWT (Abstract Window Toolkit)


 Some AWT components use native code
 Platform-dependent
 Ensure that the look and feel of an application run on
different machines be comparable
 Swing
 Written entirely using the Java programming language
 Platform-independent
 Ensures applications deployed across different
platforms have the same appearance
 Built around a number of APIs that implement various
parts of the AWT
• Can be used with AWT
Demo

 MessageBox
 InputBox
 Create Frame (AWT)
 Create Frame (Swing)
 CenterFrame
Exercises

Display two input-boxes that accepts two


numbers then shows the result.
Accepts three numbers, displays the
largest, smallest.
(Assume that all input values are valid
numbers)
Create a simple frame
AWT Control Components

An AWT control is a component that


enables end users to interact with
applications created in Java.
All AWT controls in Java are subclasses of
the Component class.
The Component class provides the add()
method to add AWT components to
containers, such as an applet or a window.
AWT Control Components

 TextField
 TextArea
 Button
 List
 CheckBox
 Choice
 Labels
Awt components
• The Abstract Window Toolkit (AWT) is Java's original platform-
independent windowing, graphics, and user-interface widget toolkit.
The AWT is now part of the Java Foundation Classes (JFC) — the
standard API for providing a graphical user interface (GUI) for a Java
program.
• AWT is also the GUI toolkit for a number of Java ME profiles. For
example, Connected Device Configuration profiles require Java
runtimes on mobile telephones to support AWT.

16
Dem
o
 FrameWithControl
Swing Control Components

 Swing components contain the Pluggable Look and Feel


(PL&F) feature that allows applications to have the same
behavior on various platforms.
 Identifying the Swing Component Class Hierarchy
 The JComponent class is the root of the Swing hierarchy, which is an
extension of the AWT container class.
 The class hierarchy of the Swing components is categorized into:
• Top-level Swing Containers: Acts as a container for
placing the intermediate-level and atomic swing components, such as
panels, frames, buttons, and check boxes.
• Intermediate-level Swing Containers: Placed on the top-level
containers and contains atomic components.
• Atomic Components: Placed on the intermediate-level swing
containers. Atomic components are used to accept input from a user.
Swing Component
Example

19
Swing Control Components

 Using the Top-level Swing Containers


 JApplet
• The JApplet class is an extension of the AWT applet class.
• The Swing components that contain an applet need to
extend the JApplet class.
• The JApplet() constructor enables you to create a
swing applet instance when you create an instance of the
JApplet class.
 JFrame:
• The JFrame class is an extension of the AWT Frame class.
• You cannot add components directly to JFrame.
Swing Control Components

 Using the Top-level Swing Containers (Cont.)


 JDialog
• The JDialog class is an extension of the AWT
java.awt.Dialog class.
 Using the Intermediate Level Swing
Containers
 JPanel
• JPanel class is an extension of the JComponent class that
provides a replacement for the AWT Panel class.
• You create a panel and add various components to it.
• The panel is further added to the content pane, which represents
the display area of a window, a dialog, or a frame.
• JPanel supports all layout managers of AWT.
• By default, JPanel applies the flow layout manager.
Swing Control Components

 Using the Intermediate Level Swing Containers (Contd.)


 JTabbedPane:
• The JTabbedPane class is used to create a tabbed pane
component that enables you to switch between groups of
components by clicking a tab with a given label.
• Tabs are added to the JTabbedPane object by using the addTab()
method.
• The JTabbedPane class enables you to add multiple components but it
displays only a single component at a time.
 Using the Atomic Components
 JButton
 JTextField
 JCheckBox
 JComboBox
 JLabel
 JRadioButton
Dem
o
 JFrameWithControl
Displaying Text and Images in a
window
• Most windows you’ll create that can contain Swing GUI components are instances of
class JFrame or a subclass of JFrame.
• JFrame is an indirect subclass of class java.awt.Window that provides the basic
attributes and behaviors of a window—a title bar at the top, and buttons to minimize,
maximize and close the window.

See the Example Program on the Next


Slide

24
D Importing
Classes
I That will be
S Used in
P
the
L
program
A Declaring three
JLabel Instances
Y
I
T
N
E

XG
T

A
Of the program
Constructor

MI 14
A
G
Output of the
Program

26
Labeling GUI
components
• A typical GUI consists of many components. GUI designers often provide
text stating the purpose of each. Such text is known as a label and is created
with a JLabel—a subclass of JComponent.AJLabel displays read-only text, an
image, or both text and an image. Applications rarely change a label’s
contents after creating it. Following is the Example program:

27
Output of the
program

28
Common GUI Event Types and
• Listener
Following Interfaces
Figure illustrates a hierarchy containing many event
classes from the package java.awt.event. These event types
are used with both AWT and Swing components. Additional
event types that are specific to Swing GUI components are
declared in package javax.swing.event.

29
Jbutto
n
• A button is a component the user clicks to trigger a specific action.
• A Java application can use several types of buttons, including command
buttons, checkboxes, toggle buttons and radio buttons.
Following is the Swing Button Hierarchy:

30
JbuttonExam
ple

Importing swing and AWT classes


ButtonFram class is extending JFrame
Declaring Jbuttons Variables plainJButton
And fancyJButton

Adds the Jbutton To JFrame


Creating Image Icon Adding button to JFrame

Creating Button Handler

These lines declares

actionPerformed
To display a message 20
Dialog Box containing the
label for the button
The user pressed
Jbutton Example
(cont)

Creating
Main

21
Buttons that Maintains
States
• The Swing GUI components contain three types of state
buttons
1. JToggleButton
A toggle button is a button that represents a settings with two
states i.e. on and off.
Toggle buttons look similar to command buttons and display
a graphic or text (or both) to identify the button.
The graphic or button text should remain the same whether
the button is in the on or off state.
The state is indicated by highlighting the background of the
buttons.
Users can click toggle buttons to turn a setting on or off--for
instance, to switch between italic and plain style in selected 22
text.
Button that maintain
States (cont)
2-Check Boxes:
 A checkbox is a control that represents a setting or value with an on or
off choice.
 The setting of an individual checkbox is independent of other
checkboxes--that is, more than one checkbox in a set can be checked at
any given time.
 A check mark within the checkbox indicates that the setting is selected.
The following figure shows both available and unavailable checkboxes in
selected and unselected states.


23
 The user clicks a checkbox to switch its setting from off to on, or on to
off. When a checkbox is unavailable, the user cannot change its setting.
Example
JCheckBoxes
Importing the classes

Using method setFont inherited by


JtextField indirectly from class
component

Creating two JCheckBox


object

Creating an instance of class


CheckBoxHandler and register
It with method addItemListener
For both the JCheckBox objects
2
4
Event Handling is being performed
By an instance of private inner class
JCheckBox Example
(Cont)

Main Class

25
Buttons that Maintains
States(cont)
3-Radio Buttons
 A radio button represents an exclusive choice within a set of related
options.
 Within a set of radio buttons, only one button can be on at any given
time.
 The following figure shows active radio buttons and inactive radio
buttons in both on and off states.

 When users click a radio button, its setting is always set to on. An
inner filled circle within the round button graphic indicates that the
setting is selected. If another button in the set has previously been
selected, its state changes to off.
26
 When a radio button is unavailable, users cannot change its setting.
JRadioButton
Example

Creating 4 JRadioButtonobjects
And adding them to JFrame 27
Instantiates ButtonGroup
JRadioButton Example Object radioGroup
(Cont) Using ButtonGroup method add
To associate each of the
JRadioButtons with radio group

Creating four instances of inner class


RadioButtonHandler

Class RadioButtonHandler implements


Interface ItemListener so it can handle
ItemEvents generated by the JRadioButtons

39
JRadioButton
(cont)

40
JComboB
ox
 A JComboBox, lets the user choose one of several choices, can have two
very different forms.
 The default form is the uneditable combo box, which features a button
and
a drop-down list of values.

 The second form, called the editable combo box, features a text field with a
small button abutting it. The user can type a value in the text field or click
the button to display a drop-down list.

41
JComboBox
Example
Declaring and initializing array
Icons with four new image
icon objects
It contains the names of the four
Image files that are stored in the
Same directory as the application

A constructor initializes a JComboBox


Object with the strings in array names
As the elements in the list
Using JComboBox method setMaximumRowCount
to set Maximum number of elements That are
displayed when the user Clicks JComboBox

Are one statement that declares the event listner’s


Class,creates an object of that class and register It as
the listener for imagesJComboBox’s ItemEvents.
JComboBox Example
(Cont)

43
JLis
t• A JList presents the user with a group of items, displayed in
one or more columns, to choose from.
• Lists can have many items, so they are often put in scroll
panes.
The following figures shows two applications that use
lists.

44
Jlist
(Cont)
Types of Lists:
 Single Selection
Only one item can be selected at a time. When the user selects an item, any
previously selected item is deselected first.

 Single Interval Selection


Multiple, contiguous items can be selected. When the user begins a new
selection range, any previously selected items are deselected first.

45
Jlist
(Cont)
 Multiple Interval Selection:
The default. Any combination of items can be selected. The user must
explicitly deselect items.

46
Jlist Example
Creating Jlist object colorJList

This line uses Jlist method


setSelectionMode To specify the list’s
selection mode.Class ListSelectMode1
Declares three constants that specify
A Jlist’s selectionMode-SINGLE
SELECTION
Adding new instance of class
JScrollPane to the Jframe.

These lines uses Jlist method


addListSelectionListener to register
An object that implements ListSelectionListner
Jlist Example
(Cont)

48
JSlid
er
• A JSlider component is intended to let the user easily enter a
numeric value bounded by a minimum and maximum value.
The following picture shows an application that uses a slider
to control animation speed:

49
Jslider
Example

Class OvalPanel contains a paintComponent


Method that draws a filled circle.

A setDiameter method that changes the


Circle’s diameter and repaints the OvalPanel

A getPreferredSize method that returns


The preferred width and height of an
OvalPanel

getMinimumSize method that returns


An OvalPanel’s minimum width and height
39
Jslider Exapmle
(Cont)

These lines creates Jslider object


DiameterSlider to control the diameter
Of the circle drawn on the OvalPanel
These lines customize the
appearance
Of the Jslider.Method setMajorTickSpacing
Indicates that each major tick mark
Represents 10 values in the range of
Values supported by the Jslider.

51
Jslider Example
(Cont)

52
Layout Managers

 The layout managers are used to position the components, such as an


applet, a panel, or a frame in a container.
 The layout managers implement the java.awt.LayoutManager
interface.
 A layout manager is an instance of the LayoutManager interface in Java.
 You can use the following method to apply the desired layout to the
components:

 void setLayout(layoutManager obj)


 In the preceding syntax, obj is the reference to the desired layout
manager.
 Java has various predefined classes of layout managers.
 All layout managers make use of the setLayout() method to set the
layout of a container.
 If the setLayout() method is not used, then the default layout of the
container is set.
Layout Managers

 The different types of layout managers are:


 FlowLayout Manager
• The flow layout is the default layout manager used for the
Applet class.
• In the flow layout manager, the components are placed in a
container window in a sequence one after the other in rows.
• Java provides the FlowLayout class to apply flow layout to the
various components that you are inserting in an applet.
• You can use the following constructors to create an instance of
the FlowLayout class:
– FlowLayout()
– FlowLayout(int align)
– FlowLayout(int align, int hgap,int vgap)
Layout Managers

 BorderLayout Manager
 BorderLayout is the default layout of the Frame class.
 The BorderLayout layout manager divides the container into
north, south, east, west, and centre regions.
 You can place five components or controls in each part.
 Java provides the BorderLayout class to apply the border layout to
the components.
 The setLayout() method is used for applying border layout to a
container.
 You specify the directions for the BorderLayout using the
BorderLayout.NORTH, BorderLayout.SOUTH,
BorderLayout.EAST, BorderLayout.WEST, and
BorderLayout.CENTER constants.
 You can use the following constructors to create an instance of the
BorderLayout class:
 BorderLayout()
 BorderLayout(int h, int v)
Layout Managers

 GridLayout Manager
 The grid layout is the layout that divides the container
into rows and columns.
 The intersection of a row and a column of the grid
layout is called cell.
 The GridLayout class of Java enables you to create a grid
layout.
 All the components in a grid are of the same size.
 You can use the following constructors to create an
instance of the GridLayout class:
• GridLayout()
• GridLayout(int r, int c)
• GridLayout(int r, int c, int h, int v)
Dem
o
 FlowLayout
 BorderLayout
 GridLayout
To be
continued
 To be continued….
Reference
s
 Java Passion from Sun Microsystems
 Java Tutorial from Sun Microsystems
Core Java 2 Volume I Fundamentals 7th
Edition
 Java How to Program 6th Edition
 Java Swing 2nd Edition
www.niit-vn.c
om
www.niit-vn.com/4rum

You might also like