0% found this document useful (0 votes)
37 views45 pages

AOOP CH - 4 GUI-1

The document discusses Java GUI and database connectivity. It describes developing GUI with Java using containers, components and layout managers. It also explains key classes like JLabel, JButton, AbstractButton and provides code examples to create these GUI components.
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)
37 views45 pages

AOOP CH - 4 GUI-1

The document discusses Java GUI and database connectivity. It describes developing GUI with Java using containers, components and layout managers. It also explains key classes like JLabel, JButton, AbstractButton and provides code examples to create these GUI components.
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
You are on page 1/ 45

A D VA N C E D O B J E C T O R I E N T E D P R O G R A M M I N G

By Nahom.G

C H A P T E R F O U R : JAVA G U I A N D J D B C
INTRODUCTION

 Java is general-purpose programming language.

It is attractive to software developers primarily due to its powerful


library and runtime, simple syntax, rich set of supported platforms
(Write Once, Run Anywhere - WORA) and
awesome/inspire/excellent community.
Used to designed user friendly graphical interface for ease of use
and desirable/attiractive communication.
DEVELOPING GUI WITH JAVA

A graphical user interface (GUI) makes a system user friendly


and easy to use.
GUI-are built from GUI Components like: Text Fields, labels,
Buttons, Text Boxes, Radio Buttons and etc.
There are currently three sets of Java APIs for graphics
programming:
 AWT (Abstract Windowing Toolkit),

 Swing and

 JavaFX.
… DEVELOPING GUI WITH JAVA
1. Abstract Windowing Toolkit (AWT) API was introduced in JDK 1.0. Most of the
AWT components have become absolute and should be replaced by newer Swing
components.

2. Swing API, a much more comprehensive set of graphics libraries that enhances the
AWT, it 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. The latest JavaFX, which was integrated into JDK 8, is meant to replace Swing.
CONTAINERS AND COMPONENTS

There are two types of GUI elements:


1. Component: Components are elementary GUI entities, such as Button, Label, and Text Field.
2. Container: Containers, such as Frame and Panel, are used to hold components in a specific layout
(such as Flow Layout or Grid Layout). A container can also hold sub-containers.
 In the above figure, there are three containers: a Frame and two Panels.
 A Frame is the top-level container of an AWT program.
 A Frame has a title bar (containing an icon, a title, and the
minimize/maximize/close buttons), an optional menu bar and the
content display area.
 A Panel is a rectangular area used to group related GUI components in a
certain layout.
 In the above figure, the top-level Frame contains two Panels.
 There are five components:
a Label (providing description),
a TextField (for users to enter text), and three Buttons (for user to trigger
certain programmed actions).
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 c).

A container (say c) can invoke c.add(aComponent) to add aComponent into itself.

For example,

Panel pnl = new Panel(); // Panel is a container

Button btn = new Button("Press"); // Button is a component

pnl.add(btn); // The Panel container adds a Button component

GUI components are also called controls (e.g., Microsoft ActiveX Control), widgets (e.g.,
Eclipse's Standard Widget Toolkit, Google Web Toolkit), which allow users to interact with (or
control) the application.
AWT CONTAINER CLASSES
Top-Level Containers: Frame, Dialog and Applet
 Each GUI program has a top-level
container. The commonly-used top-level
containers in AWT are Frame, Dialog and
Applet:
 A Frame provides the "main window" for
your GUI application.
 It has a title bar (containing an icon, a
title, the minimize,
maximize/restoredown and close buttons),
an optional menu bar, and the content
display area.
 To write a GUI program, we typically
start with a subclass extending from
java.awt.
Frame to inherit the main window as
import java.awt.Frame; // Using Frame class in package java.awt

// A GUI program is written as a subclass of Frame - the top-level container

// This subclass inherits all properties from Frame, e.g., title, icon, buttons, content-pane

public class MyGUIProgram extends Frame {

// private variables ......

// Constructor to setup the GUI components

public MyGUIProgram() { ...... }

// methods ...... ......

// The entry main() method

public static void main(String[] args) {

// Invoke the constructor (to setup the GUI) by allocating an instance

new MyGUIProgram(); } }
 An AWT Dialog is a "pop-up
window" used for interacting with the
users.
 A Dialog has a title-bar (containing an
icon, a title and a close button) and a
content display area, as illustrated.
 An AWT Applet (in package
java.applet) is the top-level container
for an applet, which is a Java program
running inside a browser.
SECONDARY CONTAINERS: PANEL AND SCROLL PANE

Secondary Containers: Panel and ScrollPane

Secondary containers are placed inside a top-level container or another


secondary container.

AWT provides these secondary containers:

Panel: a rectangular box used to layout a set of related GUI components in pattern
such as grid or flow.

Scroll Pane: provides automatic horizontal and/or vertical scrolling for a single
child component.
HIERARCHY OF THE AWT CONTAINER CLASSES
COMPONENTS

