CSC 335 Arkansas Baptist College Java Programming Questionnaire

11/3/2020Java I/O Framework Design
Philosophy
CSC 335 – I/O and
Serialization
• Programs that do I/O should be portable.
• Platform differences in file names and line terminators must
be handled in a way that ensures the code runs everywhere.
• I/O is based on streams based on a physical “device” on
one end.
• Device can be a file or a location in memory.
• That physical device is managed by some class and you wrap
(layer) additional logical classes on top of that for specific
kinds of I/O.
Dr. Jonathan Misurda
jmisurda@cs.arizona.edu
• There are lots of small classes that do one thing,
instead of a few big classes that do many things.
• Use Decorator and Composite patterns extensively.
1
2
Java I/O: IOException
File and Directory Operations
• Many java.io class methods throw an IOException (or a
subclass of it) if they encounter a problem.
• Java provides the File class to make it easier to write platformindependent code that deals with files.
• Directories (Composite pattern) are referenced as File objects as
well.
• IOException inherits from Exception and serves as the
base class for all of the exceptions thrown by the
java.lang.io package.
Recursive directory listing example:
static void listDir(File dir) {
System.out.println(dir.getPath());
• Some commonly seen subclasses of IOException.
if(dir.isDirectory()) {
for(File f: dir.listFiles()) {
listDir( f );
}
}
• EOFException
• FileNotFoundException
• InterruptedIOException
}
3
boolean
boolean
boolean
boolean
long
String
String
String
boolean
boolean
long
File[]
canExecute()
canRead()
canWrite()
exists()
length() // in bytes
getName()
getPath()
getParent()
isFile()
isDirectory()
lastModified() // time
listFiles()
4
Java I/O Streams
Character and Byte Streams
• A stream is an ordered sequence of bytes of
indeterminate length.
• Byte Streams (aka binary streams) are used for compact
and efficient I/O of primitive data (int, double, …) as
well as objects and arrays, in machine-readable form.
• Input streams carry bytes of data into a Java program from
some external source.
• Output streams carry bytes of data from a Java program to
some external destination.
• Streams can also be used to carry bytes or Unicode characters
of data from one part of a Java program to another.
Some streams of note:
5
Some useful File methods:
• The classes for byte streams are called InputStreams
and OutputStreams.
• Character Streams (aka text streams) are used for I/O
from text files and human-readable output. They use
16-bit Unicode characters.
Connected to:
InputStream
System.in
Usually the keyboard.
PrintStream
System.out
Usually the program’s output
or console.
PrintStream
System.err
Usually used to display error
messages to the console.
• The classes for character streams are called Readers
and Writers.
6
1
11/3/2020
Text/Character-Oriented Streams
A Riddle
• A text- or character-oriented data stream will
canonicalize read text to ‘\n’ regardless of how it was
stored in the data
• This could be a destructive operation, and is only valid
on “text files”
• When is a 162 byte file actually 156 bytes?
• Answer: When I made it on Windows
• Files that contain only human-readable text
• If we do this on “binary files” we will corrupt our data
• Every byte that is 13 followed by a byte that is 10 may get
changed to one or the other when we write it back out
• That’s not okay if that data represented colors, or our saved
Connect4 game state, etc.
7
8
A Typewriter
Teletype
• An electronically controlled
typewriter
9
10
ASCII Control Codes
Text
• Several ASCII codepoints (numbers) represent
unprintable characters to control a teletype and to
represent whitespace
String s = “Hello\n”
• What does \n mean? Depends on the Operating System
Windows
H
• Carriage Return (CR) is ASCII char number 13
• Line Feed (LF) is ASCII char number 10
E
L
L
O
CR
O
LF
O
CR
LF
UNIX-likes (Including Mac OS X)
H
E
L
L
Mac OS versions prior to OS X
H
11
E
L
L
12
2
11/3/2020
Line Ending Conversion
Reading bytes with FileInputStream
File System
// File created on Windows with CR LF endings
File myFile = new File(“foo.txt”);
FileInputStream inStream = null;
File requestedFile = new File(“test.html”);

