CS3250 Lesson 6 Lectures&Notes PDF

Title CS3250 Lesson 6 Lectures&Notes
Course Java Software Development
Institution Utah Valley University
Pages 54
File Size 1.3 MB
File Type PDF
Total Downloads 73
Total Views 173

Summary

Lectures and textbook notes for Lesson 6 in Fall 2019 CS-3250 with Lynn Thackeray....


Description

1

CS-3250 Lesson 6 Lectures and Textbook Notes Table of Contents LESSON 6

2

Lecture Chapter 6 Introduction to GUI Programming 6.1 A Basic JavaFX Application 6.1.1 JavaFX Applications 6.1.2 Stage, Scene, and SceneGraph 6.1.3 Nodes and Layout 6.1.4 Events and Event Handlers 6.2 Some Basic Classes

2 4 4 4 6 7 8 10

6.2.1 Color and Pain 6.2.2 Fonts

10 12

6.2.3 Image 6.2.4 Canvas and GraphicsContext

12 13

6.2.5 CSS 6.3 Basic Events

17 18

6.3.1 Event Handling 6.3.2 Mouse Events

18 18

6.3.3 Dragging 6.3.4 Key Events

20 21

6.3.5 AnimationTimer 6.3.6 State Machines

22 22

6.4 Basic Controls 6.4.3 CheckBox and RadioButton

29 30

6.4.5 Slider 6.5 Basic Layout

31 32

6.5.1 Do Your Own Layout 6.5.2 BorderPane

33 35

6.5.3 HBox and VBox 6.5.4 GridPane and TilePane

35 40

6.6 Complete Programs JavaFX Slides

42 43

JavaFX Graphics Slides JavaFX Code Demos

44 44

2 LESSON 6 Lecture ●

Any time you use a graphical user interface, you incur a cost—there is a hit in performance and memory.



To make a GUI in Netbeans: File → New Project → JavaFX



When a button is clicked in a GUI, it is an event—it causes a state change.



Most console applications are procedural; most GUI applications are event-driven.



An event handler is code that listens for an event.



You can use a .fxml template, CSS, or use code for GUIs.



Every JavaFX program can only have one Stage.



You can have more than one Scene for the Stage.





Inside a Scene is a Parent Pane, and Node children can be placed on the Parent Pane.



So you can have multiple Parent Panes in a Scene.