Components- are GUI entities with which you can allow the users of your application to use
application easily.
 In other word, an object with which the users interacts with the application via input forms
like keyboard, mouse..).

Container
Container : Container is a GUI that holds a set of components.

• Java swing technology provides three types of containers. Such as

- JFrame

- JApplet

- JPanel
LAYOUT MANAGERS

Layout managers are provided to arrange GUI components in a container for


presentation purposes.

Programmers can use the layout managers for basic layout capabilities instead
of determining the exact position and size of every GUI component.

All layout managers implement the interface Layout Manager (in package
java.awt).
FLOW LAYOUT CLASS
Flow Layout is the simplest layout manager.
GUI components are placed on a container from left to right in the order in
which they are added to the container.
When the edge of the container is reached, components continue to display on
the next line.
Flow Layout Class allows GUI components to be left aligned, centered (the
default) and right aligned.
Eg: Jframe frame=new Jframe();
frame.setLayout(new FlowLayout());
BORDER LAYOUT CLASS
The Border Layout manager arranges components into five regions: NORTH, SOUTH, EAST,
WEST and CENTER.

A Border Layout limits a Container to containing at most five components—one in each region.

NORTH

WEST CENTER EAST

SOUTH
 Eg: frame.setLayout(new BorderLayout());
frame.add(Btn1,BorderLayout.NORTH);
frame.add(Btn2,BorderLayout.WEST);
. . .
. . .
SAMPLE CODE

PUT
T
OU
GRID LAYOUT CLASS
The GridLayout layout manager divides the container into a grid.

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.
Eg: frame.setLayout(new GridLayout (2,4));
JTOOL TIP CLASS:
JToolTip Class: The Swing components support the ability to display brief pop-
up messages when the cursor rests over them.

The class used to display pop-up messages is JToolTip.

Calling the public void setToolTipText(String text) method of JComponent


automatically causes the creation of a JToolTip instance when the mouse rests
over a component with the installed pop-up message.

You don’t normally call the JToolTip constructor directly.

Eg: component.setToolTipText("This is Tool Tip Text");


JLABEL CLASS
JLabel Class: The first real Swing component to examine closely is
the simplest, the JLabel.
The JLabel serves as the replacement component for the AWT
Label but it can do much more.
JLabel can have text, images, or both. The text can be a single line
of text or HTML.
In addition JLabel can support different enabled and disabled
images.
CREATING A JLABEL:
Constructors of a JLabel class are used to create a JLabel
component.
 public JLabel()
Eg: JLabel label = new JLabel();
 public JLabel(Icon image)
Eg: Icon icon = new ImageIcon("cat.jpg");
JLabel label = new JLabel(icon);
 public JLabel(Icon image, int horizontalAlignment)
Eg: Icon icon = new ImageIcon("cat.jpg");
JLabel label = new JLabel(icon, JLabel.RIGHT);
ABSTRACT BUTTON CLASS
The Abstract Button class is an important Swing class that works
behind the scenes as the parent class of all the Swing button
components.
Some of its subclass are:
 Jbutton- for regular buttons
 JCheckBox
 JRadioButton
 JToggleButton
 ……..
ABSTRACT BUTTON CLASS…..

Fig: Swing button hierarchy.


JBUTTON CLASS
• The JButton component is the basic Abstract Button component that can
be selected.
• It supports text, images, and HTML-based labels, as shown in the
following figure.

Figure: Sample JButton components.


CREATING A JBUTTON:
• Constructors of a JButton class are used to create a JButton component.
- public JButton()
JButton button = new JButton();
- public JButton(Icon image)
Icon icon = new ImageIcon("cat.jpg");
JButton button = new JButton(icon);
- public JButton(String text)
JButton button = new JButton("Cat");
CREATING A JBUTTON…..
- public JButton(String text, Icon icon)
Icon icon = new ImageIcon("cat.jpg");
JButton button = new JButton("Cat", icon);
- public JButton(Action action)
Action action = ...;
JButton button = new JButton(action);
JBUTTON PROPERTIES
• After creating a JButton, you can modify each of its many
properties.
- enable: allow you to change the state of Jbutton component with
regard to its enablity.
Eg:okButton.setEnable(false);
- actionCommand: used to specifically identify which button user
selected.
 Use setter() and getter() method of actionCommand.
Eg: okButton.setActionCommand(“OK”);
okButton.getActionCommand();
HANDLING JBUTTON EVENTS
Event handling capabilities of a Jbutton component is inherited
from the AbstractButton class.
The common Listener for Jbutton is the ActionListener.
When a Jbutton component is selected,all registered
ActionListeners are notified.
 This is done by passing an ActionEvent into Listeners.