System.out.println(“Length: ” + requestedFile.length()); // 162
Scanner input = new Scanner(new FileInputStream(“test.html”));
while(input.hasNextLine()) {
System.out.println(input.nextLine());
}
// Only prints 157 bytes on non-Windows systems
13
FileInputStream
Bytes
Java
Program
try {
inStream = new FileInputStream(myFile);
while (true) {
Integer b = inStream.read();
if (b == -1) { // -1 means EOF
break;
}
System.out.println( “Read byte: ascii='” + (char) b.intValue()
+ “‘ hex = 0x” + Integer.toHexString(b));
}
} catch (IOException ex) { System.out.println(“File Open/Read Error”);
} finally { if ( inStream != null ) { inStream.close(); }}
14
Java I/O: Primitives (Beyond Bytes)
Wrapper Classes
• Ultimately data is stored as bytes, but in programs we
use many different types built out of one or more
bytes.
• For example, A Java long is 64 bits (8 bytes), a float is
32 bits (4 bytes), and a char is 16 bits (2 bytes).
• If we want to read data from a file, it would be very
tedious to write the code to read individual bytes and
have to re-assemble your data yourself (a process
known as unmarshalling or deserialization) .
• To make this easier, the I/O package provides the ability
to read and write all of Java’s primitives: as the
DataInputStream and DataOutputStream. It
provides this as a wrapper.
• Java’s I/O uses wrappers to permit the combination of
multiple layers of functionality.
• In the code example below, the FileInputStream is
wrapped in a DataInputStream, so that we can use
readFloat().
15
DataInputStream
File System
bytes
FileInputStream
float
Java Program
DataInputStream dataInStream = null;
try {
dataInStream = new DataInputStream(new FileInputStream(“mydata.dat”)));
System.out.println(dataInStream.readFloat());
} catch (IOException e) {e.printStackTrace();
} finally { if ( dataInStream != null ) { dataInStream.close(); }}
16
Wrapper Classes
The Decorator Pattern
• This is useful because it lets each class focus on the
functionality it is responsible and not try to do
everything
• Recurring Problem:
• How to add responsibilities to individual objects,
regardless of the class?
• One way is with inheritance, but this is static.
• delegates responsibility of reading the bytes to the stream it
wraps
File System
• Solution:
DataInputStream
bytes
FileInputStream
float
Java Program
• Enclose the object to be decorated in another object
that adds more functionality.
• The DataInputStream class adds the ability to read Java
primitives from the stream it wraps.
• Also Known As:
• Its constructor requires an InputStream to wrap.
• DataInputStream also extends FilterInputStream, which is the
base class that stores the wrapped stream.
17
Bytes
• Wrapper
18
3
11/3/2020
UML for the Decorator Pattern
Participants
• Component
• An interface for objects that can have responsibilities added
to them dynamically.
• ConcreteComponent
• An object to which additional responsibilities can be
attached.
• Decorator
• An abstract class that includes additional responsibilities.
• Also conforms to (is-a) Component’s interface.
• Has-a Component
• ConcreteDecorator
• Implements the Decorator abstract class.
19
20
Explanation
Explanation, cont.
• The constructor for Decorator is passed a
Component that is being decorated with the
additional responsibility.
• Since Decorator implements the Component
interface, an instance of it can be used wherever a
Component is.
• Clients can’t tell the difference between a decorated
component and an undecorated one.
• Since Decorator has-a Component, that component
can be decorated by a different decorator.
21
• Decorator forwards requests to its Components. It
may optionally perform additional operations
before and after forwarding the request.
22
Use Example: Java’s Input
Character Streams
UML for the Composite Pattern
• Reader is an abstract class (Component).
• It implements input character streams.
• public int read( ) throws IOException
• public int read(char[] cbuf) throws IOException
• BufferedReader (ConcreteDecoratorA) decorates
Reader.




23
public BufferedReader(Reader r)
Has-a Reader
Includes read( ) and read(char[] buf)
Also includes String readLine( )
24
4
11/3/2020
Java’s Input Character Streams,
cont.
Java’s Readers, cont.
• LineNumberReader (ConcreteDecoratorB) also
decorates Reader.
• BufferedReader and LineNumberReader can
decorate any Reader.
• public LineNumberReader(Reader r)
• Adds int getLineNumber( )
• Adds setLineNumber(int)
LineNumberReader(
BufferedReader(
StringReader(“My string”)))
• But how do you get a Reader in the first place
(subclasses of ConcreteComponent)?
• CharArrayReader(char[] buf)
• InputStreamReader(InputStream in)
• StringReader(String s)
25
26
Java I/O: Closeable
Java I/O: Buffering and Flushing
• It is important to close files when you are done
using them. This avoids wasting limited system
resources.
• In the case of input, buffering consists of reading
more data than initially requested into a location in
memory (called the buffer). The data in the buffer
is then passed to the program in whatever amounts
requested.
• In the case of output, buffering consists of storing
data to be written into a buffer until the buffer is
full. Once the buffer is full, all the accumulated
data is written out at once. This is called flushing
the buffer.
• Buffering is usually done for efficiency reasons.
• The Closeable interface is implemented by many
streams, and specifies one method


