Presentation is loading. Please wait.

Presentation is loading. Please wait.

Lecture 03 Agenda Team Projects JavaFX Generics

Similar presentations


Presentation on theme: "Lecture 03 Agenda Team Projects JavaFX Generics"— Presentation transcript:

1 Lecture 03 Agenda Team Projects JavaFX Generics
Rich video and audio media is supported on all client platforms so JavaFX needs simple ways to use media. JavaFX uses platform specific players like Windows Media Player, QuickTime and Gplayer, but will also handle software rendering if cross platform codec support is required. The Media class provides the representation of a media source file. Controls are added to this with the MediaPlayer class (start/stop, pause/resume, forward/back). MediaView makes the MediaPlayer available as a node for the scenegraph. Multiple MediaViews can use the same MediaPlayer; the design of this means it does not place a big overhead on system resources. 1

2 JavaFX is the Evolution of Java as a Rich Client Platform
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. Definition of the JavaFX platform and some of the high level sets of features. JavaFX provides the following value propositions Leverage your Java development skills: JavaFX applications are completely developed in the Java programming language, one of the most widely adopted technologies to develop and deploy software applications, which leverages standards-based programming practices and design patterns. Create without boundaries: JavaFX provides a rich set of graphics and media APIs with high-performance hardware-accelerated graphics and media engines to simplify development of immersive visual applications. Preserve investment in Java: JavaFX developers can preserve existing investments by reusing Java libraries in their JavaFX applications. They can even access native system capabilities via the Java native interface, or seamlessly connect to server-based Java EE middleware applications. Familiar Java development tools: Developers can use their favorite Java development tools, such as the NetBeans and Eclipse IDEs, for development of JavaFX applications. All the standard IDE features, including syntax highlighting, auto-completion, interactive step-through debugging, and profiling are available for JavaFX developers. Deploy on the desktop or in the browser: JavaFX applications can be deployed either as desktop applications or in-browser applets with the help of the Java browser plugin. The improved Java browser plugin provides JavaFX applications a secure way to run inside a browser. When deployed on the desktop, JavaFX applications get the benefits of better performance and native operating system integration.

3 JavaFX Features Overview
Rich video and audio media is supported on all client platforms so JavaFX needs simple ways to use media. JavaFX uses platform specific players like Windows Media Player, QuickTime and Gplayer, but will also handle software rendering if cross platform codec support is required. The Media class provides the representation of a media source file. Controls are added to this with the MediaPlayer class (start/stop, pause/resume, forward/back). MediaView makes the MediaPlayer available as a node for the scenegraph. Multiple MediaViews can use the same MediaPlayer; the design of this means it does not place a big overhead on system resources. 3

4 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: Self explanatory 4

5 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 This diagram illustrates the architectural components of the JavaFX 2.0 platform. Below the JavaFX public APIs lies the engine that runs your JavaFX code. It is composed of subcomponents that include a new high performance graphics engine, called Prism; the new small and efficient windowing system, called Glass; a media engine, and a web engine. The Quantum Toolkit ties Prism and Glass Windowing Toolkit together and makes them available to the JavaFX layer above. It also manages the threading rules related to rendering versus events handling. Prism is designed to take advantage of the latest GPUs to provide hardware accelerated graphics and minimize the load on the CPU for complex graphics operations. On Windows Prism uses Direct X for this while on other platforms (Mac, Linux) Prism uses OpenGL. On systems where there is no compatible GPU, Prism falls back to the Java2D software pipeline. So your JavaFX applications can continue to run even on older systems or systems with less resources.

6 Graphics and Media 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 New Graphics Pipeline 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 Self explanatory

7 WebView and Swing Interoperability
Embed Web content in JavaFX applications HTML rendering based on Webkit Hardware accelerated rendering using PRISM DOM access and manipulation WebView Component 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 Swing and SWT Interop Faster loading of JavaFX Web applications based on Prism Pre-loader for improved user experience with JavaFX Web applications Browser Plugin Self explanatory

