04 Java Swing

You might also like

Download as pdf or txt
Download as pdf or txt
You are on page 1of 40

Advanced Programming Applications

Lecture 4
Java Swing

CCS2304
What is a GUI Application?
• In such applications, users interact with a set of visual controls
(buttons, labels, text boxes, tool bars, menu items) to make an
application do its required tasks.

• Java GUI applications are event-driven, meaning nothing


happens until an application is called upon to respond to some
event (button pressing, menu selection, ...).

• GUI applications are governed by event listeners – they “listen”


for events to occur. Nothing happens until an event is detected.
Once an event is detected, a corresponding event method is
located, and the instructions provided by that method are
executed.

• Once an event method is completed, program control is


returned to the event listener.

2
What is a GUI Application?
• GUI applications offer flexibility, ease of use, familiarity, and
they’re nice to look at.

• All GUI applications are event-driven.

• For example, nothing happens in a word processor until you


click on a button, select a menu option, or type some text. Each
of these actions is an event.

• Example of a simple Java GUI application, a computer


stopwatch.

• This frame contains several different controls:


– Buttons to click
– Labels displaying information
– Empty text areas
3
What is a GUI Application?

• When a user clicks the button that says Start Timing, an event
is generated.

• The application processes the method associated with that


event and starts a timer, displaying the start time in the
corresponding text area.

• Similarly, when Stop Timing is clicked, the event method


associated with this button control’s click event is processed.

• In this method, the timing is stopped, the stop time is


displayed, the elapsed time is computed and displayed.

• An Exit button is used to stop/close the application.

• Swing package provides updated GUI components using what is


4
known as Java Foundation Classes (JFC).
Creating First Java Swing GUI Application

Uncheck

5
Creating First Java Swing GUI Application

6
Creating First Java Swing GUI Application

Design
Source
Controls

Form

File View

Properties
& Events

After pressing run project button,


you should select the main class.
7
Swing
• Swing is a framework or API that is used to create GUI or
window-based applications. It is an advanced version of AWT
(Abstract Window Toolkit) API and entirely written in Java.

• Unlike AWT, Java Swing provides platform-independent and


lightweight components.

• Difference between AWT and Swing:

8
Swing’s Features
• Swing is huge (consists of 18 packages of 737 classes as in JDK
1.8) and has great depth.

9
Swing’s Features
• Swing is written in pure Java (except a few classes) and
therefore is 100% portable.

• Swing components are lightweight, while the AWT components


are heavyweight (in terms of system resource utilization). Swing
components (JComponents) are written in Java. They are
generally not "weight-down" by complex GUI considerations
imposed by the underlying windowing subsystem.

• Swing components support pluggable look-and-feel. You can


choose between Java look-and-feel and the look-and-feel of the
underlying OS (Ex: Windows, UNIX or macOS).

10
Swing’s Features
• Swing supports mouse-less operation (i.e., it can operate
entirely using keyboard).

• Swing components support "tool-tips".

• Swing components are JavaBeans – a Component-based Model


used in Visual Programming (like Visual Basic). You can drag-
and-drop a Swing component into a "design form" using a "GUI
builder" and double-click to attach an event handler.

• Swing application uses AWT event-handling classes (in package


java.awt.event). Swing added some new classes in package
javax.swing.event, but they are not frequently used.

• Swing implements double-buffering and automatic repaint


batching for smoother screen repaint.

• Swing introduces JLayeredPane and JInternalFrame for creating


Multiple Document Interface (MDI) applications.
11
• Others - check the Swing website.
Commonly Used Methods
Method Description
add(Component c) Inserts a component on this
component.
setSize(int width, int height) Sets the size (width and height) of
the component.
setLayout(LayoutManager m) Defines the layout manager for the
component.
setVisible(Boolean status) Changes the visibility of the
component, by default false.
setTitle(String text) Sets the title for the component.

12
Using Swing API
• If you understood the AWT programming (in particular,
container/component and event-handling), switching over to
Swing (or any otherGraphics packages) is straight-forward.

• Swing's Components:
– Compared with the AWT component classes (in package
java.awt), Swing component classes (in package
javax.swing) begin with a prefix "J“.
Ex: JButton, JTextField, JLabel, JPanel, JFrame, or JApplet.
java.awt javax.swing
Frame JFrame
Panel JPanel
Canvas JPanel
Label JLabel
Button JButton
TextField JTextField
Checkbox JCheckbox
List JList 13
Choice JComboBox
Swing Class Hierarchy

• There are two groups of classes:


– Containers
– Components

• A container is used to hold components and it can also hold