void close() throws IOException
Closes this stream and releases any system resources
associated with it.
27
28
Java I/O: Flushable
Redirecting In, Out, and Err
• The Flushable interface (implemented by many
OutputStreams) provides the programmer with the
ability to flush a stream on demand
• Java permits you to redirect System.out, System.in, and
System.err. This can be useful when having to redirect
the output (or input) of code not under your control.
public static void setIn(InputStream in)
public static void setOut(PrintStream out)
public static void setErr(PrintStream err)
• void flush() throws IOException
• Flushes this stream by writing any buffered output to
the underlying stream.
• For example, to send everything that gets printed to
System.out to a file called out.txt:
• Note that closing a stream flushes its buffers as
well.
29
try {
System.setOut( new PrintStream(
new FileOutputStream(“out.txt”)));
} catch (FileNotFoundException e) { e.printStackTrace(); }
// Now everything sent to System.out goes to the file
30
5
11/3/2020
java.io.* InputStream
From: http://www.roseindia.net/java/example/java/io/DataStreams.shtml
31
java.io.* OutputStream
From: http://www.roseindia.net/java/example/java/io/DataStreams.shtml
32
Useful System Properties
Serialization
• Java’s maintains a list of property values accessible via
the method:
• The process of converting an object into its
individual bytes for transfer or storage is called
serialization (or marshalling).
• Reconstructing the object from the bytes is called
deserialization (or unmarshalling).
• Java provides the ability to easily read and write
objects to and from streams. It does this by
providing a special interface for classes to use and
another set of wrapper streams.
• static String System.getProperty(String key)
• Some of these keys refer to the local file-system locations.
• Some useful property keys and their associated values
(all Strings):





