Java GUI Programming.
A quick-start guide to building Swing applications.
With examples and pictures.
CS 349
Winter 2016
1
Introduction
Background
Design goals
2
Background • Designed by James Gosling
• Released by Sun Microsystems in 1995.
– Originally a proprietary license, but made open
source under GNU GPL in 2007.
– Sun and Java acquired by Oracle in 2010.
• General-purpose, portable language.
– Cross-platform, and able to scale from small
devices to large applications.
• Broadly adopted, and extremely successful.
– “Java is TIOBE's Programming Language of
2015!” ([Link])
3
4
Design Goals Five primary design goals:
1. It must be "simple, object-oriented, and
familiar".
2. It must be "robust and secure".
3. It must be "architecture-neutral and
portable".
4. It must execute with "high performance".
5. It must be "interpreted, threaded, and
dynamic".
- Gosling, “The Java Language Environment”
5
Object Oriented • C++ syntax
– Meant to be familiar to legions of C++
developers that would migrate to Java.
• Class-based, object-oriented design.
– Explicitly object-oriented
– Cannot build procedural applications!
• Extensive class libraries included
– Cross-platform!
– Support for everything from threading to
database access to building user interfaces.
– This makes Java unique; many languages rely
on third-party libraries.
6
Java Virtual Machine (JVM) • Portability is achieved through virtualization
– Java compiles to bytecode (IR).
– Bytecode is executed
by a Java virtual
machine (JVM) on the
target platform.
– Interpreted bytecode is
slower than native code
BUT just-in-time
compilation can give
near-native
performance.
[Link]
7
Java Platform
Installation
Parts of the platform
Building and deploying applications
8
Installing the Platform • There are two main Java implementations
– Oracle Java: [Link]
– Open JDK: FOSS implementation for Linux.
• JRE: standalone JVM installation (runtime).
• JDK: JRE plus development tools and libraries.
– This gives you command-line tools (javac
compiler and java runtime).
• Third-party support is excellent
– Editor support in VIM, Sublime, etc.
– IDEs like IntelliJ, Eclipse.
9
Java Platform (JDK) • Includes tools, and libraries - everything from
threading, to database access, to UI toolkits – all
cross platform and portable.
10
Building Applications • Source code is first written in plain text files
ending with the .java extension (one class per
source file).
• Source files are then compiled into .class files
(bytecode) by the javac compiler.
11
Deployment • Class files (.class) can be executed on any
platform with an appropriate JVM.
• Often applications include many class files,
which we bundle into a JAR (.jar) file (basically a
zip file with metadata).
12
Command-Line Tools To compile on the command line:
$ javac [Link]
To run compiled app:
$ java CountArgsApp one two three
You provided 3 args.
13
The Java Programming Language
Language features
Classes and objects
Libraries
Program structure
14
Standard Language Features • Java uses the same syntax as C++ in most
situations, so the style will be familiar.
– Variables
• Standard naming conventions apply
– Operators
• Equality: == !=
• Assignment: = += -= and so on.
• Logical: not (!) and (&&) or (||) ternary(? :)
– Structure
• { } to nest blocks of code
• Control flow: if… else, while, break/continue.
15
Java Simple Types: see C++ Type Size Format Range
boolean ≤1 byte — false, true
byte 1 byte signed integer ±127
short 2 bytes signed integer ±32,767
char 2 bytes unsigned integer 0 to +65,535
int 4 bytes signed integer ±2,147,483,647
long 8 bytes signed integer … Umm, really big
float 4 bytes floating point ±1038
double 8 bytes floating point ±10308
Primitive types also have corresponding Object types (e.g.
Boolean class for booleans, Integer for integers and so on.)
16
Object-Oriented Programming • Java is class-based and object-oriented
– Difficult to fall back to procedural programming;
language is not well-designed for that.
• Class: type
• Object: instance of that type
– Create a new object with the new keyword.
– Objects contain both data (fields) and behavior
(methods).
17
Instantiating an Object [Link]
ß Create an instance
No explicit destructor!
18 Do we need one?
Instantiating Objects • In Java,
– Primitive types are allocated on the stack,
passed by value.
– Objects are allocated on the heap, passed by
reference
• Technically, value of address passed on the
stack, but behaves like pass-by-reference.
Both refer to the same
memory on the heap
• Practically, this means that you don’t need to
worry about pointer semantics in parameter
passing.
19
Consider Class Bicycle
ß Instantiated on the heap
20
Pointer Gotchas! • Arrays are objects, so:
• First line allocates an array on the heap with
space for 10 Bicycle pointers (40 bytes), but all
Bicycle pointers are still null
• for loop allocates space for Bicycle to each
entry in bikeStore array
21
Pointer Gotchas • Note the following
int[] myInts = new int[10];
myInts[0]=15;
• Error or no?
– Why?
22
Garbage Collection (GC) • In Java, there’s no need to free memory
– Garbage collection runs periodically and frees
up memory that’s not in use.
– JVM attempts to do this without impacting
performance.
[Link]
23
• Static method that instantiates the pa
Structure of a Program [Link]
24
Java OO Features Familiar OO features still apply to Java:
Feature Description
Classes, objects Types, instances of those types
Dynamic dispatch Objects determine type at runtime,
instead of being static typed.
Encapsulation Data hiding
Composition Nesting objects
Inheritance Hierarchy of is-a class relationships
Polymorphism Calling code is agnostic in terms of
whether an object is a derives or
base class.
25
Java Class Structure
Variables
Class variables Shared among all static
objects.
Instance variables Belong to an object
instance.
Member variables All variables belonging
to an object.
Methods
Class methods Shared among all static
objects.
Instance methods Belong to an object
instance.
26
Nested Classes Classes can be nested as inner classes. Watch scope!
x = 23
this.x = 1
27 [Link].x = 0
Inheritance • Inheritance: increasing code reusability by
allowing a class to inherit some of it’s behavior
from a base class (“is a” relationship).
– Classes inherit common attributes and
behavior from base classes.
– e.g. “Mountain Bike” is-a “Bike”. Bike
• Common: speed, gear
• Unique: engine Mountain
– Use extends keyword. Bike
28
Subtype Polymorphism [Link]
The Animal
class is abstract,
and cannot be
instantiated.
It’s talk() method
is abstract, so
derived classes
must override it.
” Meow! “
“ Woof! “
29
Single Inheritance • Java only supports single inheritance!
• In practice, this simplifies the language.
• See the “Diamond
Problem” for one example
of multiple inheritance
being a hard problem.
• Solutions to this problem
vary by language; Java just
doesn’t let you do it.
• It’s very common to derive an existing Java
Platform class and override behavior.
• All classes have Object as their ultimate base
class (implicit).
30
Interfaces • An interface represents a set of methods that
must be implemented by a class (“contract”).
• Similar to pure abstract classes/methods.
– Can’t be instantiated
– Class implementing the interface must
implement all methods in the interface.
– Use implements keyword.
• In Java,
– extend a class to derive functionality from it
– implement an interface when you want to
31
enforce a specific API.
Interfaces Example • We can replace the abstract class/method with
an interface.
– Polymorphism still applies to interfaces.
[Link]
Note that we’re
treating the
interface, Pet,
32
as a type
Interfaces Example • You can (and will often) mix approaches.
– e.g. Drivable interface could be applied to any type
of drivable vehicle, including our Bike class
hierarchy.
interface Driveable {
public void accelerate();
public void brake();
public int getSpeed();
}
// implement interface only
class Car implements Driveable {}
class Train implements Driveable {}
// derive from base class, and implement interface
class Motorcycle extends Bike implements Driveable {}
33
Extended Example [Link] – classes
[Link] - interfaces
34
Java Class Libraries
Packages
JFrame
Swing
35
Java Platform (JDK) • The Java Platform includes extensive cross-
platform libraries to do everything from threading
to database queries to user-interfaces.
36
Java Class Library • Classes are grouped into packages
(namespaces, to avoid collision).
• Use the import keyword to import the package
– This is how you include bundled Java libraries.
• To assign your source code to a package, use
the package keyword at the top of source files.
• Typically, package = subdirectory
– e.g. “graphics” package is in subdirectory of
the same name
– alt. it can be included in a JAR file.
• For simplicity, samples and assignments won’t
normally do this.
37
Common Classes/Packages Package Classes Description
(Examples)
[Link] Color, Graphics, Contains all of the classes for
Graphics2D, event. creating user interfaces and for
painting graphics and images.
[Link] JFrame, JButton, Provides a set of "lightweight" (all-
JList, JToolbar Java language) components that
works the same on all platforms.
[Link] File, FileReader, Provides for system input and output
FileWriter, through data streams, serialization
InputStream and the file system.
[Link] Boolean, Integer, Provides classes that are
String, System, fundamental to the design of the
Thread, Math Java programming language.
[Link] ArrayList, HashMap, Contains the collections framework,
Observable legacy collection classes, event
model,…
Java 8 API Specification:
38 [Link]
Java Class Hierarchy • Implicit class hierarchy
– All classes in Java are derived from the Object class in
[Link] defines and implements common class
behavior
• e.g. clone(), toString(), finalize() methods
– Classes you write inherit this basic behavior.
39
Building Swing Interfaces
Creating a window
Swing components
Adding listeners
40
Approaches • Java has four (!) user-interface libraries,
containing different types of widgets.
1. AWT was introduced with Java in 1995
• “Heavyweight” with platform-specific widgets.
• AWT applications were limited to common-
functionality that existed on all platforms.
2. Swing supplanted AWT in 1997
• “Lightweight”, full widget implementation.
3. Java FX is in-development.
• Intended for rich desktop + mobile apps.
4. SWT developed as part of Eclipse
• Hybrid that uses native, when available.
•41 We use Swing for building cross-platform apps.
Aside: Understanding Widgets • GUI Toolkits contain sets of widgets that you can
use to build applications, and enable event
delivery to widgets
• So … what is a widget?
• A widget (also graphical control element or
control) is an element of interaction in a
graphical user interface (GUI), such as a button
or a scroll bar. Controls are software
components that a computer user interacts with
through direct manipulation to read or edit
information about an application. User interface
libraries contain a collection of widgets and the
logic to render these.
– Wikipedia (AKA the font of all knowledge)
Widget • Child windows are essentially widgets
– Widget is a generic name for parts of an
interface that have their own behavior:
buttons, progress bars, sliders, drop-
down menus, spinners, file dialog
boxes, …
– widgets also called “components”,
“controls”
– Can have their own appearance
– Receive and interpret their own events
– Put into libraries (toolkits) for reuse
Widget from Wow Wow Wubbzy
43 CS349 | Multiple Windows
Java AWT, Java SWT, Java Swing • Each operating system implements a set of
native widgets
– What you would expect: buttons, checkboxes,
combo boxes, etc., etc.
– But each OS’s native widget set had
idiosyncrasies
• Java’s cross-platform goal required a decision:
– AWT, lowest common denominator
– Swing, roll your own for the JVM.
– SWT, platform specific
• Pluses and minuses to each approach.
– What are they?
Using Swing Components • How to use Swing
– Create a top-level application window, with a
Swing container class (JFrame or JDialog).
– Add Swing components directly to this window.
• Typically, you create a smaller container (like
a JPanel) and add components to the panel.
• This makes dynamic layouts easier (more on
that later in the course!)
– Add listeners for all events, like keyboard
(press), mouse (down, up, move)
– Make components update and paint
themselves based on input/events.
45
Simple Swing Example
46
[Link]
Listeners • How do we interact with components?
– For each component, add listeners for events
that you want that component to process.
• Java has interfaces for each type of listener.
• To use them, write a class that implements this
interface, and override the appropriate methods.
47
Using Listeners
[Link]
What’s wrong with this
approach?
48
Adapters vs. Listeners • Java also has adapters, which are base classes
with empty listeners.
– Extend the adapter and override the event
handlers that you care about; avoids bloat.
[Link]
What’s wrong with this
approach?
49
Anonymous Inner Classes • We really, really don’t want to create custom
adapters for every component.
– Solution? Anonymous inner class.
[Link]
50
Swing UI Thread • Swing needs to make sure that all events are
handled on the Event Dispatch thread.
• If you just “run” your application from main, as we’ve
been doing in the examples, you risk the main
program accepting input before the UI is
instantiated!
– Use invokeLater() to safely create the UI.
– We’ll discuss in greater detail later in the course.
51
Drawing in Java
Graphics object
paint() method
52
Graphics and painting • You can also draw using a series of primitive
operators and the [Link] object.
– Derive your top-level canvas from JComponent
– Override the paint() method
– Use the Graphics objects methods to set
colors, draw lines, and so on.
53
Drawing Example [Link]
54
Next? • A1
– Canvas should be a top-level object, derived
from JComponent
– Drawables can be a [Link].
– Override each components paint method, and
let it paint itself based on state (e.g. the ball
should know its position, and be able to draw
itself in the correct position; blocks know where
they’re positioned).
– Event loop? Likely want some type of timer to
tick and update the game at a constant rate
(e.g. force the ball to move every 1/30 of a
second).
55
Resources • Java 8:
[Link]
• Java 8 SE Platform Reference:
[Link]
[Link]
• Java 8 Tutorials:
[Link]
• Java Language Whitepaper:
[Link]
• Jetbrains Student Licenses (IntelliJ):
[Link]
56