containers because it is a (subclass of) component.
14
Swing's Top-Level and Secondary Containers

• Swing application requires a top-level container.

• There are three top-level containers in Swing:


1. JFrame: used for the application's main window (with an
icon, a title, minimize/maximize/close buttons, an optional
menu-bar, and a content-pane).

2. JDialog: used for secondary pop-up window (with a title, a


close button, and a content-pane).

3. JApplet: used for the applet's display-area (content-pane)


inside a browser’s window.

• Similar to AWT, there are secondary containers (such as


JPanel) which can be used to group and layout relevant
components.

15
Swing Controls
• JFrame control:
– The frame control is the basic ‘container’ for other controls.
It is the framework for a Java project. The title property
establishes the caption information. Every application we
build will start by building a class that extends the Jframe
control.

• JButton control:
– The button control is used to start some action. The text
property is used to establish the caption.

• JLabel control:
– The label control allows placement of formatted text
information on a frame (text property).

16
Swing Controls
• JTextField control:
– The text field control accepts a single line of typed
information from the user (text property).

• JTextArea control:
– The text area control accepts multiple lines of scrollable
typed information (text property).

• JCheckBox control:
– The checkbox control is used to provide a yes or no answer
to a question.
– Moreover, we can make multiple selection.

17
Swing Controls
• JRadioButton control:
– The radio button control is used to select from a mutually
exclusive group of options. You always work with a group of
radio buttons.

• JComboBox control:
– The Combo box controls are very common in GUI
applications. Users can choose an item from a drop-down
list (states, countries, product).

• JList control:
– A list control is like a combo box with the list portion always
visible. Multiple selections can be made with a list control.

18
Swing Controls
• JScroll control:
– A scroll bar control is used to select from a range of values.
The scroll bar is always “buddied” with another control
related to the scroll bar selection.

• JPasswordField control:
– A component that allows the editing of a single line of text
where the view indicates something was typed but does not
show the original characters.

19
JFrame Layout
• A window with a title bar, a resizable border, and possibly a
menu bar.
– A frame is not attached to any other surface.
– It has a content pane that acts as a container.
– The container uses BorderLayout by default.
– A layout manager, an instance of one of the layout classes,
describes how components are placed on a container.

– Size(300, 200); // width, height in pixels


– Visible(true);
– Location(50, 100); // x and y from upper-left corner
20
Create the User Interface
• An object called a layout manager determines how controls are
arranged in a frame. Some of the layout managers and their
characteristics are:

FlowLayout Places controls in successive rows, fitting as many as


possible in a given row.
BorderLayout Places controls against any of the four frame borders.

CardLayout Places controls on top of each other like a deck of


cards.
GridLayout Places controls within a specified rectangular grid.

GridBagLayout Places controls with a specified very flexible


rectangular grid.
BoxLayout Arranges controls either in a row or column.

SpringLayout Arranges controls with positions defined by sprints


and struts.

21
GridBagLayout
• Offers the nicest interface appearance.

• A frame is actually made up of several different panes.

• Controls are placed in the content pane of the frame.

• The GridBagLayout manager divides the content pane into a


grid of rows and columns:

– The top row is Row 0 and row number increases as you go down the
grid. The left column is Column 0 and column number increases as
you move to the right in the grid.

22
Stopwatch Application – Adding Controls

We will place these controls in a 3 x 3 array:


• startButton: • elapsedLabel :
– text Start Timing – text Elapsed Time (sec)
– gridx 0 – gridx 1
– gridy 0 – gridy 2
• stopButton : • startTextField :
– text Stop Timing – text [Blank]
– gridx 0 – columns 15
– gridy 1 – gridx 2
• exitButton : – gridy 0
– text Exit • stopTextField :
– gridx 0 – text [Blank]
– gridy 2 – columns 15
• startLabel : – gridx 2
– text Start Time – gridy 1
– gridx 1 • elapsedTextField :
– gridy 0 – text [Blank]
• stopLabel : – columns 15
– text End Time – gridx 2
23
– gridx 1 – gridy 2
– gridy 1
Stopwatch Application – Adding Controls
• Declare the nine controls (recall these lines go after the opening
left brace for the class definition):

• Establish the grid layout (inside the constructor):

24
Stopwatch Application – Adding Controls
• Set the position of the controls in the GridBagLayout grid
(inside the constructor):
– First, declare an object of type GridBagConstraints to allow
positioning.
– Place each control in the grid.
– To finalize placement of controls in the frame, execute a pack
method, pack().