java.home
java.class.path
java.io.tmpdir
user.home
user.dir
Java installation directory.
List of paths to search for libraries.
Default temp file path.
User’s home directory.
User’s current working directory.
33
34
java.io.Serializable
Object Streams
• To use Java’s serialization, the object to be
serialized and deserialized must implement the
java.io.Serializable marker interface.
• Eclipse will warn you if your Serializable class does
not define a serialVersionUID.
• The ObjectOutputStream is the wrapper class that
provides the writeObject() method.
• void writeObject(Object obj) throws IOException
• An ObjectOutputStream can be wrapped around any
OutputStream.
• The ObjectInputStream is the wrapper class that
provides the readObject() method.
• This variable should be changed in a class if the
structure of the object changes such that it must be read
differently.
• The declaration for this must be:
• Object readObject() throws IOException,
ClassNotFoundException
• An ObjectInputStream can be wrapped around any
InputStream.
static final long serialVersionUID = id;
35
36
6
11/3/2020
Serializable Marker Class
Sending a Graph of Objects
public class Model implements Serializable {
… }
• What if an instance has a field that is a reference to
another instance?
• Serialize both instances and include information on how
to fix up the references.
public class GUI {
Model m;
• What if an instance is referenced by two or more
other instances?
void done () {
ObjectOutputStream oos
= new ObjectOutputStream(…);
oos.writeObject(m);
}
• Serialize each instance exactly once but include
information about how to fix up the multiple references
to an instance.
}
• What if there is a cycle in the instance references?
• Record a cycle only once
37
38
Serialization pitfalls: Changing the
Object
Serialization pitfalls: transient
modifier
• If you write an object out through an ObjectOutputStream,
then change that object and rewrite it, the other end will
receive the original values twice, which is not correct.
• From http://java.sun.com/javase/technologies/core/basic/serializationFAQ.jsp
• What if you don’t want a field serialized?
• “The ObjectOutputStream class keeps track of each object it
serializes and sends only the handle if the object is written into the
stream a subsequent time. This is the way it deals with graphs of
objects. The corresponding ObjectInputStream keeps track of all of
the objects it has created and their handles so when the handle is
seen again it can return the same object. Both output and input
streams keep this state until they are freed.”
• “Alternatively, the ObjectOutputStream class implements a
reset( ) method that discards the memory of having sent an object,
so sending an object again will make a copy.”
39
• (e.g., a secure object, or information that won’t be valid
upon being loaded, or objects that can’t be serialized)
• Java provides the transient modifier for fields that
are not to be written out during serialization.
• Fields marked transient are skipped.
public class MySerializable implements Serializable {
private static final long serialVersionUID = 1L;
private transient String secretPassword; // not serialized

}
40
Serialization pitfalls: transient
Summary
• It is also possible to define special readObject and
writeObject methods for a class such that those
methods are called at the corresponding time
during serialization or deserialization.
• Java I/O is another Java framework, this time for
performing Input and Output of bytes, characters,
and more
public class MySerializable implements Serializable {
private transient String secretPassword;

private void readObject(ObjectInputStream in)
throws IOException, ClassNotFoundException {
in.defaultReadObject(); // calls regular objreader
// prompt user for secret passwd
secretPassword = promptForSecretPassword();
}
}
41
• Decorator pattern is used throughout.
• Serializable marker interface and transient modifier
allow Objects to customize how they are saved and
restored
42
7
10/8/2020
Separation of Concerns
CSC 335 – MVC and
Design Patterns
• One of the primary goals of our OOP design is to break
our program into small parts each dealing with some
aspect of the total program
• Design Principle:
• Divide our program up into small sections
• Each section is responsible for a single task
• Each section is separate from each other (enabling testing,
reuse, and modification without worrying about other
sections)
Dr. Jonathan Misurda
jmisurda@cs.arizona.edu
• We have called these sections modules, and in Java,
classes are one way of implementing modularity
1
2
A Common Program Design
Designing an Architecture
• Think of a typical interactive program.
• It probably, broadly, has three parts:
• If we are adhering to the goals of modularity via
the separation of concerns, we could see each of
those tasks as a separate unit of our program
1. Some way of interacting with the program
2. Some data structure(s) that model the problem the
program solves
3. Some code that responds to the interaction and uses
the data structures to do some work
• In an OOPL, that might mean each broad part
becomes a separate class
• Thus, without even considering the program’s
behavior, we have an idea about how to break it
into modules
3
4
Model/View/Controller
What does MVC buy us?
• This particular architecture is often called
Model/View/Controller (MVC)
• Abstraction
• The model is the object that holds the data that
represents the state of the world
• The view shows the data to the user and allows them to
interact with it
• The controller acts as the glue between them
• If we have properly separated the concerns and
made a useful interface between the model and
the controller, and the controller and the view, we
get something very powerful:
• You can change the view without changing the
controller or the model
• You can change the model without changing the
controller or the view
• Each component is kept separate
• E.g., the view never talks to the model, except through
the controller
5
6
1
10/8/2020
Changing the View
Exceptions help keep SoC
• What would it take to change our project from a
console-based text input view to one of a graphical
user interface (GUI)?
• Note that the controller needs to enforce that it’s
actions are on valid input
• This might result in some change to the view
• We do not want the controller displaying a message
or asking for new input
• Would you need to change the model?
• Would you need to change the controller?
• That’s the view’s job and only the view’s job
• So if we get an error, we can throw an exception,
and the caller of the controller’s method (the view)
can handle it
7
8
In-Class Activity: MVC
MVVM
• Choose an application to model in the MVC
architecture
• We hear a lot today about a similar architecture to
MVC, called Model-View-ViewModel or MVVM
• We’ve already uses Mastermind and Tic Tac Toe as
examples, so choose something else
• It doesn’t have to be a game
• This is a common design among a number of Single
Page Application (SPA) web programming
frameworks
• Use the form handed out to produce a UML
diagram for each MVC class
• Angular.js
• Ember.js
• Knockout.js
• Not writing any actual code
9
10
View Model
MVVM with MVC
Web Browser
• A View Model is a module whose job it is to map
(bind) elements from the view to the model
View
Name:
V
• For instance, we might have a textbox that
represents the contents of some variable
• When we edit the textbox, we want the variable to
change
• When we change the variable, we want the textbox to
change
Save
– name: TextBox
+ onChange()
+ onClick()
+ onLoad()
Model
– name: String
+ getName(): String
+ setName(name: String)
Controller
C
M
11
ViewModel
Bob
– databasePW: String
+ onPost(parameters: Array)
+ onGet(query: string): JSON
Web Server
Database
12
2
10/8/2020
Patterns
Architectural Patterns
• A pattern
• MVC and MVVM are Architectural Patterns
• They described a way to design an application’s
architecture:
• Describes a problem which occurs over and over again
• Describes the core of the solution to that problem
• Identify the concerns to separate
• Map those concerns onto classes
• Describe how those classes should interact
• It does so “in such away that you can use this
solution a million times over, without ever doing it
the same way twice”
• At no point did they ever tell you:
• What methods to have
• What fields to store
• What classes beyond the top level ones (M, V, C, VM) to
have
• What code to write
• Christopher Alexander – A pattern Language
• A pattern is not an implementation (code). It is a
design.
13
14
Design Patterns
Singleton
• A design pattern is a general reusable solution to a
commonly occurring problem within a given
context in software design.
public class Singleton {
private Singleton() { }
private static Singleton myInstance;
• For instance, we may only want to have at most a
single instance of an object instantiated.
public static Singleton getInstance() {
if(myInstance == null)
myInstance = new Singleton();
return myInstance;
• We can use a Singleton Pattern.
}
}
15
16
java.lang.Runtime Documentation
Some Runtime Methods
public class Runtime extends Object
Method
Description
availableProcessors() Returns the number of processors available to the
Java virtual machine.
Every Java application has a single instance of class
Runtime that allows the application to interface with
the environment in which the application is running.
The current runtime can be obtained from the
getRuntime method.
An application cannot create its own instance of this
class.
17
exec()
Executes the specified string command in a separate
process.
exit(int status)
Terminates the currently running Java virtual
machine by initiating its shutdown sequence.
freeMemory()
Returns the amount of free memory in the Java
Virtual Machine.
gc()
Runs the garbage collector.
getRuntime()
Returns the runtime object associated with the
current Java application.
18
3
10/8/2020
Why is Runtime a Singleton?
Singletons
• This represents the underlying system features, it
wouldn’t make sense to instantiate multiple copies
• Singleton is the easiest design pattern to
understand
• Why not just have them all be static methods, like
with System?
• It’s also probably one of the worst
• Captures the notion of “global” state, which can begin to
break down modularity
• ¯\_(ツ)_/¯
• Throughout the course we will see more, some
used in the Java Class Library and some not
19
20
4
10/22/2020
AWT
• Java’s first major GUI support was called the
Abstract Window Toolkit (AWT)
• AWT was based upon the native controls of the
actual OS you ran it on
CSC 335 – JavaFX
• E.g., a Button was a real button on Windows, Mac
• Also was used to create Applets in web browsers
Dr. Jonathan Misurda
jmisurda@cs.arizona.edu
1
• AWT had some limitations, and some particular
problems with how it was implemented on some
platforms
2
Swing
AWT vs Swing Look-and-feel
• AWT was replaced by a new library called Swing
• more versatile, more robust, and more flexible
• Swing was designed primarily for use in desktop
applications
import java.awt.*;
• Could do some web-based things with it though Applets
public class GUIDemo {
public static void main(String[] args)
{
Frame frame = new Frame(“Swing
Frame”);
Panel panel = new Panel();
panel.add(new Button(“Click Me!”),
BorderLayout.CENTER);
frame.add(panel);
frame.pack();
frame.setVisible(true);
}
}
• Swing used native “panels” from the underlying OS, but
all other controls were drawn and handled by Java itself
• A JButton was just a rectangle that Swing makes act like a
button
• Swing applications don’t have native “look-and-feel”
3
public class GUIDemo {
public static void main(String[] args)
{
JFrame frame = new JFrame(“Swing
Frame”);
JPanel panel = new JPanel();
panel.add(new JButton(“Click Me!”),
BorderLayout.CENTER);
frame.add(panel);
frame.pack();
frame.setVisible(true);
}
}
4
JavaFX
JavaFX: Desktop and RIAs
• Swing has been replaced by a new GUI and Event
library called JavaFX
• Programmers can still use Swing (for the
foreseeable future), however
• JavaFX lets us write RIAs (Rich Internet
Applications)
• These run under a browser (Firefox / Chrome / Safari)
just like they run on a desktop
• Oracle isn’t going to develop Swing it any further
• Swing is essentially a dead-end technology
• Previously, the browser experience was delivered
by Java Applets
• Applets are pretty much dead also
• Just kidding! Java 11 removed JavaFX from the JDK
and only offers it as a separate download. Oracle
wants to go back to Swing. Sigh.
5
import java.awt.BorderLayout;
import javax.swing.*;
6
1
10/22/2020
JavaFX
Event Driven GUIs
import javafx.application.Application;
root.getChildren().add(btn);
import javafx.stage.Stage;
Scene scene = new Scene(root, 300,
import javafx.scene.Scene;
• A Graphical User Interface (GUI) presents a
graphical view of an application to users
• To build an event-driven GUI application, you must:
250);
import javafx.scene.control.Button;
primaryStage.setTitle(“JavaFX
import javafx.scene.layout.StackPane;
Scene”);
• Have a well-tested model that is independent of the
view
• Make graphical components visible to the user
• Ensure the correct things happen for each event
primaryStage.setScene(scene);
public class GuiDemo extends Application
{
@Override
public void start(Stage primaryStage)
primaryStage.show();
}
public static void main(String[] args)
{
{
• user clicks a button, or moves the mouse, or presses the enter
key, …
launch(args);
Button btn = new Button();
}
btn.setText(“Click Me!”);
}
• Let’s first consider some of Java’s GUI components:
• Pane, Button, Label, TextField
StackPane root = new StackPane();
7
8
Get the app to show itself
Graphical Components in JavaFX
// Show an empty stage with no components in it
public class FirstApp extends Application {
Stage: window
with title,
border, menu,
buttons
public static void main(String[] args) {
BorderPane:
where we can
add Buttons,
Labels, …
(inside the
Scene)
launch(args);
}
@Override
public void start(Stage stage) {
stage.setTitle(“Our First GUI”);
Button: A
component that
can “clicked”
Label: A display
area for a small
amount of text
BorderPane window = new BorderPane();
TextField: Allows
editing of a single
line of text
Scene scene = new Scene(window, 300, 90); // 300 pixels wide, 90 tall
stage.setScene(scene);
//
Don’t forget to show the running app:
stage.show();
}
}
9
10
Get the app to show itself
Get the app to show itself
// Show an empty stage with no components in it
// Show an empty stage with no components in it
public class FirstApp extends Application {
public class FirstApp extends Application {
public static void main(String[] args) {
public static void main(String[] args) {
launch(args);
launch(args);
The main entry point for
all JavaFX apps
}
@Override
@Override
public void start(Stage stage) {
public void start(Stage stage) {
The top level
JavaFX container.
stage.setTitle(“Our First GUI”);
stage.setTitle(“Our First GUI”);
BorderPane window = new BorderPane();
BorderPane window = new BorderPane();
Scene scene = new Scene(window, 300, 90); // 300 pixels wide, 90 tall
Scene scene = new Scene(window, 300, 90); // 300 pixels wide, 90 tall
stage.setScene(scene);
stage.setScene(scene);
//
//
Don’t forget to show the running app:
stage.show();
Don’t forget to show the running app:
stage.show();
}
}
}
11
The main entry point for
all JavaFX apps
}
}
12
2
10/22/2020
Get the app to show itself
Get the app to show itself
// Show an empty stage with no components in it
// Show an empty stage with no components in it
public class FirstApp extends Application {
public class FirstApp extends Application {
public static void main(String[] args) {
launch(args);
The main entry point for
all JavaFX apps
}
public static void main(String[] args) {
The top level
JavaFX container.
@Override
public void start(Stage stage) {
stage.setTitle(“Our First GUI”);
launch(args);
The main entry point for
all JavaFX apps
}
The top level
JavaFX container.
@Override
One of many Pane
Types
public void start(Stage stage) {
stage.setTitle(“Our First GUI”);
One of many Pane
Types
BorderPane window = new BorderPane();
BorderPane window = new BorderPane();
Scene scene = new Scene(window, 300, 90); // 300 pixels wide, 90 tall
Scene scene = new Scene(window, 300, 90); // 300 pixels wide, 90 tall
stage.setScene(scene);
stage.setScene(scene);
//
Don’t forget to show the running app:
//
stage.show();
Don’t forget to show the running app:
stage.show();
}
}
}
}
13
The container for all
content
14
Adding Components
• So far we have an empty stage
• Let us add a Button, a Label, and a one line Editor (TextField)
• First construct three graphical components:
// Three different UI controls as instance variables
private Button button = new Button(“Click this very wide button”);
Components are Nodes in a Graph
• Add three components to the BorderPane as Node
objects
window.setTop(button);
window.setCenter(label);
window.setBottom(textField);
• In addition to the 3 message above, we can
setLeft(Node)
setRight(Node)
private Label label = new Label(“Button above and TextField below”);
private TextField textField = new TextField();
• The Node objects are in a Pane object
• Need to add these objects to the BorderPane referenced by
window
15
• These nodes are children of the Pane
• The Pane is in a Scene object
• The Scene is in the Stage object
16
BorderPane
The 5 Areas of BorderPane
• By default, BorderPane objects have only five places
where you can add components
• a 2nd add wipes out the 1st
window.setTop(new Button(“Top”));
window.setLeft(new Button(“Left”));
window.setCenter(new Button(“Center”));
window.setRight(new Button(“Right”));
window.setBottom(new Button(“Bottom”));
• There is no padding or locating Nodes here
• So this layout looks odd
17
18
3
10/22/2020
Adding two controls to a subpane
Panes with Layout Strategies
• If adding a second control to a subpane of the
BorderPane replaces it, how do we ever have two
controls in the same pane?
• For example, we might want a toolbar of buttons in the
Top position
• Solution: We can put Panes inside of other Panes
Pane Class
Strategy
BorderPane
GridPane
TilePane
FlowPane
AnchorPane
Areas for top, bottom, left, right, center
Layout children in a table like grid
Layout children in a grid, all the same size
Layout children left to right, top to bottom
Children are positioned in relative position to the
Pane’s boundary
Wraps children inside others, used to decorate
such as putting a button over a a colored
rectangle
StackPane
19
20
Composite Pattern
Composite Pattern
• Recurring problem:
• Solution:
• Often complex structures are built with container objects and
primitive objects. Container objects can be contained by
other objects.
• How can code that uses these classes treat all the objects in
the structure identically some of the time, yet differently
when it matters?
• Define an abstract class that represents both primitives
and their containers. Primitive classes will not
implement the child-related operations.
• Also known as:
• Used in the View class of the Smalltalk MVC as well as
most other GUI toolkits.
• Example: Graphics
• We want a visual element which can be either a simple shape
or a collection of several other elements
• Don’t want separate interfaces for primitive shapes and
complex compositions
21
22
UML for the Composite Pattern
Participants
• Component
• Declares the interface for all objects in the composition.
• Implements default behavior, as appropriate.
• Declares an interfaces for accessing and managing its child
components.
• (Optional) May provide a way to access a component’s
parent.
• Leaf
• Has no children: it is a primitive.
• Composite
• Defines behavior for components having children.
• Implements child-related operations in the Component
interface.
23
24
4
10/22/2020
Explanation
Composite Pattern Diagram
• Component has Operation( ), which is a method that
applies to all components, whether composite or leaf.
• The composite pattern lets us treat an object (the
Component) as if it could be a Leaf (contains no
children) or a Composite, made up of a number of
leaves and/or composites.
• There are generally many operations.
• Component also has composite methods: Add( ),
Remove( ), and GetChild( ).
• Note that in all cases a Component is passed.
• Component itself just throws an exception for these methods.
• Leaf implements the operations.
• Does nothing on Component methods, which just return.
• Composite implements the composite methods.
• Also implements the operations, by invoking the operation on
each of its children in succession.
25
26
JavaFX: Node
JavaFX Subclass Hierarchy, cont.
Object
• Node is something that goes in a Parent
• Since a Parent isA Node, you get a hierarchy
• Some functionality the Node class provides to its
descendants:




Parent
Painting (how an object is displayed), borders
Application-wide pluggable look and feel
Support for layout (where in the container does it go?)
Support for accessibility (mouse and keyboard)
Pane
getChildren()
VBox
FlowPane
GridPane
• Some example descendants of Node are: (many kinds
of) Pane, Button, ListView, Label, and many more.
BorderPane
27
HBox
28
JavaFX Layout Classes
Top-Level Containers
• To appear onscreen, every GUI component must be
added to a top-level container.
• The top-level container corresponds to what you
think of as a “window” or “application” on your
computer.
Stage
top-level container
A containment (has-A)
hierarchy for a simple GUI:
Scene
Parent
components
GridPane
Label
29

Menu
MenuItem

30
5
10/22/2020
Event-Driven Programming
Event-Driven Programming
• A style of coding where a program’s overall flow of
execution is dictated by events:
• We contrast this with the types of programs that
we have been producing so far, which we might
term: prompt-and-wait style programs
• The program loads
• The program waits for the user to generate input
• Each event causes some particular code to respond
• Need an event handler
• The overall flow of what code is determined by the user
generating a series of events
31
32
Event-Driven Programming
Kinds of Events
• The main body of the program is an event loop
• Different events that can occur in an event-driven
program with a GUI
• The main algorithm abstractly:










do {
}
e = getNextEvent();
processEvent(e);
while (e != quit);
Mouse move/drag/click, mouse button press/release
Keyboard: key press/release
Touchscreen finger tap/drag
Joystick, drawing tablet, other device inputs
Window resize/minimize/restore/close
Network activity or file I/O (start, done, error)
Timer interrupt
Move a scroll bar
Chose a menu selection
Media finishes
handle(Event)
33
34
Java’s Event Model
Example: ActionEvent
• Java and the operating system work together to detect
user interaction
• The button and textField do not yet perform any
action
• Let’s make something happen when
• Button objects are notified when clicked
• Send a handle(ActionEvent) message to registered ActionEvent
handlers
• The button is clicked
• The user presses enters into the textField
• TextField objects are notified when the user presses Enter
• A handle(ActionEvent) message is sent to registered event
handlers
• When the mouse is clicked, the node under the cursor is
notified
• Send a handle(MouseEvent) message to registered Mouse event
handlers
• When a key is pressed
• Send a handle(KeyEvent) message to registered KeyEvent handlers
35
36
6
10/22/2020
How to Handle Events
Using an Inner Class
• Add a private inner class that will handle the event
that the component generates
• Have a private inner class that implements EventHandler
:
• This class must implement an interface to guarantee
that it has the expected method such as
}
public void handle(ActionEvent ae)
• Register the event handler so the component can
later send the correct message to that event
handler
private class ButtonHandler implements EventHandler
{
@Override
public void handle(ActionEvent event) {
button.setText(textField.getText());
}
}
• Events occur anytime in the future–the event handler is
waiting for user generated events such as clicking button
• Send this message to the GUI component:
button.setOnAction(handler);
37
EventHandler handler = new ButtonHandler();
button.setOnAction(handler);
38
Using a Lambda
JavaFX Input: Inversion Of Control
button.setOnAction((event) -> {
• Using Blocking/Polling: Application calls a method and waits
(blocks) for input from the user:
button.setText(textField.getText());
}
// Waits for user input, polling…
inputString = myScanner.nextLine();
});
• Using Callbacks: the programmer indicates what methods,
specified in EventHandlers and other event listener classes) are
to be called passed certain input events (or ActionEvents). These
methods are called callbacks because the application is telling
JavaFX to call it back should a given event occur
• JavaFX is in control and delegates control, based on input, to the
application code. Hence the term Inversion Of Control.
39
40
Observer Design Pattern
Observer Design Pattern
• Observer is a software design pattern in which the model
maintains a list of its observers, and notifies them
automatically of any state changes
• Observer is used so frequently that Java supplies
• A class to be extended: Observable
• An interface to be implemented by many classes:
Observer
• It is the heart of MVC
• This is what we will use to have multiple views (ButtonView,
TextAreaView, DrawingView) observe the model and change
when the model changes
• Both views must be added as “Observers”
• The model is the “Observable”
• A specific message from an interface is sent to all observers
in these methods of Patterns in TTT
• TicTacGame()
• startNewGame()
• choose(int row, int col)
41
42
7
10/22/2020
Observer Design Pattern
The Model’s Responsibilities
/** Use a Pane to implement this interface so the Pane
can show a view of the model and allow user input */
public class ButtonView extends BorderPane implements Observer
// This method is called by Observable’s notifyObservers()
public void update(Observable observable, Object message) {
theGame = (TicTacToeGame) observable;
updateButtons();
if (theGame.didWin(‘X’))
stateButton.setText(“X wins”);
else if (theGame.didWin(‘O’))
stateButton.setText(“O wins”);
else if (theGame.tied())
stateButton.setText(“Tie”);
else
stateButton.setText(clickMessage);
}
• Provide access to the state of the model
• didWin(char),
getAt(int, int),