8 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

9 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 Rich video and audio media is supported on all client platforms so JavaFX needs simple ways to use media. JavaFX uses platform specific players like Windows Media Player, QuickTime and Gplayer, but will also handle software rendering if cross platform codec support is required. The Media class provides the representation of a media source file. Controls are added to this with the MediaPlayer class (start/stop, pause/resume, forward/back). MediaView makes the MediaPlayer available as a node for the scenegraph. Multiple MediaViews can use the same MediaPlayer; the design of this means it does not place a big overhead on system resources. 9

10 Open Source and Standardization
JavaFX source code being contributed as part of 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 Oracle announced at JavaOne San Francisco 2011 that it would be open sourcing JavaFX. This will be done through the OpenJFX project. Oracle have also commited to standardising JavaFX through the Java Community Process to ensure that interested parties can provide input. 10

11 Adding HTML Content The Embedded Browser WebEngine WebView
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

12 Charts JavaFX provides a rich set of charting controls that simplifies the display of complex data as a single picture. 12

13 Effects... GaussianBlur InnerShadow Reflection SepiaTone 13
To improve the richness of a GUI JavaFX provides a comprehensive set of effects that can be applied to nodes. Remember that media is a node, so all of these effects can be applied to media just as easily as to shapes or controls. SepiaTone 13

14 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); Nodes can be transformed in standard ways or an affine transform matrix can be used. rect.setTranslateX(40); rect.setTranslateY(10); 14

15 Structure of an FX Application
Rich video and audio media is supported on all client platforms so JavaFX needs simple ways to use media. JavaFX uses platform specific players like Windows Media Player, QuickTime and Gplayer, but will also handle software rendering if cross platform codec support is required. The Media class provides the representation of a media source file. Controls are added to this with the MediaPlayer class (start/stop, pause/resume, forward/back). MediaView makes the MediaPlayer available as a node for the scenegraph. Multiple MediaViews can use the same MediaPlayer; the design of this means it does not place a big overhead on system resources. 15

16 Scene Graph Directed Acyclic Graph Parents and children
Representation of the GUI components The Root is at the head AWT and Swing use a container/component hierarchy for organising the GUI. Layout managers are fundamental to this, but can make development difficult and involved. JavaFX uses a scenegraph which will be familiar to developers who have programmed in 3D. The concept is that all components in the GUI are represented by nodes. Each node can have one parent and groupings can be made by attaching multiple nodes (which may themselves be parents) to a parent. Applying effects to groups of nodes is simply a matter of applying the effect to the parent node. Z ordering can also be altered within a group and for a group as a whole. 16

17 Layout Panes JavaFX provides many types of panes for organizing nodes in a container. 17

18 There are two kinds of JavaFX projects: 1/ No Fxml 2/ Fxml
Rich video and audio media is supported on all client platforms so JavaFX needs simple ways to use media. JavaFX uses platform specific players like Windows Media Player, QuickTime and Gplayer, but will also handle software rendering if cross platform codec support is required. The Media class provides the representation of a media source file. Controls are added to this with the MediaPlayer class (start/stop, pause/resume, forward/back). MediaView makes the MediaPlayer available as a node for the scenegraph. Multiple MediaViews can use the same MediaPlayer; the design of this means it does not place a big overhead on system resources. 18

19 See TabBrowserMain.java
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); JavaFX 2.0 is a pure Java API. Anyone who knows how to program in Java can use JavaFX. There are some small additions to the way an application startsm but these are minimal and easy to understand. Stage Scene Root See TabBrowserMain.java 19

20 Basic Structure of JavaFX
Application Override the start(Stage) method Stage, Scene, and Root (Node) MyJavaFX Run MultipleStageDemo Run 20

