Download presentation
Presentation is loading. Please wait.
Published byΚύμα Ζωγράφου Modified over 5 years ago
1
Winter 2019 CMPE212 4/20/2019 CMPE212 – Reminders Assignment 4 on Inheritance due next Friday. Is it possible to use enums for arguments here? Exercise 9 would be good preparation for assn 4. Quiz 2 marking underway. Still… Winter 2019 CMPE212 - Prof. McLeod Prof. Alan McLeod
2
Winter 2019 CMPE212 4/20/2019 Today A nice demo that builds and tests a Generic Collection Factory class. Any questions? Lambda Functions. Coming Up: GUI Construction using JavaFX. We know enough about Java to understand and write JavaFX code. Start by looking at Event-Driven Programming in general. Winter 2019 CMPE212 - Prof. McLeod Prof. Alan McLeod
3
Second Demo – A Generic Collection Factory
Can you build an ArrayList<T> collection from argument data in a text file, without assuming anything about type T? But: A generic method cannot instantiate an array of type T. A generic method cannot instantiate a generic class typed to T. The only way to instantiate objects of type T is to use Reflection. See GenericFactory.java and TestFactory.java. Winter 2019 CMPE212 - Prof. McLeod
4
Second Demo – A Generic Collection Factory, Cont.
It is assumed that the arguments represented as text in the data file can be numbers or Strings only. (What else could they be?) It is also assumed that only one constructor for type T will be used. It would not be too hard to locate different constructors if the text file had different argument types on different lines in the file… Note that you cannot obtain the class object from type T. The code T.class or T.getClass() does not work due to what Java calls “Type Erasure”. To get around this, the desired type must be passed as an argument, like Pizza.class, to a Class<?> parameter type. Winter 2019 CMPE212 - Prof. McLeod
5
Second Demo – A Generic Collection Factory, Cont.
Factory methods generate objects, or more specifically, collections of objects. There is all kinds of neat stuff demonstrated in this code, including the use of Reflection, the use of the Object type, the generic wildcard, the construction of a generic class, the use of the Class<T> object, use of a try-with-resources block to read a text file, the use of the StringTokenizer object, annotation, a multi-catch block, for-each loops and 2D arrays. Winter 2019 CMPE212 - Prof. McLeod
6
Aside – Dynamic Casting
A Class<T> object has a method called .cast(), which accepts an Object to be cast to type T. This provides “dynamic casting”, which would be really cool if our object, T, was part of a hierarchy and our casts were within that hierarchy. We have been using “static casts” until now. Unfortunately in the demo, we could not use dynamic casts to make ints and doubles out of Strings. We had to use the “trial and error” approach to discover if a String actually represented a number. Winter 2019 CMPE212 - Prof. McLeod
7
From Before: Anonymous Class Example
public class AnonymousClassDemo { public static void main(String[] args) { MessageSender ms = new MessageSender() { public void sendGreeting (String name) { System.out.println("Hello " + name + "!"); } // end sendGreeting }; // end ms, NOTE ";"! ms.sendGreeting("Alan"); } // end main } // end AnonymousClassDemo Winter 2019 CMPE212 - Prof. McLeod
8
Anonymous Class Example - Cont.
MessageSender is an interface, not an Object: public interface MessageSender { void sendGreeting (String name); } // end MessageSender interface Java 8 now has a very tidy solution to using messy anonymous classes – Lambda Functions: Winter 2019 CMPE212 - Prof. McLeod
9
The Lambda Version public class LambdaDemo { public static void main(String[] args) { MessageSender ms = name -> System.out.println("Hello " + name); ms.sendGreeting("Steve"); } // end main } // end LambdaDemo Winter 2019 CMPE212 - Prof. McLeod
10
A Lambda Function Kind of like an “anonymous method”. Syntax:
Parameters for the method first. No parameters, use { }, one parameter by itself – no brackets required, more than one use (a, b, etc.). No types required. Then the fancy -> “arrow”. Then the method body. Put more than one statement inside { }. Can even define an inner interface: Winter 2019 CMPE212 - Prof. McLeod
11
The Lambda Version, Cont.
public class LambdaDemoAgain { interface MessageSender { void sendGreeting(String aName); } // end MessageSender interface public static void main(String[] args) { MessageSender ms = name -> System.out.println("Hello " + name); ms.sendGreeting("Steve"); } // end main } // end LambdaDemoAgain Winter 2019 CMPE212 - Prof. McLeod
12
Lambda Functions, Cont. Note how the abstract method in the interface determines the structure of the lambda function – the parameters and parameter types, the method name and the lack of a return statement. These functions could be useful! (Especially when attaching events to GUI components.) Only certain interface structures can be used. Winter 2019 CMPE212 - Prof. McLeod
13
Lambda Functions, Cont. Suppose you have a method that only displays certain members of a collection, depending on a criteria that is specified outside the method and provided as an argument. You don’t want to hard code the criteria in the display method. First technique: Supply an object implementing an interface that has a “filter” method that returns a true or false. See TestFilter1.java Winter 2019 CMPE212 - Prof. McLeod
14
Lambda Functions, Cont. Second technique: TestFilter2.java – use an anonymous class instead. Third technique: TestFilter3.java – use a Lambda function. This is the best version, so far! Winter 2019 CMPE212 - Prof. McLeod
15
boolean check(Person)
Lambda Functions, Cont. But how does it work? The structure of the method implemented by the lambda function is specified by the interface type used in the displaySome method. The signature is: boolean check(Person) The compiler knows from this that the type to the left of the -> must be a Person and the expression to the right of the -> must evaluate to a boolean. Winter 2019 CMPE212 - Prof. McLeod
16
Lambda Functions, Cont. Filter is an example of a Functional Interface. These interfaces can only contain a single abstract method. Lambdas can only be created using Functional Interfaces. You can use annotation to make sure your interface is OK. Winter 2019 CMPE212 - Prof. McLeod
17
Pre-Defined Functional Interfaces
Turns out the java.util.function package has many pre-defined generic functional interfaces. See the API, svp. The one that matches our check function signature is called Predicate<T>. It has the abstract method signature: boolean test(T) See TestFilter4.java. Even better than the last best one! Winter 2019 CMPE212 - Prof. McLeod
18
Method References ArrayList.sort() accepts a Comparator<T> object that can specify the desired algorithm for comparison of objects of type T. Turns out Comparator is a Functional Interface, so you can build a lambda function for a comparator. See TestSorting.java. Winter 2019 CMPE212 - Prof. McLeod
19
Method References, Cont.
But suppose our Person class already has a method that matches the Comparator interface: public static int compareByAge(Person p1, Person p2) { return p1.age - p2.age; } In this case you can supply a Method Reference instead of building the lambda function. See TestSortingAgain.java. Winter 2019 CMPE212 - Prof. McLeod
20
Method References, Cont.
db.sort(Person::compareByAge); Wow, that was easy! Even easier than a Lambda! The method reference must match the functional interface’s specification. You can use non-static methods or methods from an instance. If you wish to supply a constructor, use: ClassName::new And you can use existing API methods! Winter 2019 CMPE212 - Prof. McLeod
21
Lambda Functions, Cont. You can have multiple lines of code in a lambda, but don’t make them too long. You can use as many lambdas as you wish when invoking a function, as long as they each match up to some functional interface. In GUI programming the most common event handler interface, EventHandler<ActionEvent> is a functional interface, so lambdas can be used to attach event code to handlers. Winter 2019 CMPE212 - Prof. McLeod
22
Event-Driven Programming
Fall 2013 CMPE212 Event-Driven Programming So far, for assignments, you have written single threaded “batch” programs – the coder (you!) controls the flow of execution. For event-driven programs, the user controls the flow by initiating events. A GUI interface consists of components contained within a frame (or “window”). Components and even the frame itself can respond to events. Winter 2019 CMPE212 - Prof. McLeod Prof. Alan McLeod
23
Possible Events Some things that can trigger code execution:
Left mouse click down on a command button. Left mouse click down on any component. Similarly for any mouse button. Similarly for holding a mouse button down. Similarly for mouse button up. Double click on a component… Cursor over a component. Cursor leaving a component. Cursor hovering over a component. Component has focus or has lost focus. Component contents have changed. Alt-key or Cntrl-key or Shift-key, etc… Winter 2019 CMPE212 - Prof. McLeod
24
Events, Cont. Most events you ignore – your interface does not have to respond to every possible keyboard and mouse initiated event – that would be crazy!! To respond to an event in code, you attach an Event Handler object to a component. When an event occurs to a component that has the focus, the handler receives an object which contains information about the source of the event (which mouse button, etc.) You decide which events are of interest and what you want your program to do when these events occur. Winter 2019 CMPE212 - Prof. McLeod
25
GUI Construction Construction of a Graphical User Interface involves:
Fall 2013 CMPE212 GUI Construction Construction of a Graphical User Interface involves: Creating the design of the window – choosing components (buttons, labels, text boxes, etc.) and where they are positioned in the window. Changing the properties, including appearance properties, of the components. Adding and linking functionality to events, where needed. Repeating these steps for each window! Connecting the program flow between windows. Winter 2019 CMPE212 - Prof. McLeod Prof. Alan McLeod
26
History of GUI Components in Java
Fall 2013 CMPE212 History of GUI Components in Java Next slide has a hierarchy of Historical Interest: These classes are part of the Component hierarchy in javax.swing Swing was a modern improvement of the older AWT (“Abstract Windows Toolkit”) classes. The following diagram is a simplified summary of the structure: Winter 2019 CMPE212 - Prof. McLeod Prof. Alan McLeod
27
java.awt javax.swing Abstract Class Concrete Class Object Component
BorderLayout FlowLayout GridLayout Container Window java.awt Frame javax.swing JFrame JComponent Winter 2019 CMPE212 - Prof. McLeod
28
javax.swing JFrame JComponent JPanel AbstractButton JLabel JMenuBar
JTextComponent JMenuItem JButton JMenu JTextArea JTextField Winter 2019 CMPE212 - Prof. McLeod
29
JavaFX JavaFX classes are no longer part of this hierarchy.
JavaFX is a bold, relatively new world of GUI coding! Swing API code will no longer be updated. Any improvements will be in JavaFX packages only. Library code was bundled with the API but recently was changed back to being a separate download (See the Resources page, which refers to JavaFX 11.) And you need to configure Eclipse to program in JavaFX (later). Winter 2019 CMPE212 - Prof. McLeod
30
JavaFX, Cont. Swing was developed mostly for enterprise/business use, not for personal use and certainly not for mobile devices. JavaFX is available in the API since Java 7. The latest is called JavaFX 12. Jazzier controls and more support for portable devices. Winter 2019 CMPE212 - Prof. McLeod
31
“Client Technologies”
For lots of links on JavaFX and Swing see: Winter 2019 CMPE212 - Prof. McLeod
32
Getting Started Using JavaFX - Topics
Overview / Installation. Start by looking at the Scene/Stage model. What is a Scene Graph? How components are laid out using Pane-based layout managers. Look at the use of CSS style sheets. Attach events to components. Look at the use of FXML files and SceneBuilder. Winter 2019 CMPE212 - Prof. McLeod
33
JavaFX Overview You can separate style and layout from functional code using *.css and *.fxml files. Very modern! Contains a rich set of tools for: Web browsing. Media playing. 2D and 3D drawing and animation. Including many visual effects. Taking advantage of hardware accelerated rendering. Winter 2019 CMPE212 - Prof. McLeod
34
JavaFX Overview, Cont. Already contains separate threads for:
The main application. Rendering. Media playback. Over 50 controls, built-in. A dozen built-in chart types. 2D and 3D transformations as well as many other visual effects can be applied to most controls. Winter 2019 CMPE212 - Prof. McLeod
35
Fall 2013 CMPE212 JavaFX - Installation You need to add e(fx)clipse to eclipse in order to have the libraries and tools you need to write JavaFX code. You don’t need SceneBuilder but might like to play with it later. See the Resources page on the course web site. The homepage for e(fx)clipse is: Winter 2019 CMPE212 - Prof. McLeod Prof. Alan McLeod
36
e(fx)clipse Version May 2018: released version 3.3.0...
Follow the instructions on the course “Resources” page. Winter 2019 CMPE212 - Prof. McLeod
37
SceneBuilder Version Latest installer build linked to the Gluon site is (June, 2018) for Java 10. A drag and drop visual editor that edits an *.fxml file in the background. SceneBuilder can be invoked from within eclipse, but essentially runs outside of eclipse. More later… Winter 2019 CMPE212 - Prof. McLeod
Similar presentations
© 2025 SlidePlayer.com. Inc.
All rights reserved.