25
Stopwatch Application – Adding Event
Methods
• We need to add event methods and their corresponding
listeners to our application.

• There are two ways to add listeners, one for AWT objects and
one for Swing objects. Listeners are added in the frame
constructor code.

• Java event listeners for AWT objects (primarily those for mouse
and keyboard inputs) are implemented using something called
adapters.
Ex: listen for the event when the user closes the window

• The adapter that implements events for the frame is called the
WindowAdapter and it works with the WindowListener.

26
Stopwatch Application – Adding Event
Methods
• In our case, we want to listen for the windowClosing event.

• For Swing components, like the button, label and text field,
event methods (actionPerformed) are added using the
ActionListener.

• For our stopwatch example, we will assume click events for the
three button controls.

27
Stopwatch Application – Adding Event
Methods
• Typically, the control event methods are usually placed after
the constructor method.

28
Stopwatch Application – Adding Event
Methods
• Before writing the control event methods, we should declare
three class level variables.

29
Stopwatch Application – Adding Event
Methods
• Now, we are ready to write the control event methods for the
three buttons.

30
Variables
• Variables must be properly named.

• Rules used in naming variables:


– They may include letters, numbers, and underscore (_), though the
underscore is rarely used.
– The first character must be a letter.
– You cannot use a reserved word (keywords used by Java).

• Meaningful variable names that help you (or other


programmers) understand the purpose of the information stored
by the variable.

• By convention, Java variable names begin with a lower case


letter. If a variable name consists of more than one word, the
words are joined together, and each word after the first begins
with an uppercase letter.
Ex: startingTime, interestValue, letter05, timeOfDay

31
Java Data Types
• Each variable is used to store information of a particular type.

• Java has a wide range of data types.

• You must always know the type of information stored in a particular


variable.

• boolean variables can have one of two different values: true or false
(reserved words in Java).

• If a variable stores a whole number (no decimal), there are three data
types available: short, int or long

Data Type Range


short -32,678 to 32,767

int -2,147,483,648 to 2,147,483,647

long -9,223,372,036,854,775,808 to
9,223,372,036,854,775,807

32
Java Data Types
• If a variable stores a decimal number, there are two data types: float or
double.

• The double uses twice as much storage as float, providing more precision
and a wider range.

Data Type Value


float 3.14

double 3.14159265359

• Java is a popular language for performing string manipulations. These


manipulations are performed on variables of type String. A string variable
is just that - a string (list) of various characters. In Java, string variable
values are enclosed in quotes.
Ex: “Java is fun!”

• Single character string variables have a special type, type char, for
character type. Char types are enclosed in single quotes.
Ex: ‘a’

33
Variable Declaration
• To explicitly declare a variable, you must first determine its
scope. Scope identifies how widely disseminated we want the
variable value to be.

• We will use three levels of scope:


– Loop level (are only available within a computation loop)

– Method level (are only available within a method)

– Class level (retain their value and are available to all


methods within that class)

34
Arrays
• It provides a way to store a large number of variables under the same
name.

• Each variable, called an element, in an array must have the same data
type, and they are distinguished from each other by an array index
(contained within square brackets).

• We usually declare and create arrays in the same line of code. For
example, to declare an integer array named 'item', with dimension 9, at
the method level, we use:
int[] item = new int[9];

• The index on an array variable begins at 0 and ends at the dimensioned


value minus 1.
item[0] to item[8]
item[8] = newValue;
sum = item[0] + item[1] + item[3];

• It is also possible to have arrays of controls. For example, to have 20


button types available use:
Button[] myButtons = new Button[20];

35
Swing Counter Example

36
Any Questions?

37
Java AWT
• Java AWT (Abstract Window Toolkit) is an API to develop
Graphical User Interface (GUI) or windows-based applications in
Java.

• Java AWT components are platform-dependent


– Components are displayed according to the view of
operating system (OS).

• AWT is heavy weight


– Its components are using the resources of underlying
operating system (OS).

38
Swing components are JavaBeans
• JavaBeans is a reusable class code element often applied on
java-based software application programming.

• The JavaBeans class components are methods, events,


properties, and persistence.

• This class type is advantageous due to its notable reusability


characteristics, enables object communication, is platform-
independent, has shorter time consumption, requires lesser
manual efforts, etc.

39
The Content-Pane of Swing's Top-Level Container

• The JComponents shall not be added onto the top-level


container (e.g., JFrame, JApplet) directly because they are
lightweight components.

• The JComponents must be added onto the so-called content-


pane of the top-level container. Content-pane is in fact a
java.awt.Container that can be used to group and layout
components.

40

You might also like