21 JavaFX Properties Rich video and audio media is supported on all client platforms so JavaFX needs simple ways to use media. JavaFX uses platform specific players like Windows Media Player, QuickTime and Gplayer, but will also handle software rendering if cross platform codec support is required. The Media class provides the representation of a media source file. Controls are added to this with the MediaPlayer class (start/stop, pause/resume, forward/back). MediaView makes the MediaPlayer available as a node for the scenegraph. Multiple MediaViews can use the same MediaPlayer; the design of this means it does not place a big overhead on system resources. 21

22 See PropertiesDriver and PropertyChangeEvent1
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 Properties are the basis for high-level binding. There are property types for all Java primitives as well as String and Object. The API for this is simple, allowing you to bind or unbind the property. Bi-directional binding is also supported. See PropertiesDriver and PropertyChangeEvent1 22

23 JavaFX Bindings Rich video and audio media is supported on all client platforms so JavaFX needs simple ways to use media. JavaFX uses platform specific players like Windows Media Player, QuickTime and Gplayer, but will also handle software rendering if cross platform codec support is required. The Media class provides the representation of a media source file. Controls are added to this with the MediaPlayer class (start/stop, pause/resume, forward/back). MediaView makes the MediaPlayer available as a node for the scenegraph. Multiple MediaViews can use the same MediaPlayer; the design of this means it does not place a big overhead on system resources. 23

24 See BillDriver and BillDriver2
Binding Binding is one of the most powerful features of JavaFX. It allows developers to specify the relationship between properties and values so that when the value changes the property is automatically modified byt the JavaFX runtime system. This is analogous to the listener pattern used extensively in AWT/Swing but requires less coding by the developer. The API is separated into a high level version that covers most of the common tasks, but does not provide total flexibility. For tasks that require complete flexibility the low-level API can be used. This, however, requires more coding. See BillDriver and BillDriver2 24

25 Line ShowLine Run 25

26 Simple Binding Example
private SimpleDoubleProperty topXProperty = new SimpleDoubleProperty(); private SimpleDoubleProperty topYProperty = Line foldLine = new Line(); foldLine.setEndX(200); foldLine.setEndY(200); foldLine.startXProperty().bind(topXProperty); foldLine.startYProperty().bind(topYProperty); ... topXProperty.set(tx); topYProperty.set(ty); Here we have a simple binding example. We create two properties that we will modify the values of. We bind these to the start X and Y co-ordinates of a line. Whenever we change the values of the properties the line’s position will automatically change (this could be, for example, through a timeline or by ising a mouse) position) See ShowLine example 26

27 Create your own bindings
Binding is one of the most powerful features of JavaFX. It allows developers to specify the relationship between properties and values so that when the value changes the property is automatically modified byt the JavaFX runtime system. This is analogous to the listener pattern used extensively in AWT/Swing but requires less coding by the developer. The API is separated into a high level version that covers most of the common tasks, but does not provide total flexibility. For tasks that require complete flexibility the low-level API can be used. This, however, requires more coding. See BindMain 27

28 Binding Property: getter, setter, and property getter
28

29 See BindToBarSample, BindSimpleListDriver
More bindings Binding is one of the most powerful features of JavaFX. It allows developers to specify the relationship between properties and values so that when the value changes the property is automatically modified byt the JavaFX runtime system. This is analogous to the listener pattern used extensively in AWT/Swing but requires less coding by the developer. The API is separated into a high level version that covers most of the common tasks, but does not provide total flexibility. For tasks that require complete flexibility the low-level API can be used. This, however, requires more coding. See BindToBarSample, BindSimpleListDriver 29

30 See SwingFxMain, SwingTest
Swing Integration Rich video and audio media is supported on all client platforms so JavaFX needs simple ways to use media. JavaFX uses platform specific players like Windows Media Player, QuickTime and Gplayer, but will also handle software rendering if cross platform codec support is required. The Media class provides the representation of a media source file. Controls are added to this with the MediaPlayer class (start/stop, pause/resume, forward/back). MediaView makes the MediaPlayer available as a node for the scenegraph. Multiple MediaViews can use the same MediaPlayer; the design of this means it does not place a big overhead on system resources. See SwingFxMain, SwingTest 30

