java gui programming. - university of waterloocs349/w16/slides/2.1-java-part1.pdf · (examples)...

41
Java GUI Programming. A quick-start guide to building Swing applications. With examples and pictures. CS 349 Winter 2016 1

Upload: others

Post on 18-Mar-2020

16 views

Category:

Documents


1 download

TRANSCRIPT

Page 1: Java GUI Programming. - University of Waterloocs349/w16/slides/2.1-java-part1.pdf · (Examples) Description java.awt Color, Graphics, Graphics2D, event. Contains all of the classes

Java GUI Programming.

A quick-start guide to building Swing applications. With examples and pictures.

CS 349 Winter 2016

1

Page 2: Java GUI Programming. - University of Waterloocs349/w16/slides/2.1-java-part1.pdf · (Examples) Description java.awt Color, Graphics, Graphics2D, event. Contains all of the classes

Introduction

BackgroundDesign goals

2

Page 3: Java GUI Programming. - University of Waterloocs349/w16/slides/2.1-java-part1.pdf · (Examples) Description java.awt Color, Graphics, Graphics2D, event. Contains all of the classes

Bac

kgro

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

Page 4: Java GUI Programming. - University of Waterloocs349/w16/slides/2.1-java-part1.pdf · (Examples) Description java.awt Color, Graphics, Graphics2D, event. Contains all of the classes

4

Page 5: Java GUI Programming. - University of Waterloocs349/w16/slides/2.1-java-part1.pdf · (Examples) Description java.awt Color, Graphics, Graphics2D, event. Contains all of the classes

Des

ign

Goa

ls 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

Page 6: Java GUI Programming. - University of Waterloocs349/w16/slides/2.1-java-part1.pdf · (Examples) Description java.awt Color, Graphics, Graphics2D, event. Contains all of the classes

Obj

ect O

rient

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

Page 7: Java GUI Programming. - University of Waterloocs349/w16/slides/2.1-java-part1.pdf · (Examples) Description java.awt Color, Graphics, Graphics2D, event. Contains all of the classes

Java

Virt

ual M

achi

ne (J

VM) • 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

Page 8: Java GUI Programming. - University of Waterloocs349/w16/slides/2.1-java-part1.pdf · (Examples) Description java.awt Color, Graphics, Graphics2D, event. Contains all of the classes

Java Platform

InstallationParts of the platformBuilding and deploying applications

8

Page 9: Java GUI Programming. - University of Waterloocs349/w16/slides/2.1-java-part1.pdf · (Examples) Description java.awt Color, Graphics, Graphics2D, event. Contains all of the classes

Inst

allin

g th

e Pl

atfo

rm • There are two main Java implementations– Oracle Java: https://docs.oracle.com/javase/8/– Open JDK: FOSS implementation for Linux.

• JRE: standalone JVM installation (runtime).• JDK: JRE plus development tools and libraries.

– This gives you command-line tools (javaccompiler and java runtime).

• Third-party support is excellent– Editor support in VIM, Sublime, etc.– IDEs like IntelliJ, Eclipse.

9

Page 10: Java GUI Programming. - University of Waterloocs349/w16/slides/2.1-java-part1.pdf · (Examples) Description java.awt Color, Graphics, Graphics2D, event. Contains all of the classes

Java

Pla

tform

(JD

K) • Includes tools, and libraries - everything from

threading, to database access, to UI toolkits – all cross platform and portable.

10

Page 11: Java GUI Programming. - University of Waterloocs349/w16/slides/2.1-java-part1.pdf · (Examples) Description java.awt Color, Graphics, Graphics2D, event. Contains all of the classes

Bui

ldin

g A

pplic

atio

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

Page 12: Java GUI Programming. - University of Waterloocs349/w16/slides/2.1-java-part1.pdf · (Examples) Description java.awt Color, Graphics, Graphics2D, event. Contains all of the classes

Dep

loym

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

Page 13: Java GUI Programming. - University of Waterloocs349/w16/slides/2.1-java-part1.pdf · (Examples) Description java.awt Color, Graphics, Graphics2D, event. Contains all of the classes

Com

man

d-Li

ne T

ools To compile on the command line:

$ javac CountArgsApp.java

To run compiled app:$ java CountArgsApp one two three

You provided 3 args.

13

Page 14: Java GUI Programming. - University of Waterloocs349/w16/slides/2.1-java-part1.pdf · (Examples) Description java.awt Color, Graphics, Graphics2D, event. Contains all of the classes

The Java Programming Language

Language featuresClasses and objectsLibrariesProgram structure

14

Page 15: Java GUI Programming. - University of Waterloocs349/w16/slides/2.1-java-part1.pdf · (Examples) Description java.awt Color, Graphics, Graphics2D, event. Contains all of the classes

Stan

dard

Lan

guag

e Fe

