Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
38 views

Visual Programming Pt5

This document discusses Java's graphical user interface (GUI) application programming interface (API) and event-driven programming. It covers the Java AWT and Swing APIs, the differences between them, and elements of GUI applications like components, events, and listeners. Key GUI elements like frames, panels, and common components are demonstrated.
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
38 views

Visual Programming Pt5

This document discusses Java's graphical user interface (GUI) application programming interface (API) and event-driven programming. It covers the Java AWT and Swing APIs, the differences between them, and elements of GUI applications like components, events, and listeners. Key GUI elements like frames, panels, and common components are demonstrated.
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 46

Chapter 4

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
In this lesson, we will learn on how to
use SWING API to create Graphical user
interface for JAVA application

But.. Before that, let’s begin with


understanding of what is JAVA API?
Java API for GUI
The Java API
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 graphics 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. The latest JavaFX, which was integrated into JDK 8, is meant to replace
Swing
Now... Let’s take a look at
the different between
Swing API and AWT API
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
• Limited graphics programming to the lowest common
denominator.
• 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.
In order for us to be able to create the
GUI and proper event for JAVA
application , we need to import these
important packages into our program
codes:
1. java.awt

2. java.awt.event

3. javax.swing
Java API for GUI

Main Packages

Contains the main superclasses for the


java.awt GUI components plus a number of utility
type classes, such as Color and Point.

Contains the classes and interfaces for


managing events from the GUI
java.awt.event components, e.g. button clicks and mouse
movements.

Contains most of the visible GUI


javax.swing components that are used such as
buttons, text fields, frames and panels.
Java GUI API hierarchy
Java GUI API hierarchy
These are the javax.swing GUI
classes.
Java GUI API hierarchy
The javax.swing
These arepackage providesGUI
the javax.swing classes
for java swing APIclasses.
such as JButton,
JTextField..etc.
To distinguish from classes in java.awt
package, classes for javax.swing API
always started with capital J.
e.g: JApplet, Jframe, JTextField..etc.
Ok, now.. Let’s take a look at
the definition of GUI and 3
important elements of GUI
Applications
Elements of GUI applications

A graphical user interface (GUI) presents a user-


friendly mechanism for interacting with an application

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

3 Main elements of GUI applications:


1. GUI Component
2. Event
3. Listener
Elements of GUI applications

1. GUI 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 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

There are two types of GUI elements:


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

• 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 Containers

• A special type of component that is used to


hold and organize other components.
• A dialog box and an applet are examples of
container components.
• Include applets (JApplet), frames (JFrames)
and panels (Jpanel).
Elements of GUI applications

Java Containers & Swing’s Components


Creating GUI
Container
Container - JFrame

Sample codes:
import javax.swing.*; Importing all javax.swing
classes from the package
public class DemojFrame {
public static void main(String[] args) {
JFrame frame = new JFrame(“javax.swing.JFrame");
frame.setSize(400, 300);
frame.setVisible(true);
frame.setDefaultCloseOperation(
JFrame.EXIT_ON_CLOSE);
}
}
Creating GUI Label Text
field
Check
Box
Radio
Button

Objects Button
Components
Combo
Box
// 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"});
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
Creating a JFrame window
Steps:
1. Create JFrame object
2. Set frame size
3. Set frame visibility
4. Set frame close operation
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
Frame
Creating a JFrame window
1. Create frame object
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
Frame
Creating a JFrame window

import javax.swing.*; 2. Set frame size


public void setSize (int width, int height)
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
Frame
Creating a JFrame window

import javax.swing.*;

public class DemojFrame {


public static void main(String[]
3.
Set visibility of the frame
args)
public void { (Boolean visibility)
setSize
JFrame frame = new JFrame(“Jframe Window");
frame.setSize(400, 300);
frame.setVisible(true);
frame.setDefaultCloseOperation(
JFrame.EXIT_ON_CLOSE);
}
}
User interfaces using frames
Frame
Creating a JFrame window

4. Setimport javax.swing.*;
frame close operation

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
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
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
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.
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.
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.
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);
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.
User interfaces using frames
Using Panels as Sub-Containers
JPanel
The JPanel is a simplest 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
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.
End of
Chapter 4 part 1

You might also like