Introduction to Java

snottybugbearΛογισμικό & κατασκευή λογ/κού

3 Νοε 2013 (πριν από 4 χρόνια και 6 μήνες)

109 εμφανίσεις

©1995-2007Skilltop Technology Limited. All rights reserved.
Introduction to Java
The Java 2 Standard Edition Platform (J2SE 1.4.2)
Session 6 –Java User Interface Design with Swing
©1995-2007Skilltop Technology Limited.
Overview for night 6 –Building GUIs with Swing
What should you be able to do after this lecture:

Understand the fundamentals of how GUIs are built
using the Swing classes

Display a simple form on the screen

Add labels, buttons and text entry areas to the form

Retrieve values from the components on the form

Invoke code when buttons are pushed

Update the form with new values

Arrange components on a form
©1995-2007Skilltop Technology Limited.
Building GUIs with Swing –the SwingSetDemo

The SwingSetdemo is installed with the JDK.


Has source browser built into it, so you can see the code as
you play with the demo

Will spend about 20 minutes walking through the demo,
explaining what you’re seeing.

The key to the demo is to not get overwhelmed –There is a
lotyou can do with Swing, and the SwingSetdemo is huge.
©1995-2007Skilltop Technology Limited.
Building GUIs with Swing –Evolution in action

Why does J2SE 1.4.2 ship with two sets of mostly
incompatible graphics libraries?

Java 1.0 AWT built in 30 days, and it shows

Java 1.1 AWT significantly improved, but GUI not
finished yet

Java 2 Swing: vastly improved

Older browser support requires that Java maintains it’s
backwards compatibility, hence the survival of AWT.

Historical note –Swing was the internal code name at Sun
for their AWT replacement. When they decided to ship,
they liked the name, and stuck with it.
©1995-2007Skilltop Technology Limited.
Building GUIs with Swing –
The Fundamentals

All of the Java based GUIs you are going to
encounter are made up of the same
fundamental building blocks. Once you
understand these, you should be able to
build fairly complex GUIs without much
trouble. These building blocks are:
•Events and Event listeners
©1995-2007Skilltop Technology Limited.
Building GUIs with Swing –
The Fundamentals

All Swing classes live in or under the package javax.swing.

Some Swing classes use classes from the package java.awt,
or one of it’s sub-packages.

This re-use is done to take advantage of years of
development that went into the AWT packages, and to
avoid having duplicate code where possible.

Primary re-use that will impact yourcode is through event

Other reuse is through inheiritance. Browse through the
Swing APIs on line to see how the classes in the swing
packages extend the AWT classes.
©1995-2007Skilltop Technology Limited.
Building GUIs with Swing –
The Fundamentals

Obviously enough, you put things into

JFrameis a top level container, which
represents a window on the screen.

JPanelis an internal container that is used
to group related components. JPanelshave
a number of properties, such as size,
border, title.
©1995-2007Skilltop Technology Limited.
Building GUIs with Swing –
The Fundamentals

A component is something you put into a
container. Containers themselves are
components, which means that they can also be
put into other containers

Most of the time, you’ll be adding components
such as JLabel, JButton, JTextFieldetc. to your

Most components are there to either display
information, or to receive user input
©1995-2007Skilltop Technology Limited.
Building GUIs with Swing –
The Fundamentals
Events and Event Listeners.

Components have lists of listeners that they
notify when certain types of events occur

JButtonsfor example have ActionListeners
that will be sent an ActionEventwhen the
button is pushed.

You add a class that implements the
appropriate listener to the list of listeners
that the component maintains.
©1995-2007Skilltop Technology Limited.
Building GUIs with Swing –
The Fundamentals

Components are not just strewn willy-nilly on the screen,
but are organized in particular ways

Layout Managers control how components are placed,
relative to each other, the container they are in, and their

Layout Managers also control how components are
positioned and resized if their container is resized

FlowLayoutadds components from left to right until it
runs out of room, then starts on the next row.

Border layout divides the screen into 5 areas (North,
South, West, East and Center) and allows you to add one
component to each of these areas
©1995-2007Skilltop Technology Limited.
Building GUIs with Swing –time for a break
10 minute break
©1995-2007Skilltop Technology Limited.
Building GUIs with Swing –The Heirarchies

There are two primary heirarchiesto
understand when building GUIs with Swing

First is the class hierarchy
•This is your usual Java inheiritancehierarchy
•Easiest to understand by browsing the API

Second is the containment hierarchy
•This covers the Container –Contained
relationship between Containers and the
Components that they contain
©1995-2007Skilltop Technology Limited.
Building GUIs with Swing –the Containment Hierarchy

An example:

There are four components in this GUI:
•A JFramewhich is the top level container. It directly contains the
•A JPanelused to organize the next two components
•A JButtonwhich is a base level component –you cannot add other
components to it
•A JLabelwhich is also a base level component –you cannot add other
components to a JLabel
©1995-2007Skilltop Technology Limited.

the containment hierarchy for this GUI can be seen below:

Note the inclusion of a content pane. You do not add
components directly to a Jframe, but rather to it’s content
Building GUIs with Swing –theJFrameHierarchy
©1995-2007Skilltop Technology Limited.
Building GUIs with Swing –The Code

This code snippet creates the JFrame, adds the
components to a JPanel, then adds the JPanelto
the content pane of the JFrame.
frame = new JFrame(“SwingApplication”);
panel = new JPanel();
button = new JButton(“I’ma Swing
label = new JLabel(“Numberof clicks:0”);
©1995-2007Skilltop Technology Limited.
Building GUIs with Swing –JFrame

javax.swing.JFrameis notshown when created –you must
invoke setVisible(true)

You must also the frame to adjust it’s size, or you will get a
very tiny JFrameby default. Use pack() to do so.

Add things to the frames content pane, not to the frame
Jframef = new JFrame(“Title”);
f.pack(); // try omitting this
©1995-2007Skilltop Technology Limited.
Building GUIs with Swing –
Things with Text

There are a number of text components –
we’re going to cover three of them now.

JLabel–used for display of static text (and

JTextField–used for single line text entry

JTextArea–used for display and editing of
multiple lines of text
©1995-2007Skilltop Technology Limited.
Building GUIs with Swing –JLabel

javax.swing.JLabelis noteditable, but it is

Three basic varitiesof JLabel:
•Both an Icon and Text

Basic text is most often used
JLabelmyLabel= new JLabel(“Label”);
©1995-2007Skilltop Technology Limited.
Building GUIs with Swing –JTextField

javax.swing.JTextFieldis editable by default,
but can be changed to be non-editable

All text in the JTextFieldhas the same font.
JTextFieldf = new JTextField(7);
String s = f.getText();
©1995-2007Skilltop Technology Limited.
Building GUIs with Swing –JTextArea

javax.swing.JTextAreais editable by default,
but can be changed to be non-editable

You specify a number of rows and columns
when you build a JTextArea
JTextAreaa = new JTextArea(7,3);
f.setText(“Line1\nLine 2\nL 3”);
String s = f.getText();
©1995-2007Skilltop Technology Limited.
Building GUIs with Swing –JButton

javax.swing.JButtoncan display a label, an icon or both.

You add implementorsof the interface
java.awt.event.ActionListenerto JButtonsto have code
invoked when the JButtonis pressed.
// MyListenerimplements ActionListener
MyListenerlistener = new MyListener();
JButtonb = new JButton(“Button”);
// When JButtonis pressed,
// actionPerformed() is called on listener
©1995-2007Skilltop Technology Limited.
Building GUIs with Swing –Properties

Most JComponentshave properties associated with

Look for setXand getX(or isX) pairs in the API

Common properties:
•Font–setFont() andgetFont()
•Text–setText() andgetText()
•Colour–setForeground() andsetBackground()
©1995-2007Skilltop Technology Limited.
Building GUIs with Swing –
Event Handling

Every time the user types a character, moves the mouse or
pushes a mouse button, an event occurs.

Any object can be notified of the event. The class needs to:
•implement the appropriate interface and
•be registered as an event listener on a component by calling the
appropriate addXListenermethod on the component.

Swing components can generate many kinds of events
•Check the API for details
•look for addXListenermethods
•Don’t forget to check the super class methods
©1995-2007Skilltop Technology Limited.
Building GUIs with Swing –
Event Handling Example
import javax.swing.*;
import java.awt.event.*;
public class MyListenerimplements ActionListener{
public void actionPerformed(ActionEvente) {
System.out.println(“Buttonwas pushed”);
public static void main(String[] args) {
JFrameframe = new JFrame(“Example”);
JButtonbutton = new JButton(“Button”);
MyListenerlistener = new MyListener();
frame.pack(); frame.setVisible(true);
©1995-2007Skilltop Technology Limited.
Building GUIs with Swing –
Layout Managers

Java uses the concept of a Layout Manager to
indicate how components are arranged in a

There are many layout managers supplied with
the 1.4.2 SDK

We’re going to look at two of them
©1995-2007Skilltop Technology Limited.
Building GUIs with Swing –FlowLayout

FlowLayoutadds items on the current row until it runs
out of room, then starts on the next row.

Items will naturally take up as much space as they need

You can see this in this example taken from the Swing
Tutorial –the buttons take up as much room as possible.

FlowLayoutis the defaulthat you get if you do not specify
a layout manager.
©1995-2007Skilltop Technology Limited.
Building GUIs with Swing –BorderLayout

BorderLayoutgives you 5 locations you can add
components to.

Prior to 1.4, the preferred names for the areas were
are still supported, but the new names are preferred.
©1995-2007Skilltop Technology Limited.
Building GUIs with Swing –BorderLayout

In 1.4, the preferred names for the areas are

You first set the layout to BorderLayout, then add
components to a specific area.
import javax.swing.*;
import java.awt.*;
JPanelp = new JPanel();
p.add(newJButton("Okay"), BorderLayout.CENTER);