31 See LaboriousLayoutMain
FXML Rich video and audio media is supported on all client platforms so JavaFX needs simple ways to use media. JavaFX uses platform specific players like Windows Media Player, QuickTime and Gplayer, but will also handle software rendering if cross platform codec support is required. The Media class provides the representation of a media source file. Controls are added to this with the MediaPlayer class (start/stop, pause/resume, forward/back). MediaView makes the MediaPlayer available as a node for the scenegraph. Multiple MediaViews can use the same MediaPlayer; the design of this means it does not place a big overhead on system resources. See LaboriousLayoutMain 31

32 With FXML Stage Scene Root <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(); } JavaFX also supports a markup language, FXML, which allows the layout of components to be specified separately from the code that controls them. Here is the same example of a cirlce using FXML. Stage Scene Root 32

33 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 Self explanatory See FirstMain

34 Java APIs and FXML End-to-end Java development
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 Self explanatory

35 Some Binding JavaFX examples
Rich video and audio media is supported on all client platforms so JavaFX needs simple ways to use media. JavaFX uses platform specific players like Windows Media Player, QuickTime and Gplayer, but will also handle software rendering if cross platform codec support is required. The Media class provides the representation of a media source file. Controls are added to this with the MediaPlayer class (start/stop, pause/resume, forward/back). MediaView makes the MediaPlayer available as a node for the scenegraph. Multiple MediaViews can use the same MediaPlayer; the design of this means it does not place a big overhead on system resources. 35

36 Panes, UI Controls, and Shapes
ButtonInPane Run 36

37 See BorderPaneExample
Display a Shape This example displays a circle in the center of the pane. ShowCircle Run See BorderPaneExample 37

38 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

39 Uni/Bidirectional Binding
BidirctionalBindingDemo Run 39

40 Some Layout JavaFX examples
Rich video and audio media is supported on all client platforms so JavaFX needs simple ways to use media. JavaFX uses platform specific players like Windows Media Player, QuickTime and Gplayer, but will also handle software rendering if cross platform codec support is required. The Media class provides the representation of a media source file. Controls are added to this with the MediaPlayer class (start/stop, pause/resume, forward/back). MediaView makes the MediaPlayer available as a node for the scenegraph. Multiple MediaViews can use the same MediaPlayer; the design of this means it does not place a big overhead on system resources. 40

41 Common Properties and Methods for Nodes
style: set a JavaFX CSS style rotate: Rotate a node NodeStyleRotateDemo Run 41

42 The Font Class FontDemo Run 42

43 The ImageView Class ShowImage Run 43

44 FlowPane ShowFlowPane Run 44

45 GridPane ShowGridPane Run 45

46 BorderPane ShowBorderPane Run 46

47 HBox 47

48 VBox ShowHBoxVBox Run 48

49 Shapes JavaFX provides many shape classes for drawing texts, lines, circles, rectangles, ellipses, arcs, polygons, and polylines. 49

50 Text 50

51 Text Example ShowText Run 51

52 Rectangle 52

53 Circle 53

54 Label The Label class defines labels. LabelWithGraphic Run 54 54

55 Buttons, CheckBoxes, JavaFX examples
Rich video and audio media is supported on all client platforms so JavaFX needs simple ways to use media. JavaFX uses platform specific players like Windows Media Player, QuickTime and Gplayer, but will also handle software rendering if cross platform codec support is required. The Media class provides the representation of a media source file. Controls are added to this with the MediaPlayer class (start/stop, pause/resume, forward/back). MediaView makes the MediaPlayer available as a node for the scenegraph. Multiple MediaViews can use the same MediaPlayer; the design of this means it does not place a big overhead on system resources. 55

56 Button Example ButtonDemo Run 56 56

57 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 57