atur

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

Page 16: Java GUI Programming. - University of Waterloocs349/w16/slides/2.1-java-part1.pdf · (Examples) Description java.awt Color, Graphics, Graphics2D, event. Contains all of the classes

Java

Sim

ple

Type

s: s

ee C

++ Type Size Format Rangeboolean ≤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

16

Primitive types also have corresponding Object types (e.g. Boolean class for booleans, Integer for integers and so on.)

Page 17: Java GUI Programming. - University of Waterloocs349/w16/slides/2.1-java-part1.pdf · (Examples) Description java.awt Color, Graphics, Graphics2D, event. Contains all of the classes

Obj

ect-O

rient

ed P

rogr

amm

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

Page 18: Java GUI Programming. - University of Waterloocs349/w16/slides/2.1-java-part1.pdf · (Examples) Description java.awt Color, Graphics, Graphics2D, event. Contains all of the classes

Inst

antia

ting

an O

bjec

t

No explicit destructor!Do we need one?18

Bicycle.java

ß Create an instance

Page 19: Java GUI Programming. - University of Waterloocs349/w16/slides/2.1-java-part1.pdf · (Examples) Description java.awt Color, Graphics, Graphics2D, event. Contains all of the classes

Inst

antia

ting

Obj

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

Page 20: Java GUI Programming. - University of Waterloocs349/w16/slides/2.1-java-part1.pdf · (Examples) Description java.awt Color, Graphics, Graphics2D, event. Contains all of the classes

Con

side

r Cla

ss B

icyc

le

20

ß Instantiated on the heap

Page 21: Java GUI Programming. - University of Waterloocs349/w16/slides/2.1-java-part1.pdf · (Examples) Description java.awt Color, Graphics, Graphics2D, event. Contains all of the classes

Poin

ter G

otch

as! • Arrays are objects, so:

21

• 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

Page 22: Java GUI Programming. - University of Waterloocs349/w16/slides/2.1-java-part1.pdf · (Examples) Description java.awt Color, Graphics, Graphics2D, event. Contains all of the classes

Poin

ter G

otch

as • Note the followingint[] myInts = new int[10];myInts[0]=15;

• Error or no?– Why?

22

Page 23: Java GUI Programming. - University of Waterloocs349/w16/slides/2.1-java-part1.pdf · (Examples) Description java.awt Color, Graphics, Graphics2D, event. Contains all of the classes

Gar

bage

Col

lect

ion