A GridPane allows you to place nodes using coordinates. public class M  ain extends Application   { @Override public void start(Stage primaryStage) { GridPane = n  ew GridPane(); grid.setAlignment(Pos.CENTER); grid.setHgap(1  0); grid.setVgap(1  0); grid.setPadding(n  ew Inserts(2  5, 25, 25, 25)); Scene scene = n  ew Scene(grid, 300, 275);  Please Login: "); Text scenetitle = n  ew Text(" scenetitle.setFont(Font.font("  Tahoma", FontWeight.NORMAL, 20); Label userName = new Label("  User Name:"); TextField userTextField = new TextField(); Label pw = n  ew Label("  Password:"); PasswordField pwBox = n  ew PasswordField(); grid.add(scenetitle, 0  , 0, 2, 1); grid.add(userName, 0, 1); grid.add(userTextField, 1  , 1); //(userTextfield, column index, rowindex) grid.add(pw, 0  , 2); grid.add(pwBox, 1  , 2); grid.setGridLinesVisible(false); /  / Create button console

3

Button btn = n  ew Button("Sign in"); /  / Create layout for button so we can align it to bottom right HBox hbBtn = n  ew HBox(10) // 10 is the spacing hbBtv.setAlignment(Pos.BOTTOM_RIGHT); hbBtn.getChildren().add(btn); grid.addhbBtn, 1  , 4); final Text actiontarget = n  ew Text(); grid.add(actiontarget, 1  , 6  );  btn.setOnAction(event -> { actiontarget.setFill(Color.BLUEVIOLET); actiontarget.setText("  Sign in button pressed."); }); primaryStage.setTitle("  JavaFX Login Form"); primaryStage.setScene(scene) primaryStage.show() }  ublic static void main(String args[] { p launch(args); } }



To use a CSS file: scene.getStylesheets().add(Login.class.getResource("Login.css").toExternalForm();



Using a CSS file decouples the look and feel of your look and code (your code can have different "skins").

Image ●

Creating an image: File file = new File("image.jpg"); Image image = new Image(file.toURI().toString());

Panes ●

A StackPane allows you to lay objects on top of each other.



A BorderPane has margins. The margins stay relative to the size of the pane.



A FlowPane wraps objects. Use if you have a series of buttons. ○

Nodes are laid out consecutively. Can be in rows or columns.

Blended Shapes Commands ●

ADD

4 ●

MULTIPLY



SRC_ATOP



SRC_OVER



SCREEN

Chapter 6 Introduction to GUI Programming ●

GUI programs differ from traditional "straight-through" programs. One big difference is that GUI programs are event-driven. That is, user actions such as clicking on a button or pressing a key on the keyboard generate events, and the program must respond to these events as they occur.



Event-driven programming builds on all the skills you have learned in the first five chapters of this text. You need to be able to write the methods that respond to events. Objects are everywhere in GUI programming. Events are objects. Colors and fonts are objects. GUI components such as buttons and menus are objects. Events are handled by instance methods contained in objects. In Java, GUI programming is object-oriented programming.



Java has had several "toolkits" for building GUI program. This textbook uses J avaFX as its toolkit.

6.1 A Basic JavaFX Application ●

A GUI program offers a much richer type of user interface, where the user uses a mouse and keyboard (or other input devices) to interact with GUI components such as windows, menus, buttons, check boxes, text input boxes, scroll bars, and so on.

6.1.1 JavaFX Applications ●

A JavaFX program (or "application") is represented by an object of type A  pplication, which is defined in the package javafx.application. Application is an abstract class, which defines, among other things, one abstract instance method, named start(). To create a JavaFX program, you need to create a class that extends Application and provides a definition for the start() method



The class that you write to create a JavaFX application also typically includes a main() method that simply "launches" the application: public static void main(String[] args) { launch(args); }



When this main() routine is executed, the launch() method creates a new thread, called the JavaFX application thread.

5 ○

A thread can execute a sequence of instructions that can be run in parallel with other threads.



It is important that anything that affects the GUI be done on the JavaFX application thread. The launch() method then creates the object that represents the application; that object is an instance

of the class that contains the call to the launch() method. The start() method of that object is then called on the JavaFX application thread, and it is the responsibility of that start() method to set up the GUI and open a window on the screen. ●

Example JavaFX application: import import import import import import import import import import

javafx.application.Application; javafx.scene.Scene; javafx.stage.Stage; javafx.application.Platform; javafx.scene.layout.BorderPane; javafx.scene.layout.HBox; javafx.geometry.Pos; javafx.scene.control.Label; javafx.scene.control.Button; javafx.scene.text.Font;

public class   HelloWorldFX extends   Application { public void start(Stage stage) { Label message = new Label("First FX Application!"); message.setFont( new Font(40) ); Button helloButton = new Button("Say Hello"); helloButton.setOnAction( e -> message.setText("Hello World!") ); Button goodbyeButton = new Button("Say Goodbye"); goodbyeButton.setOnAction( e -> message.setText("  Goodbye!!") ); Button quitButton = n  ew Button("Quit"); quitButton.setOnAction( e -> Platform.exit() ); HBox buttonBar = new HBox( 20, helloButton, goodbyeButton, quitButton ); buttonBar.setAlignment(Pos.CENTER); BorderPane root = new BorderPane(); root.setCenter(message); root.setBottom(buttonBar); Scene scene = n  ew Scene(root, 450, 200); stage.setScene(scene); stage.setTitle("JavaFX Test"); stage.show(); } // end start();

6

public static void main(String[] args) { launch(args); // Run this Application. } } // end class HelloWorldFX



The first thing that you will notice is the large number of imports at the start of the program, all from subpackages of the javafx package. A typical JavaFX program uses many classes from such packages.

6.1.2 Stage, Scene, and SceneGraph ●

AS  tage object represents a window on the computer's screen. The stage that is passed as a parameter to start() is constructed by the system. It represents the main window of a program, and is often referred to as the "primary stage." A program can create other windows by constructing new objects of type Stage.



A window is an area on the screen that can be filled with content. It can contain GUI components such as menus, buttons, and text input boxes, as well as drawing areas. ○

Although the primary stage is created before start() is called, the window does not have any content, and it is not yet visible on the screen.



The start() method is responsible for adding content to the window and making it visible. ○

The very last line of start() in the HelloWorldFX program, stage.show()  , is what makes the window visible.



The rest of the method creates content, adds the content to the window, and sets various configuration options for the content and for the window itself. For example, the line





stage.setTitle("JavaFX Test");



sets the text that will appear in the title bar at the top of the window.

A stage shows a scene, which fills its content area and serves as a container for the GUI components in the window. A scene is represented by an object of type Scene. In the sample program, the statement





stage.setScene(scene);



sets the scene that will be displayed in the content area of the stage.

A scene can be filled with things called GUI c omponents, such as buttons and menu bars. Each component is represented by an object belonging to a JavaFX class. ○

For example, a push button such as the "Say Hello" button in the sample program, is represented by an object belonging to the class Button, from the package

7 javafx.scene.control. Some components, such as the object buttonBar of type

HBox, are containers. A container represents a region in the window that can contain other components, including other containers. ○

A window contains GUI components, inside containers, which can be inside bigger containers, each represented by an object. All of these objects make up something called the scene graph for the window. ■

The s cene graph shows the containment relationships among all the components in the scene.



A scene contains a single "root" component, which is a container that contains all of the other components in the scene. In the sample program, the root component is named root (although of course that is not required), and the root of the scene is set when the Scene object is constructed: ○

Scene scene = new Scene(root, 450, 200);



The numbers in this constructor specify the width and the height of the scene, in pixels. The numbers can be omitted, in which case the size will be computed based on the contents of the scene.

6.1.3 Nodes and Layout ●

Objects that can be part of a scene graph are referred to as nodes. Scene graph nodes must belong to one of the subclasses of javafx.scene.Node. Scene graph objects that can act as containers must belong to one of the subclasses of javafx.scene.Parent, which is a subclass of Node  . ○

The nodes that are contained in a parent are called children of that node. The root node in a scene graph must be a Parent.



The buttons in HelloWorldFX are represented by objects of type Button, which is a subclass of Parent. ○

The constructor that is used to create the button objects specifies the text that is displayed on the button.



Similarly, message is a node of type Label, from package javafx.scene.control, whose purpose is simply to passively display a String. ■

One of the properties of a Label object is a font, which specifies the size and style of the characters in the displayed string. The font for the text is set by calling the label's setFont() method. The Font constructor that is used in the sample program, new Font(40), takes a parameter that specifies the size of the font.



Containers are Nodes which can have other nodes as children. The act of arranging a container's children on the screen is referred to as l ayout.

8 ○ ●

Layout means setting the size and location of the components inside the container.

While it is possible for a program to set the sizes and locations directly, it is more commonly done automatically by the container. Different containers implement different layout policies. For example, an HBox is a container that simply arranges the components that it contains in a horizontal row. In the constructor HBox buttonBar = new HBox( 20, helloButton, goodbyeButton, quitButton );



the first parameter specifies the size of a gap that the HBox will place between its children, and the remaining parameters are nodes to be added as children of the container.



A BorderPane is a container that implements a completely different layout policy. A BorderPane can contain up to five components, one in the center of the pane and up to four more placed at the top, at the bottom, to the left, and to the right of the center. In the sample program, the root of the scene is a BorderPane and components are added in the pane's center and bottom positions with the statements root.setCenter(message); root.setBottom(buttonBar);



Layout is configurable by a large number of options. The sample program has only one example of this, ○

buttonBar.setAlignment(Pos.CENTER);



This command centers the buttons within the HBox; without it, they would be shoved over to the left edge of the window.



Pos, short for "position," is an enumerated type. JavaFX uses many enumerated types for specifying various options.

6.1.4 Events and Event Handlers ●

In addition to setting up the physical layout of the window, the start() method configures event handling. ○

In HelloWorldFX, an event occurs when the user clicks one of the buttons. The application must be configured to respond to, or "handle," these events. ■

Handling an event involves two objects. ●

The event itself is represented by an object that holds information about the event. For a button click, the event is of type ActionEvent, and the information that it carries is the button that was clicked. The second object is of type EventHandler, a functional interface that defines a method handle(e), where the parameter, e, is the event object.

9 ○

To program a response to an event, you can create a class that implements the EventHandler interface and provides a definition for the handle() method. ■

However, since EventHandler is a functional interface, the handler can alternatively be specified as a lambda expression.



Lambda expressions are very commonly used in JavaFX for writing event handlers, among other uses. For example, the lambda expression ●

e -> message.setText("Hello World!")



represents an event handler that responds to an event by changing the text of the message to read "Hello World!".



The parameter, e, is the ActionEvent object that represents the event. In this case, the parameter is not used in the response in any way, but it still has to be there to satisfy the syntax of the lambda expression.



In addition to writing the event handler, you also have to register the handler with the object that will produce the event. In this case, the object is helloButton, and the handler is registered by calling the button's setOnAction() method: ○



helloButton.setOnAction( e -> message.setText("Hello World!") );

Handlers for each of the other two buttons are set up in a similar way. Remember that in each case, there is an object that generates the event in response to a user action, an object that represents the event, and an event handler that contains the code that is executed in response to the event. This diagram summarizes how it all works:



The static exit() method in the Platform class is the preferred way to programmatically end a JavaFX program. It is preferred to System.exit() because it cleanly shuts down the application thread and gives it an opportunity to clean up by calling the application's stop() method before terminating.

10 6.2 Some Basic Classes ●

CSS style sheets can be used to control many aspects of the visual appearance of GUI components.

6.2.1 Color and Pain ●

Computer color uses an RGB  color system—a  color on a computer screen is specified by three numbers, called color components, giving the level of red, green, and blue in the color.



A color is represented by an object of type Color, from package javafx.scene.paint. In JavaFX, each color component is a double value in the range 0.0 to 1.0. A Color object also has a fourth component in the range 0.0 to 1.0, referred as the alpha color component, which is generally used to represent the transparency or opaqueness of the color when it is used for drawing. ○

When a fully opaque color (alpha component equal to 1.0) is used for drawing, the drawing color completely replaces the current color of the drawing surface.



When a fully transparent color (alpha component equal to 0.0) is used for drawing, it has no effect at all.



When the alpha component is between 0.0 and 1.0, the drawing color is combined with the current color to give the new color of the drawing surface, as if the original contents of the drawing surface were being viewed through colored, translucent glass.



A Color object can be constructed by giving its red, green, blue, and alpha components; for example, ○

Color myColor = new Color( r, g, b, a );



where r, g, b, and a are in the range 0.0 to 1.0. However, the Color class also has a number of static methods for making color objects. Static methods whose job is to create objects are sometimes called factory methods.



So instead of using the constructor, you could also say ■



and in the common case of a fully opaque color, with a equal to 1.0, you can use ■



Color myColor = Color.color( r, g, b, a );

Color myColor = Color.color( r, g, b );

These static factory methods are preferable to the constructor because they have the option of r...


Similar Free PDFs