Java GUI Programming.: A Quick-Start Guide To Building Swing Applications. With Examples and Pictures. CS 349 Winter 2016
Java GUI Programming.: A Quick-Start Guide To Building Swing Applications. With Examples and Pictures. CS 349 Winter 2016
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!” (www.tiobe.com)
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".
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.
http://viralpatel.net/blogs/java-virtual-machine-an-inside-story/
7
Java Platform
Installation
Parts of the platform
Building and deploying applications
8
Installing the Platform • There are two main Java implementations
– Oracle Java: https://docs.oracle.com/javase/8/
– Open JDK: FOSS implementation for Linux.
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 CountArgsApp.java
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
• 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 Bicycle.java
ß 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.
20
Pointer Gotchas! • Arrays are objects, so:
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.
http://www.ibm.com/developerworks/library/j-jtp10283/
23
• Static method that instantiates the pa
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
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 ShadowTest.this.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 Animals1.java
The Animal
class is abstract,
and cannot be
instantiated.
” 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”).
• 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.
Animals2.java
interface Driveable {
public void accelerate();
public void brake();
public int getSpeed();
}
33
Extended Example Bikes1.java – classes
Bikes2.java - 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.
37
Common Classes/Packages Package Classes Description
(Examples)
java.awt Color, Graphics, Contains all of the classes for
Graphics2D, event. creating user interfaces and for
painting graphics and images.
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.
45
Simple Swing Example
46
BasicForm1.java
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
BasicForm2.java
BasicForm3.java
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 java.awt.Graphics 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 SimpleDraw4.java
54
Next? • A1
– Canvas should be a top-level object, derived
from JComponent
– Drawables can be a java.util.ArrayList.
– 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:
http://www.oracle.com/technetwork/java/javase/
• Java 8 Tutorials:
http://docs.oracle.com/javase/tutorial/java/index.html