RECOMMENDED STEPS FOR HANDLING EVENTS
1. Declare and Define the Listeners.
Syntax: ActionListener ls=new ActionListener(){
public void actionPerformed(ActionEvent e)
{
//your event handling code is here
}
};
II. Register the Listeners for each components.
Syntax: okButton.addActionListener(ls);
cancilButton.addActionListener(ls);
SAMPLE CODE
package buttons;
import java.awt.*;
import java.awt.event.*;
Import javax.swing.*;
;
utp ut
/** * @author chimdesa T h e O
*/
public class JButtonClass
{
public static void main(String[] args) {
JFrame frame =new JFrame("JButton Class");
JButton okButton=new JButton("OK");
JButton cancilButton=new JButton("Cancil");
ActionListener twoListener=new ActionListener()
{
SAMPLE CODE ….
//Override Action Events
@Override
public void actionPerformed(ActionEvent e) {
String command=e.getActionCommand();
if(command.equals("OK"))
{
JOptionPane.showMessageDialog(null, "You Clicked OK Button");
}
else if(command.equals("Cancil"))
{
JOptionPane.showMessageDialog(null, "You Clicked Cancil Button");
}
}
};
SAMPLE CODE … .
//Register Listeners
okButton.addActionListener(twoListener);
cancilButton.addActionListener(twoListener);
frame.setVisible(true);
frame.setSize(200, 200);
frame.add(okButton);
frame.add(cancilButton);
frame.setLayout(new FlowLayout());
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
}
JTEXTFIELD CLASS
- JTextField class used to create a TextField Component for a
single line input.
 Its size is determined by number of characters.
Is a single-line area in which the user can enter text
JPasswordField.
Extends Jtextcomponent class which provides many features
common to Swing’s text-based components.

Eg: JTextFieldClass obj=new JTextFieldClass(15);


CREATING JTEXTFIELD
• Constructors of a JTextField class are used to create a JTextField
component.
- public JTextField(String text)
Eg: JTextField UserNameText=new JTextField(“Enter your
name here”);
-public JTextField(int columnWidth)

Eg: JTextField nameText =new JTextField(15);


JTEXTFIELD PROPERTIES
• After creating a JTextField, you can modify each of its many properties.
- editable: a properties that deals with editability of JTextField component.

Eg: nameText .setEditable(flase);


This one make the text field uneditable—i.e., the user cannot modify the text in the text
field.
- Horizontal Alignment: used to adjust the adjustment of the text in the
JTextField component.

Eg: nameText.setHorizontalAlignment(JTextField.RIGHT);
JCHECKBOX CLASS
The JCheckBox class represents the toggle component.
It is JToggleButton subclass.
Displays a check box icon next to the text label for a two-state
option.
The Icon uses an optional check mark to show the current state of
the object.
 JCheckBox inherits all properties from AbstractButton Class. (text,
icon, alignment, text position, selected, mnemonics ).
JCHECKBOX CLASS …

• Although the ButtonGroup is available to group together


check boxes, it isn’t normally appropriate.
• When multiple JCheckBox components are within a
ButtonGroup, they behave like JRadioButton components
but look like JCheckBox components.
CREATING JCHECKBOX
SAMPLE CODE
JCHECKBOX PROPERTIES
• After creating a JCheckBox, you can modify each of its many
properties.
– borderPainted: permits to display the border around the check icon as two-
dimensional.

By default, the borderPainted property is false, meaning the border will be


three-dimensional.
• Eg: wolloCheckedBox.setBorderPainted(true);

– Selection: this is can either help to check the selection status of a JCheckBox
object or it is used to set icon options when the instance is selected.
JCHECKBOX PROPERTIES…
• Eg. wolloCheckedBox.isSelected( );
– //checks the selection status and returns true if selected
• Eg. emptyCheckedBox.setSelectedIcon(Icon icon);
– //sets the icon when the instance is selected.

– Enable: You can enable or disable a JCheckBox instance with


the enable property in the same way we did for JButton
instance.
• Eg. wolloCheckedBox.setEnabled(false);
– //Disables the wolloCheckedBox instance to be checked and unchecked.
• You can handle JCheckBox events in any one of three ways: with an
ActionListener, ItemListener, or a ChangeListener.
Site: http://www.java2s.com/Tutorial/Java/0240__Swing/ListeningtoJCheckBoxEventswithanItemListener.htm
Component Description
JLabel Displays uneditable text or icons.
JTextField Enables user to enter data from the keyboard. Can also be used to
display editable or uneditable text.
JButton Triggers an event when clicked with the mouse.
JCheckBox Specifies an option that can be selected or not selected.
JComboBox Provides a drop-down list of items from which the user can make a
selection by clicking an item or possibly by typing into the box.
JList Provides a list of items from which the user can make a selection by
clicking on any item in the list. Multiple elements can be selected.
JPanel Provides an area in which components can be placed and organized.
Can also be used as a drawing area for graphics.
DATA VALIDATION
Lab session 1: create a project GUI project and create a class called data
validation under this project
PROJECT WORK
GUI Calculator, Create a class called GUIcalculator under the project GUIPoject

You might also like