(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

Page 24: Java GUI Programming. - University of Waterloocs349/w16/slides/2.1-java-part1.pdf · (Examples) Description java.awt Color, Graphics, Graphics2D, event. Contains all of the classes

Stru

ctur

e of

a P

rogr

am

• Static method that instantiates the parent class.

24

Bicycle.java

Page 25: Java GUI Programming. - University of Waterloocs349/w16/slides/2.1-java-part1.pdf · (Examples) Description java.awt Color, Graphics, Graphics2D, event. Contains all of the classes

Java

OO

Fea

ture

s 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

Page 26: Java GUI Programming. - University of Waterloocs349/w16/slides/2.1-java-part1.pdf · (Examples) Description java.awt Color, Graphics, Graphics2D, event. Contains all of the classes

Java

Cla

ss S

truc

ture

VariablesClass variables Shared among all

objects.static

Instance variables Belong to an object instance.

Member variables All variables belonging to an object.

MethodsClass methods Shared among all

objects.static

Instance methods Belong to an object instance.

26

Page 27: Java GUI Programming. - University of Waterloocs349/w16/slides/2.1-java-part1.pdf · (Examples) Description java.awt Color, Graphics, Graphics2D, event. Contains all of the classes

Nes

ted

Cla

sses Classes can be nested as inner classes. Watch scope!

x = 23this.x = 1

ShadowTest.this.x = 027

Page 28: Java GUI Programming. - University of Waterloocs349/w16/slides/2.1-java-part1.pdf · (Examples) Description java.awt Color, Graphics, Graphics2D, event. Contains all of the classes

Inhe

ritan

ce • 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”.

• Common: speed, gear• Unique: engine

– Use extends keyword.

Bike

Mountain Bike

28

Page 29: Java GUI Programming. - University of Waterloocs349/w16/slides/2.1-java-part1.pdf · (Examples) Description java.awt Color, Graphics, Graphics2D, event. Contains all of the classes

Subt

ype

Poly

mor

phis

m

” Meow! ““ Woof! “

Animals1.java

The Animalclass is abstract,

and cannot be instantiated.

It’s talk() method is abstract, so

derived classes must override it.

29

Page 30: Java GUI Programming. - University of Waterloocs349/w16/slides/2.1-java-part1.pdf · (Examples) Description java.awt Color, Graphics, Graphics2D, event. Contains all of the classes

Sing

le In

herit

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

Page 31: Java GUI Programming. - University of Waterloocs349/w16/slides/2.1-java-part1.pdf · (Examples) Description java.awt Color, Graphics, Graphics2D, event. Contains all of the classes

Inte

rfac

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

enforce a specific API.31

Page 32: Java GUI Programming. - University of Waterloocs349/w16/slides/2.1-java-part1.pdf · (Examples) Description java.awt Color, Graphics, Graphics2D, event. Contains all of the classes

Inte

rfac

es E

xam

ple • We can replace the abstract class/method with

an interface.– Polymorphism still applies to interfaces.

Animals2.java

Note that we’re treating the

interface, Pet, as a type32

Page 33: Java GUI Programming. - University of Waterloocs349/w16/slides/2.1-java-part1.pdf · (Examples) Description java.awt Color, Graphics, Graphics2D, event. Contains all of the classes

Inte

rfac

es E

xam

ple

interface Driveable {public void accelerate();public void brake();public int getSpeed();

}

// implement interface onlyclass Car implements Driveable {}class Train implements Driveable {}

// derive from base class, and implement interfaceclass Motorcycle extends Bike implements Driveable {}

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

33

Page 34: Java GUI Programming. - University of Waterloocs349/w16/slides/2.1-java-part1.pdf · (Examples) Description java.awt Color, Graphics, Graphics2D, event. Contains all of the classes

Exte

nded

Exa

mpl

e Bikes1.java – classesBikes2.java - interfaces

34

Page 35: Java GUI Programming. - University of Waterloocs349/w16/slides/2.1-java-part1.pdf · (Examples) Description java.awt Color, Graphics, Graphics2D, event. Contains all of the classes

Java Class Libraries

PackagesJFrameSwing

35

Page 36: Java GUI Programming. - University of Waterloocs349/w16/slides/2.1-java-part1.pdf · (Examples) Description java.awt Color, Graphics, Graphics2D, event. Contains all of the classes

Java

Pla

tform

(JD

K) • The Java Platform includes extensive cross-

platform libraries to do everything from threading to database queries to user-interfaces.

36

Page 37: Java GUI Programming. - University of Waterloocs349/w16/slides/2.1-java-part1.pdf · (Examples) Description java.awt Color, Graphics, Graphics2D, event. Contains all of the classes

Java

Cla

ss L

ibra

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

Page 38: Java GUI Programming. - University of Waterloocs349/w16/slides/2.1-java-part1.pdf · (Examples) Description java.awt Color, Graphics, Graphics2D, event. Contains all of the classes

Com

mon

Cla

sses

/Pac

kage

s Package Classes (Examples)

Description

java.awt Color, Graphics, Graphics2D, event.

Contains all of the classes for creating user interfaces and for painting graphics and images.

javax.swing JFrame, JButton, JList, JToolbar

Provides a set of "lightweight" (all-Java language) components that works the same on all platforms.

java.io File, FileReader, FileWriter, InputStream

Provides for system input and output through data streams, serialization and the file system.

java.lang Boolean, Integer, String, System, Thread, Math

Provides classes that are fundamental to the design of the Java programming language.

java.util ArrayList, HashMap, Observable

Contains the collections framework, legacy collection classes, event model,…

Java 8 API Specification: https://docs.oracle.com/javase/8/docs/api/overview-summary.html38

Page 39: Java GUI Programming. - University of Waterloocs349/w16/slides/2.1-java-part1.pdf · (Examples) Description java.awt Color, Graphics, Graphics2D, event. Contains all of the classes

Java

Cla

ss H

iera

rchy • Implicit class hierarchy

– All classes in Java are derived from the Object class in java.lang defines and implements common class behavior • e.g. clone(), toString(), finalize() methods

– Classes you write inherit this basic behavior.

39

Page 40: Java GUI Programming. - University of Waterloocs349/w16/slides/2.1-java-part1.pdf · (Examples) Description java.awt Color, Graphics, Graphics2D, event. Contains all of the classes

Wha

t’s n

ext? • Java Part 2

– Java components– Using listeners and adapters to handle events– Drawing components

• Events– Event dispatch

40

Page 41: Java GUI Programming. - University of Waterloocs349/w16/slides/2.1-java-part1.pdf · (Examples) Description java.awt Color, Graphics, Graphics2D, event. Contains all of the classes

Res

ourc

es • Java 8: http://www.oracle.com/technetwork/java/javase/

• Java 8 SE Platform Reference: https://docs.oracle.com/javase/8/docs/api/overview-summary.html

• Java 8 Tutorials: http://docs.oracle.com/javase/tutorial/java/index.html

• Java Language Whitepaper: http://www.stroustrup.com/1995_Java_whitepaper.pdf

• Jetbrains Student Licenses (IntelliJ): https://www.jetbrains.com/student/

41