advJava-lec03-2016
Download
Report
Transcript advJava-lec03-2016
Lecture 03 Agenda
Team Projects
JavaFX
Generics
JavaFX is the Evolution of Java as a Rich Client Platform.
It is designed to provide a modern Java environment
featuring a lightweight, hardware accelerated UI platform
that meets tomorrow’s needs.
2
Copyright © 2011, Oracle and/or its affiliates. All rights reserved.
Insert Information Protection Policy Classification from Slide 8
JavaFX Features Overview
JavaFX is …a graphics framework
Familiar: 100% Java APIs
Powerful: leverages underlying Java platform
Modern: CSS skinning, HW acceleration, Webkit
Backwards ‘compatible’: Swing & SWT interoperability
Open Source: http://openjdk.java.net/projects/openjfx
JavaFX Runtime High Level Architecture
JavaFX Glossary
Glass Windowing Toolkit: Provides native operating services, such as managing the
windows, timers, and surfaces
Prism: Graphics pipeline that can run on hardware and software renderers
Quantum Toolkit: Ties Prism and Glass together and makes them available to the
JavaFX APIs
Graphics and Media
New Graphics Pipeline
• New hardware accelerated graphics
pipeline (Prism)
• New windowing toolkit (Glass) for
Prism
• Java2D software pipeline under
Prism
• High-level support for making rich
graphics simple
• Shadows, Blurs, Reflections, Effects,
2D transforms
• 3D Transforms today; Full 3D objects
in future
Media
• Stable media framework based on
GStreamer
• VP6, MP3 playback of Web
multimedia content
• Low latency audio
• Alpha channel support
• Performance improvements
• Full screen video
WebView and Swing
Interoperability
WebView Component
• Embed Web content
in JavaFX
applications
• HTML rendering
based on Webkit
• Hardware accelerated
rendering using
PRISM
• DOM access and
manipulation
Swing and SWT Interop
• Embed JavaFX
content into existing
Swing applications
• Extend existing Swing
applications with new
JavaFX features such
as WebView and
high-performance
graphics
• Applies to SWT
applications as well
Browser Plugin
• Faster loading of
JavaFX Web
applications based on
Prism
• Pre-loader for
improved user
experience with
JavaFX Web
applications
JavaFX vs Swing and AWT
Swing and AWT are superseded by the JavaFX platform for
developing rich Internet applications.
When Java was introduced, the GUI classes were bundled in a
library known as the Abstract Windows Toolkit (AWT). AWT is fine
for developing simple graphical user interfaces, but not for
developing comprehensive GUI projects. In addition, AWT is prone
to platform-specific bugs. The AWT user-interface components were
replaced by a more robust, versatile, and flexible library known as
Swing components.
Swing components are painted directly on canvases using Java code.
Swing components depend less on the target platform and use less of
the native GUI resource. With the release of Java 8, Swing is
superseded by a completely new GUI platform known as JavaFX.
8
Media
JavaFX supports both visual and audio media
Cross-platform JavaFX media file format (fxm, mp3)
Platform specific formats supported via native players
Media class represents a media file
MediaPlayer provides control of the media rendering
MediaView uses MediaPlayer to render media as Node
Many MediaViews can use the same MediaPlayer
Open Source and Standardization
JavaFX source code being contributed as part of OpenJFX
http://openjdk.java.net/projects/openjfx/
Source code being contributed in phases
Initial phase: UI Controls
Oracle is committed to standardize JavaFX through JCP
One or more JSRs will be submitted
Expected to be become part of the Java SE specification
Adding HTML Content
The Embedded Browser
WebEngine
Provides basic web page browsing functionality
Supports user interaction: navigating links, submitting forms
WebView
Web page as a Node in scenegraph
• Effects can be applied
Encapsulates WebEngine object
No plugin support
Charts
Effects...
GaussianBlur
InnerShadow
Reflection
SepiaTone
Transforms
Rectangle rect=new Rectangle(0,0,60,60);
rect.setFill(Color.DODGERBLUE);
rect.setArcWidth(10);
rect.setArcHeight(10);
rect.setRotate(45);
rect.setScaleX(2);
rect.setScaleY(0.5);
Shear shear = new Shear(0.7, 0);
rect.getTransforms().add(shear);
rect.setTranslateX(40);
rect.setTranslateY(10);
Structure of an FX Application
Scene Graph
Directed Acyclic Graph
Parents and children
Representation of the GUI components
The Root is at the head
Layout Panes
JavaFX provides many types of panes for organizing nodes
in a container.
17
There are two kinds of JavaFX
projects:
1/ No Fxml
2/ Fxml
No FXML
public class JavaFXTest extends Application {
@Override public void start(Stage stage) {
Group root = new Group();
Scene scene = new Scene(root,100,100);
stage.setScene(scene);
Circle c1 =
new Circle(50.0f, 50.0f, 50.0f, Color.RED);
root.getChildren().add(c1);
stage.setVisible(true);
}
public static void main(String a[]) {
Launcher.launch(JavaFXTest.class, null);
}
}
See TabBrowserMain.java
Stage
Scene
Root
Basic Structure of JavaFX
Application
Override the start(Stage) method
Stage, Scene, and Root (Node)
Stage
Scene
Button
MyJavaFX
MultipleStageDemo
Run
Run
20
JavaFX Properties
Properties
Basis for high level binding API
Concrete types for all primitives, String and Object
DoubleProperty, StringProperty, etc
Examine the SDK
We use the Properties to facilitate binding to events in JavaFX
See PropertiesDriver and PropertyChangeEvent1
JavaFX Bindings
Binding
See BillDriver and BillDriver2
Line
ShowLine
Run
25
Simple Binding Example
private SimpleDoubleProperty topXProperty =
new SimpleDoubleProperty();
private SimpleDoubleProperty topYProperty =
new SimpleDoubleProperty();
Line foldLine = new Line();
foldLine.setEndX(200);
foldLine.setEndY(200);
foldLine.startXProperty().bind(topXProperty);
foldLine.startYProperty().bind(topYProperty);
...
topXProperty.set(tx);
topYProperty.set(ty);
See ShowLine example
Create your own bindings
See BindMain
Binding Property:
getter, setter, and property getter
28
More bindings
See BindToBarSample, BindSimpleListDriver
Swing Integration
See SwingFxMain, SwingTest
FXML
See LaboriousLayoutMain
With FXML
<BorderPane>
<center>
<Circle radius=“50” centerX=“50” centerY=“50”/>
</center>
</BorderPane>
public class JavaFXTest extends Application {
@Override public void start(Stage stage) {
stage.setTitle(“FXML Example”);
Parent root = FXMLLoader.load(getClass().getResource(“example.fxml"),
ResourceBundle.getBundle(“r.fxml_example"));
stage.setScene(new Scene(root));
stage.show();
}
}
Stage
Scene
Root
JavaFX Scene Builder for Rapid UI Design
SceneBuilder: WYSIWYG GUI design tool
for the JavaFX platform
Enables designing user interface screens by
simply dragging and positioning GUI
components from a palette onto a scene
Generates files in FXML format that can be
used within a project in any IDE such as
NetBeans or Eclipse
Can be used to create GUI for desktop and
Web applications
See FirstMain
Java APIs and FXML
Java APIs for JavaFX
• End-to-end Java development
• Java language features - generics,
annotations, multi-threading
• Fluent API for UI construction
• Alternative JVM supported languages
(e.g. Groovy, Scala) with JavaFX
• Leverage sophisticated Java IDEs,
debuggers and profilers
• Java APIs preserve convenient
JavaFX Script features (e.g., bind)
FXML
• Scriptable, XML-based markup
language for defining UI
• Convenient alternative to developing
UI programmatically in Java
• Easy to learn and intuitive for
developers familiar with web
technologies or other markup based
UI technologies
• Powerful scripting feature allows
embedding scripts within FXML. Any
JVM scripting language can be used,
including JavaScript, Groovy, and
Scala
Some Binding JavaFX examples
Panes, UI Controls, and Shapes
ButtonInPane
Run
36
Display a Shape
This example displays a circle in the center of the pane.
x
y
Y Axis
X Axis
(0, 0)
(x, y)
(0, 0)
Y Axis
Java
Coordinate
System
X Axis
Conventional
Coordinate
System
ShowCircle
See BorderPaneExample
Run
37
Binding Properties
JavaFX introduces a new concept called binding property
that enables a target object to be bound to a source object.
If the value in the source object changes, the target
property is also changed automatically. The target object is
simply called a binding object or a binding property.
ShowCircleCentered
Run
38
Uni/Bidirectional Binding
BidirctionalBindingDemo
Run
39
Some Layout JavaFX examples
Common Properties and Methods
for Nodes
style: set a JavaFX CSS style
rotate: Rotate a node
NodeStyleRotateDemo
Run
41
The Font Class
FontDemo
Run
42
The ImageView Class
ShowImage
Run
43
FlowPane
ShowFlowPane
Run
44
GridPane
ShowGridPane
Run
45
BorderPane
ShowBorderPane
Run
46
HBox
47
VBox
ShowHBoxVBox
Run
48
Shapes
JavaFX provides many shape classes for drawing texts,
lines, circles, rectangles, ellipses, arcs, polygons, and
polylines.
49
Text
50
Text Example
ShowText
Run
51
Rectangle
52
Circle
53
Label
The Label class defines labels.
LabelWithGraphic
Run
54
Buttons, CheckBoxes, JavaFX
examples
Button Example
ButtonDemo
Run
56
CheckBox
A CheckBox is used for the user to make a selection. Like Button,
CheckBox inherits all the properties such as onAction, text,
graphic, alignment, graphicTextGap, textFill, contentDisplay
from ButtonBase and Labeled.
57
CheckBox Example
CheckBoxDemo
Run
58
RadioButton
Radio buttons, also known as option buttons, enable you to choose a single
item from a group of choices. In appearance radio buttons resemble check
boxes, but check boxes display a square that is either checked or blank,
whereas radio buttons display a circle that is either filled (if selected) or
blank (if not selected).
59
RadioButton Example
RadioButtonDemo
Run
60
TextField
A text field can be used to enter or display a string. TextField is a
subclass of TextInputControl.
61
ListView
A list view is a component that performs basically the same function as a
combo box, but it enables the user to choose a single value or multiple
values.
62
Example: Using ListView
This example gives
a program that lets
users select
countries in a list
and display the flags
of the selected
countries in the
labels.
ListViewDemo
Run
63
ScrollBar
A scroll bar is a control that enables the user to select from a range of values. The
scrollbar appears in two styles: horizontal and vertical.
64
Scroll Bar Properties
See BindToBarSample
65
Example: Using Scrollbars
This example uses
horizontal and vertical
scrollbars to control a
message displayed on a
panel. The horizontal
scrollbar is used to move
the message to the left or
the right, and the vertical
scrollbar to move it up and
down.
ScrollBarDemo
Run
66
Case Study: Bounce Ball
Listing 15.17 gives a program that displays a bouncing
ball. You can add a slider to control the speed of the ball
movement.
blueC
s
See GamePractice.java
Slider Demo
Run
67
Example: Using Media
This example displays a
video in a view. You can use
the play/pause button to
play or pause the video and
use the rewind button to
restart the video, and use the
slider to control the volume
of the audio.
MediaDemo
See ensemble.jar
Run
68
Resources
JavaFX website: http://javafx.com
Open source project
http://openjdk.java.net/projects/openjfx/
Oracle Premier Support for Software
http://www.oracle.com/us/support/software/premier/
Blogs
– http://fxexperience.com
– http://blogs.oracle.com/javafx
Twitter: @javafx4you
Generics in Java
What is Generics
Collections can store Objects of any Type
Generics restricts the Objects to be put in a
collection
Generics ease identification of runtime errors at
compile time
Prior to the JDK 5.0 release, when you created a Collection, you
could put any object in it.
List myList = new ArrayList(10);
myList.add(new Integer(10));
myList.add("Hello, World");
Getting items out of the collection required you to use a casting
operation:
If you accidentally cast the wrong type, the program would
successfully compile, but an exception would be thrown at
runtime.
Use instanceof to avoid a blind cast.
If you want to interate over a heterogeneous data structure, be
careful!
List stringList1 = new ArrayList();
stringList1.add("Java”);
stringList1.add(new Integer(545));
Generics
J2SE 5.0 provides compile-time type safety with the Java
Collections framework through generics
Generics allows you to specify, at compile-time, the types of
objects you want to store in a Collection. Then when you add and
get items from the list, the list already knows what types of
objects are supposed to be acted on.
So you don't need to cast anything. The "<>" characters are used to
designate what type is to be stored. If the wrong type of data is
provided, a compile-time exception is thrown.
Generics (cont’d)
Example:
import java.util.*;
public class First {
public static void main(String args[]) {
List<Integer> myList = new ArrayList<Integer>(10);
myList.add(10); // OK
myList.add("Hello, World"); // NOT OK (compile time
error)
}
}
Generics (cont’d)
If you want to get rid of the warning, you can add <Object> to the
List declaration, as follows:
import java.util.*;
public class Second {
public static void main(String args[]) {
List<Object> list = new ArrayList<Object>();
list.add(10);
}
}
Here, Object is the E, and basically says that anything can be
stored in the List.
Parameterized Classes and Generics
The class ArrayList is a parameterized class
It has a parameter, denoted by Base_Type, that can
be replaced by any reference type to obtain a class for
ArrayLists with the specified base type
Starting with version 5.0, Java allows class definitions
with parameters for types
These classes that have type parameters are called parameterized class or
generic definitions, or, simply, generics
See ArrayListExample
Generics (Cont’d)
A class definition with a type parameter is stored in a
file and compiled just like any other class.
Once a parameterized class is compiled, it can be
used like any other class.
However, the class type plugged in for the type parameter must be
specified before it can be used in a program.
Doing this is said to instantiate the generic class.
Sample<String> object = new Sample<String>();
A Class Definition with a Type Parameter
See SampleDriver
A Class Definition with a Type Parameter (Cont’d)
A class that is defined with a parameter for a type is
called a generic class or a parameterized class
The type parameter is included in angular brackets after the class name
in the class definition heading.
Any non-keyword identifier can be used for the type parameter, but by
convention, the parameter starts with an uppercase letter e.g. T.
T, U, V, etc.
or K, V for maps. Or E for element.
The type parameter can be used like other types used in the definition of
a class.
Generic Class Definition: An Example
Generic Class Definition: An Example (Cont’d)
See PairDriver
Generic Class Usage: An Example
Generic Class Usage: An Example (Cont’d)
Program Output:
A Generic Constructor Name Has No Type Parameter!!!
Although the class name in a parameterized class definition has a type parameter
attached, the type parameter is not used in the heading of the constructor definition:
public Pair<T>()
A constructor can use the type parameter as the type for a parameter of the constructor,
but in this case, the angular brackets are not used:
public Pair(T first, T second)
However, when a generic class is instantiated, the angular brackets are
used:
Pair<String> pair = new Pair<STring>("Happy", "Day");
A Primitive Type Cannot be Plugged in for a Type Parameter!!!
The type plugged in for a type parameter must
always be an Object type:
It cannot be a primitive type such as int, double, or
char
However, now that Java has automatic boxing, this is not a
big restriction.
Note: Reference types can include arrays.
Limitations on Type Parameter Usage
Within the definition of a parameterized class
definition, there are places where an ordinary class
name would be allowed, but a type parameter is not
allowed.
In particular, the type parameter cannot be used in
simple expressions using new to create a new object
For instance, the type parameter cannot be used as a constructor name or
like a constructor:
T object = new T();
T[] a = new T[10];
A Generic Classes and Exceptions
It is not permitted to create a generic class with
Exception, Error, Throwable, or any
descendent class of Throwable
A generic class cannot be created whose objects are
throwable
public class GEx<T> extends Exception
The above example will generate a compiler error message
Limitations on Generic Class Instantiation
Arrays such as the following are illegal:
Pair<String>[] a =
new Pair<String>[10];
Although this is a reasonable thing to want to do, it
is not allowed given the way that Java implements
generic classes
Using Generic Classes and Automatic Boxing
See PairDriver2
Using Generic Classes and Automatic Boxing (Cont’d)
Program Output:
Multiple Type Parameters
A generic class definition can have any number of
type parameters.
Multiple type parameters are listed in angular brackets just as
in the single type parameter case, but are separated by
commas., T, U, V. or K, V
Multiple Type Parameters (Cont’d)
See TwoTypePairDriver
Multiple Type Parameters (Cont’d)
Using a Generic Class with Two Type Parameters
Program Output:
Bounds for Type Parameters
Sometimes it makes sense to restrict the possible types
that can be plugged in for a type parameter T.
For instance, to ensure that only classes that implement the
Comparable interface are plugged in for T, define a class as follows:
public class RClass<T extends Comparable>
"extends Comparable" serves as a bound on the type parameter T.
Any attempt to plug in a type for T which does not implement the Comparable
interface will result in a compiler error message.
Bounds for Type Parameters (Cont’d)
A bound on a type may be a class name (rather than an interface name)
Then only descendent classes of the bounding class may be plugged in for the type
parameters:
public class ExClass<T extends Class1>
• A bounds expression may contain multiple interfaces and up to one
class.
• If there is more than one type parameter, the syntax is as follows:
public class Two<T1 extends Class1, T2 extends Class2 &
Comparable>
Bounds for Type Parameters (Cont’d)
See MoreGenerics
Generic Interfaces
A Generic interface is just like a normal interface.
public interface Service<R,T> {
R executeService(T... args);
}
See MyServiceDriver and GenericInterfaceDriver
Generic Methods
When a generic class is defined, the type parameter
can be used in the definitions of the methods for that
generic class.
In addition, a generic method can be defined that has
its own type parameter that is not the type parameter
of any class
public static <T> T returnSomething(T t){
return t;
}
See MoreGenerics
Generic Methods
public static <T extends Number> List<Double> retunrDoubleList(List<T> list){
List<Double> doubleList = new ArrayList<>();
for (T t : list) {
doubleList.add(t.doubleValue());
}
return doubleList;
}
See MoreGenerics
A Derived Generic Class: An Example
See UnorderedPairDriver
A Derived Generic Class: An Example (Cont’d)
Program Output:
Wildcards
Wildcards help in allowing more than one type
of class in the Collections
We come across setting an upperbound and
lowerbound for the Types which can be allowed
in the collection
The bounds are identified using a ? Operator
which means ‘an unknown type’
Upperbound
List<? extends Number> means that the given
list contains objects of some unknown type
which extends the Number class
Consider the snippet
public static void doSomethingAgain(List<? extends Number> list){
for (Number number : list) {
System.out.println(number.toString());
}
}
Lowerbound
List<? super Rectangle> means that the given list
contains objects of some unknown type which is
superclass of the Rectangle class
public static void doSomethingAgainSuper(List<? super Rectangle>
list){
for (Object rec : list) {
System.out.println(rec.toString());
}
}
Data Structures
//http://stackoverflow.com/question
s/559839/big-o-summary-for-javacollections-frameworkimplementations
See package data_structs
JavaFX threading.
PbarsMain
PdfMain
ProducerConsumerMain
ThreadsMain
YelpMain
TimesMain
RsvpMain
Attributions: Some of the slides were
adapted from:
Java Generics
Compiled from Core Java
Technologies Tech Tips
Click toBy
add Text
Billy B. L. Lim