58 CheckBox Example CheckBoxDemo Run 58 58

59 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 59

60 RadioButton Example RadioButtonDemo Run 60 60

61 TextField A text field can be used to enter or display a string. TextField is a subclass of TextInputControl. 61 61

62 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 62

63 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 63

64 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 64

65 Scroll Bar Properties See BindToBarSample 65 65

66 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 66

67 Case Study: Bounce Ball
Listing gives a program that displays a bouncing ball. You can add a slider to control the speed of the ball movement. blueCs See GamePractice.java Slider Demo Run 67 67

68 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 Run See ensemble.jar 68 68

69 Resources JavaFX website: http://javafx.com
Open source project Oracle Premier Support for Software Blogs A list of resources for finding more information.

70 Generics in Java

71 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

72 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:

73 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)); //be careful of the cast!!! String s1 = (String) stringList1.get(0);

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

75 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) }

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

77 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 77

78 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>(); 78

79 A Class Definition with a Type Parameter
See SampleDriver 79

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

81 Generic Class Definition: An Example
81

82 Generic Class Definition: An Example (Cont’d)
See PairDriver 82

83 Generic Class Usage: An Example
83

84 Generic Class Usage: An Example (Cont’d)
Program Output: 84

85 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"); 85

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

87 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]; 87

88 public class GEx<T> extends Exception
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 88

89 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 89

90 Using Generic Classes and Automatic Boxing
See PairDriver2 90

91 Using Generic Classes and Automatic Boxing (Cont’d)
Program Output: 91

92 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 92

93 Multiple Type Parameters (Cont’d)
See TwoTypePairDriver 93

94 Multiple Type Parameters (Cont’d)
94

95 Using a Generic Class with Two Type Parameters
Program Output: 95

96 public class RClass<T extends Comparable>
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. 96

97 public class ExClass<T extends Class1>
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> 97

98 Bounds for Type Parameters (Cont’d)
See MoreGenerics 98

99 See MyServiceDriver and GenericInterfaceDriver
Generic Interfaces A Generic interface is just like a normal interface. public interface Service<R,T> { R executeService(T... args); } See MyServiceDriver and GenericInterfaceDriver 99

100 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 100

101 Generic Methods See MoreGenerics
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 101

102 A Derived Generic Class: An Example
See UnorderedPairDriver 102

103 A Derived Generic Class: An Example (Cont’d)
Program Output: 103

104 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’

105 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()); } }

106 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()); } }

107 See package data_structs
Data Structures // See package data_structs

108 JavaFX threading. PbarsMain PdfMain ProducerConsumerMain ThreadsMain
YelpMain TimesMain RsvpMain One of our key goals is to fully align JavaFX with the Java SE platform, which will take the form of a full integration with Java 8. We also plan to file a JSR tostandardize the JavaFX APIs, with the objective to include JavaFX under the JDK 9 umbrella JSR We also want to provide a migration path for the SWT community. Just like Swing, the SWT component framework has been aging, and we think JavaFX code can be integrated in SWT applications jjust as easily as what can be done today with JavaFX and Swing We are preparing a full fledge JavaFX 3.0 release, with concurrent availability on Windows, Mac OS, and Linux, advanced data services support, such as offline data persistence and synchronization and messaging, modularity support, and more. We will also focus on providing a better developer tool chain, including the general availability release of JavaFX Scene Builder, and better integration with Java IDEs Support for modern devices interactions is one of our goals. We’ve started with hardware acceleration, but we are looking at suppoting more featutres (e.g. camera, accelerometer), as well as an easy way to publish applications for tablets and smartphones

109 Compiled from Core Java Technologies Tech Tips By Billy B. L. Lim
Java Generics Attributions: Some of the slides were adapted from: Compiled from Core Java Technologies Tech Tips By Billy B. L. Lim


Download ppt "Lecture 03 Agenda Team Projects JavaFX Generics"

Similar presentations


Ads by Google