• Provide access to the system’s functionality
• startNewGame(), setComputerPlayerStrategy(TicTacToeStrategy)
• Notify the view(s) that the model’s state has changed
/**
* This is called from humanMove when not testing
*/
public void computerMove(int row, int col) {
if (board[row][col] != ‘_’)
return;
board[row][col] = ‘O’;
setChanged(); //Java needs this or notifyObservers does nothing
notifyObservers(); //Send update messages to all Observers
}
43
44
The Controller Responsibilities
Full MVC Architecture
• Respond to user input (when an event occurs)
Controller
• Button click in ButtonView or enter integers in the
TextArea with a button click (a view that you are asked
to implement)
Notifies upon user
interaction
• Send makeMove() messages to the model our
TicTacToeGame), that sends notifyObservers()
messages to the Observable (TicTacToeGame) that
sends update messages to the observers
• In JavaFX, our EventHandlers are controllers
Updates
View
Model
Triggers changes in
45
46
The Canvas Node
Drawing Text
• JavaFX added a Canvas Node to mimic HTML5’s Canvas
public void start(Stage stage) {
BorderPane pane = new BorderPane();
Canvas canvas = new Canvas(200, 100);
• Add a Canvas object to a Pane allows a portion of our
application to be viewed as an image
pane.setCenter(canvas);
GraphicsContext gc = canvas.getGraphicsContext2D();
• We can draw shapes and images
// This string will be drawn 20 pixels right,
// 40 pixels down as the lower left corner.
• Canvas objects have a specified width and height
// All other shapes point is the upper left
• Need to draw onto the GraphicsContext object of the
Canvas object
Scene scene = new Scene(pane, 200, 100);
gc.fillText(“I’m in a Canvas”, 20, 40);
stage.setScene(scene);
stage.show();
}
47
48
8
10/22/2020
The Coordinate System
The Coordinate System
• A simple two-dimensional coordinate system exists for each
graphics context, or drawing surface
• Each point on the coordinate system represents a pixel
y
x
X
• Top left corner of the area is coordinate
// This string will be drawn 20 pixels right,
// 40 pixels down as the lower left corner.
gc.fillText(“I’m in a Canvas”, 20, 40);
• A drawing surface has a width and height
• Anything drawn outside of that area is not visible
• When drawing shapes first position is at the top left corner
49
Y
50
How to Draw on a Canvas
Drawing Lines
public void start(Stage stage) {
• strokeLine(leftX, leftY, rightX, rightY)
BorderPane window = new BorderPane();
Canvas canvas = new Canvas(150, 150);
window.setCenter(canvas);
• Change the thickness with setLineWidth
GraphicsContext gc = canvas.getGraphicsContext2D();
gc.setFill(Color.RED);
gc.setStroke(Color.BLUE);
gc.strokeLine(0, 150, 150, 0);
gc.strokeOval(20, 20, 40, 40);
gc.fillOval(70, 20, 40, 40);
gc.setLineWidth(3);
gc.fillRect(20, 80, 40, 40);
gc.setStroke(Color.GOLD);
gc.strokeRect(70, 80, 40, 40);
for (int fromTop = 10; fromTop

Calculate your order
275 words
Total price: $0.00

Top-quality papers guaranteed

54

100% original papers

We sell only unique pieces of writing completed according to your demands.

54

Confidential service

We use security encryption to keep your personal data protected.

54

Money-back guarantee

We can give your money back if something goes wrong with your order.

Enjoy the free features we offer to everyone

  1. Title page

    Get a free title page formatted according to the specifics of your particular style.

  2. Custom formatting

    Request us to use APA, MLA, Harvard, Chicago, or any other style for your essay.

  3. Bibliography page

    Don’t pay extra for a list of references that perfectly fits your academic needs.

  4. 24/7 support assistance

    Ask us a question anytime you need to—we don’t charge extra for supporting you!

Calculate how much your essay costs

Type of paper
Academic level
Deadline
550 words

How to place an order

  • Choose the number of pages, your academic level, and deadline
  • Push the orange button
  • Give instructions for your paper
  • Pay with PayPal or a credit card
  • Track the progress of your order
  • Approve and enjoy your custom paper

Ask experts to write you a cheap essay of excellent quality

Place an order