Download presentation
Presentation is loading. Please wait.
Published byTabassum M Modified over 2 years ago
1
GUI Design using JavaFX 1
2
O UTLINE Introduction to GUI design Java AWT Java Swing JavaFX AWT vs Swing vs JavaFX Class Hierarchy Container Components 2
3
A PPLICATION D EVELOPMENT Application Program Console based GUI (Graphical User Interface) based 3
4
GUI BASED PROGRAMMING IN JAVA GUI Is An Interface That Interacts With User And Source Code. It Makes The Software User Friendly. So, Users Interact With The Interface And That Interface Interacts With Source Code. GUI BASED PROGRAMMING IN JAVA Java Abstract Window Toolkit (AWT) Java Swing JavaFX
5
AWT: A BSTRACT W INDOWING T OOLKIT It’s an API used to develop GUI for windows-based applications in the java programming language. AWT is platform dependent AWT components are heavyweight Java’s Abstract Window Toolkit provides classes and other tools for building programs that have a graphical user interface. Syntax : import java.awt.*; 5
6
S WING : It’s an API used to develop GUI for desktop-based applications in the java programming language. SWING components are lightweight Are platform independent It follows MVC architecture Extends AWT Syntax : import javax.swing.* 6
7
JAVA FX JavaFX a versatile cross OS and cross device application toolkit JavaFX comes with a rich set of GUI controls, and open source toolkits JavaFX comes with a large set of built-in GUI components, like buttons, text fields, tables, trees, menus, charts and much more. JavaFX can be styled via CSS and / or programmatically. JavaFX comes with a built-in chart library and supports 2D and 3D graphics. 7
8
JAVAFX A PPLICATION STRUCTURE 8 JavaFX application will have three major components namely Stage, Scene and Nodes as shown in the following diagram. contains all the objects of a JavaFX application data structure similar to a tree i.e. collection of nodes graphical primitive object of a JavaFX application
9
MVC A RCHITECTURE Model: Handles data and business logic. View: Presents the data to the user whenever asked for. Controller: It controls the data flow into a model object and updates the view whenever data changes. 9
10
AWT VS S WING VS JAVA FX CHARACTERISTIC AWT SWING JavaFX DEPENDENCY Platform Depen dent Platform Independent WEIGHT OF COMPONENT HeavyweightLightweight CURRENTLY IN USE Discarded Use It In A Few Places. Currently In Use PLUGGABLE Does Not Support A Pluggable Look And Feel Support Pluggable Look And Feel. Components Look The Same On All Systems Support Pluggable Look And Feel. Components Look The Same On All Systems. 10
11
AWT VS S WING VS JAVA FX CHARACTERISTIC AWT SWING JavaFX MVC Does Not Follow MVC Follow MVCFollow MVC. NO. OF COMPONENTS LessMore Than AWT More Than AWT But Less Than SWING. PACKAGEJava.Awt.PackageJavax.SwingJavafx.Util RELEASED199519972008 11
12
AWT CLASS H IERARCHY 12
13
AWT CLASS H IERARCHY ( CONT..) 13 Container The Container is a component in AWT that can contain another components like buttons, textfields, labels etc. The classes that extends Container class are known as container such as Frame, Dialog and Panel.buttons Window The window is the container that have no borders and menu bars. You must use frame, dialog or another window for creating a window. Panel The Panel is the container that doesn't contain title bar and menu bars. It can have other components like button, textfield etc. Frame The Frame is the container that contain title bar and can have menu bars. It can have other components like button, textfield etc.
14
S WING CLASS H IERARCHY 14
15
C REATING A G RAPHICAL U SER I NTERFACE GUI programming in Java is based on three concepts: Components. A component is an object that the user can see on the screen and in most cases interact with. Containers. A container is a component that can hold other components. Events. An event is an action triggered by the user, such as a key press or mouse click. Designing a graphical user interface involves creating components, putting them into containers, and arranging for the program to respond to events. 15
16
C REATING A G RAPHICAL U SER I NTERFACE Components are objects, so they’re created by invoking a constructor. A button would be created by using a constructor belonging to the Button class. The most commonly used constructor has one argument (the button’s label): Button b = new Button("Testing"); 16
17
C REATING A G RAPHICAL U SER I NTERFACE For a component to be visible, it must be added to a container (typically a frame) by the add method in swing. To detect when an event occurs, a special “listener” object can be attached to a component. When the user performs an action that involves the component, a method belonging to the listener object will be called automatically. 17
18
GUI C OMPONENT API Java: GUI component = class Properties Methods Events Button
19
U SING A GUI C OMPONENT 1. Create it 2. Configure it 3. Add children (if container) 4. Add to parent (if not JFrame) 5. Listen to it order important
20
U SING A GUI C OMPONENT 1. Create it Instantiate object: Button b = new Button(); 2. Configure it Methods: b.setText(“press me”); 3. Add it panel.add(b); 4. Listen to it Events: Listeners Button
21
C OMPONENTS OF AWT Frame Panel Button Label TextField TextArea Checkbox List Scrollbars 21
22
C OMPONENTS OF SWING jFrame jPanel jButton jLabel jTextField jTextArea jCheckbox jComboBox jRadioButtons 22
23
C OMPONENTS OF JAVAFX Button CheckBox ChoiceBox ComboBox Label ListView Menu MenuBar PasswordField 23 RadioButton TableView TabPane TextArea TextField TitledPane ToggleButton ToolBar TreeTableView TreeView
24
C OMPONENTS OF JAVAFX 24
25
RHS – SOC GUI CONSTRUCTION In general, we have two options when constructing a GUI Build it ”by hand” using Swing API Use the IDE like netbeans, eclipse, scene builder, JavaFX Using the GUI Builder is usually much easier than hand-coding the GUI
26
I NTRODUCTION TO IDE An Integrated Development Environment is a computer software to help computer programmers develop software. The Leaders: - NetBeans - Microsoft Visual Studio - Eclipse
27
I NTRODUCTION TO IDE- CONT. What does an IDE consist of: - Source code Editor. - Compiler and/or interpreter. - Build- automation tools. Optional Tools: - Debugger. - Various tools to simplify the construction of a GUI.
28
JavaFX has 3 parts A GUI builder called SceneBuilder allows drag-and-drop manipulation of widgets. A configuration language called FXML that records the widgets in the GUI, their visible attributes and their relationship to each other. A Controller class that must be completed by the programmer to bring the GUI to life. A JavaFX application has some additional parts A set of classes to describe the model, which is what the GUI allows the user to interact with. A set of cascading style sheets (CSS files) to further specify “look-and-feel”. J AVA FX P ARTS
29
J AVA FX S CENE B UILDER JavaFX Scene Builder is a standalone JavaFX GUI visual layout tool that can also be used with various IDEs including eclipse, NetBeans and IntelliJ. JavaFX Scene Builder enables you to create GUIs by dragging and dropping GUI components from Scene Builder’s library onto a design area, then modifying and styling the GUI—all without writing any code. JavaFX Scene Builder generates FXML (FX Markup Language)—an XML vocabulary for defining and arranging JavaFX GUI controls without writing any Java code.
30
J AVA FX S CENE B UILDER (C ONT.) The FXML code is separate from the program logic that’s defined in Java source code—this separation of the interface (the GUI) from the implementation (the Java code) makes it easier to debug, modify and maintain JavaFX GUI apps. Placing GUI components in a window can be tedious. Being able to do it dynamically using a configuration file makes the job much easier. No additional compilation is needed unless actions need to be programmed in the Controller.java class.
32
P ANES,UI C ONTROLS, AND S HAPES 32
33
J AVA FX A PP W INDOW S TRUCTURE ( CONT.) The Stage is the window in which a JavaFX app’s GUI is displayed It’s an instance of class Stage (package javafx.stage ). The Stage contains one active Scene that defines the GUI as a scene graph —a tree data structure of an app’s visual elements, such as GUI controls, shapes, images, video, text and. The scene is an instance of class Scene (package javafx.scene ). Controls are GUI components, such as Label s that display text, TextField s that enable a program to receive user input, Button s that users click to initiate actions, and more.
34
An application Window in JavaFX is known as a Stage. package javafx.stage A Stage contains an active Scene which is set to a Layout container. package javafx.scene The Scene may have other Layout containers for organizing Controllers in a Tree organization. Nodes with children are layout containers. Nodes without children are widgets. J AVA FX A PPLICATION L AYOUT
35
J AVA FX A PP W INDOW S TRUCTURE ( CONT.) Each visual element in the scene graph is a node —an instance of a subclass of Node (package javafx.scene ), which defines common attributes and behaviors for all nodes With the exception of the first node in the scene graph—the root node —each node in the scene graph has one parent. Nodes can have transforms (e.g., moving, rotating and scaling), opacity (whether a node is transparent, partially transparent or opaque), effects (e.g., drop shadows, blurs, reflection and lighting) and more.
36
J AVA FX CONTROLS Nodes with children are typically layout containers that arrange their child nodes in the scene. Layout containers contain controls that accept inputs or other layout containers. When the user interacts with a control, the control generates an event. Programs can respond to these events—known as event handling—to specify what should happen when each user interaction occurs. An event handler is a method that responds to a user interaction. An FXML GUI’s event handlers are defined in a so-called controller class.
37
import javafx.application.Application; import javafx.stage.Stage; import javafx.scene.Scene; import javafx.scene.layout.StackPane; import javafx.scene.control.Button; public class ButtonInPane extends Application { @Override // Override the start method in the Application class public void start(Stage primaryStage) { // Create a scene and place a button in the scene StackPane pane = new StackPane(); pane.getChildren().add(new Button("OK")); Scene scene = new Scene(pane, 200, 50); primaryStage.setTitle("Button in a pane"); // Set the stage title primaryStage.setScene(scene); // Place the scene in the stage primaryStage.show(); // Display the stage } public static void main(String[] args) { launch(args); } 37
38
D ISPLAY A S HAPE Programming Coordinate Systems start from the left- upper corner 38
39
L AYOUT P ANES JavaFX provides many types of panes for organizing nodes in a container. 39
40
F LOW P ANE 40
41
(c) Paul Fodor and Pearson Inc. 28 import javafx.application.Application; import javafx.stage.Stage; import javafx.scene.Scene; import javafx.scene.layout.FlowPane; import javafx.scene.control.Label; import javafx.scene.control.TextField; import javafx.geometry.Insets; public class ShowFlowPane extends Application { @Override public void start(Stage primaryStage) { FlowPane pane = new FlowPane(); pane.setPadding(new Insets(11, 12, 13, 14)); pane.setHgap(5); pane.setVgap(5); // Place nodes in the pane pane.getChildren().addAll(new Label("First Name:"), new TextField(), new Label("MI:")); TextField tfMi = new TextField(); tfMi.setPrefColumnCount(1); pane.getChildren().addAll(tfMi, new Label("Last Name:"), new TextField()); // Create a scene and place it in the stage Scene scene = new Scene(pane, 210, 150); primaryStage.setTitle("ShowFlowPane"); primaryStage.setScene(scene); // Place the scene in the stage primaryStage.show(); // Display the stage } public static void main(String[] args) { launch(args); } } 41
42
(c) Paul Fodor and Pearson Inc. G RID P A NE 29 42
43
(c) Paul Fodor and Pearson Inc. 30 import javafx.application.Application; import javafx.stage.Stage; import javafx.scene.Scene; import javafx.scene.layout.GridPane; import javafx.scene.control.*; import javafx.geometry.*; public class ShowGridPane extends Application { @Override public void start(Stage primaryStage) { // Create a pane and set its properties GridPane pane = new GridPane(); pane.setAlignment(Pos.CENTER); pane.setHgap(5.5); pane.setVgap(5.5); column,row// Place nodes in the pane at positions pane.add(new Label("First Name:"), 0, 0); pane.add(new TextField(), 1, 0); pane.add(new Label("MI:"), 0, 1); pane.add(new TextField(), 1, 1); pane.add(new Label("Last Name:"), 0, 2); pane.add(new TextField(), 1, 2); Button btAdd = new Button("Add Name"); pane.add(btAdd, 1, 3); GridPane.setHalignment(btAdd, HPos.RIGHT); // Create a scene and place it in the stage Scene scene = new Scene(pane); primaryStage.setTitle("ShowGridPane"); primaryStage.setScene(scene); primaryStage.show(); } public static void main(String[] args) { launch(args); }} 43
44
B ORDER P A NE 31 44
45
32 import javafx.application.Application; import javafx.stage.Stage; import javafx.scene.Scene; import javafx.scene.layout.BorderPane; import javafx.scene.layout.StackPane; import javafx.scene.control.Label; import javafx.geometry.Insets; public class ShowBorderPane extends Application { @Override public void start(Stage primaryStage) { BorderPane pane = new BorderPane(); pane.setTop(new CustomPane("Top")); pane.setRight(new CustomPane("Right")); pane.setBottom(new CustomPane("Bottom")); pane.setLeft(new CustomPane("Left")); pane.setCenter(new CustomPane("Center")); Scene scene = new Scene(pane); primaryStage.setScene(scene); primaryStage.show(); } public static void main(String[] args) { launch(args); } class CustomPane extends StackPane { public CustomPane(String title) { getChildren().add(new Label(title)); setStyle("-fx- border-color: red"); setPadding(new Insets(11.5, 12.5, 13.5, 14.5)); } 45
46
(c) Paul Fodor and Pearson Inc. H BOX AND VB OX 33 46
47
(c) Paul Fodor and Pearson Inc. 34 import javafx.application.Application; import javafx.stage.Stage; import javafx.scene.Scene; import javafx.scene.layout.BorderPane; import javafx.scene.layout.HBox; import javafx.scene.layout.VBox; import javafx.scene.control.Button; import javafx.scene.control.Label; import javafx.scene.image.Image; import javafx.scene.image.ImageView; public class ShowHBoxVBox extends Application { @Override public void start(Stage primaryStage) { BorderPane pane = new BorderPane(); HBox hBox = new HBox(15); hBox.setStyle("-fx-background-color: gold"); hBox.getChildren().add(new Button("Computer Science")); hBox.getChildren().add(new Button("CEWIT")); ImageView imageView = new ImageView(new Image("cs14.jpg")); hBox.getChildren().add(imageView); pane.setTop(hBox); VBox vBox = new VBox(15); vBox.getChildren().add(new Label("Courses")); Label[] courses = {new Label("CSE114"), new Label("CSE214"), new Label("CSE219"), new Label("CSE308")}; for (Label course: courses) { vBox.getChildren().add(course); } pane.setLeft(vBox); Scene scene = new Scene(pane); primaryStage.setScene(scene); primaryStage.show(); } 47
48
(c) Paul Fodor and Pearson Inc. SHAPES JAVAFX PROVIDES MANY SHAPE CLASSES FOR DRAWING TEXTS, LINES, CIRCLES, RECTANGLES, ELLIPSES, ARCS, POLYGONS, AND POLYLINES. 3548
49
T EXT 3649
50
(c) Paul Fodor and Pearson Inc. 37 import javafx.application.Application; import javafx.stage.Stage; import javafx.scene.Scene; import javafx.scene.layout.Pane; import javafx.scene.paint.Color; import javafx.geometry.Insets; import javafx.scene.text.Text; import javafx.scene.text.Font; import javafx.scene.text.FontWeight; import javafx.scene.text.FontPosture; public class ShowText extends Application { @Override public void start(Stage primaryStage) { Pane pane = new Pane(); pane.setPadding(new Insets(5, 5, 5, 5)); Text text1 = new Text(20, 20, "Programming is fun"); text1.setFont(Font.font("Courier", FontWeight.BOLD, FontPosture.ITALIC, 15)); pane.getChildren().add(text1); Text text2 = new Text(60, 60, "Programming is fun\nDisplay text"); pane.getChildren().add(text2); Text text3 = new Text(10, 100, "Programming is fun\nDisplay text"); text3.setFill(Color.RED); text3.setUnderline(true); text3.setStrikethrough(true); pane.getChildren().add(text3); Scene scene = new Scene(pane, 600, 800); primaryStage.setScene(scene); primaryStage.show(); }... } 50
51
L INE 38 51
52
39 import javafx.application.Application; import javafx.stage.Stage; import javafx.scene.Scene; import javafx.scene.layout.Pane; import javafx.scene.shape.Line; import javafx.scene.paint.Color; public class ShowLine extends Application { @Override public void start(Stage primaryStage) { Pane pane = new Pane(); Line line1 = new Line(10, 10, 10, 10); line1.endXProperty().bind(pane.widthProperty().subtract(10)); line1.endYProperty().bind(pane.heightProperty().subtract(10)); line1.setStrokeWidth(5); line1.setStroke(Color.GREEN); pane.getChildren().add(line1); Line line2 = new Line(10, 10, 10, 10); line2.startXProperty().bind(pane.widthProperty().subtract(10)); line2.endYProperty().bind(pane.heightProperty().subtract(10)); line2.setStrokeWidth(5); line2.setStroke(Color.GREEN); pane.getChildren().add(line2); Scene scene = new Scene(pane, 200, 200); primaryStage.setScene(scene); primaryStage.show(); } public static void main(String[] args) { launch(args); } 52
53
R ECTANG LE 4053
54
(c) Paul Fodor and Pearson Inc. 41 import javafx.application.Application; import javafx.stage.Stage; import javafx.scene.Scene; import javafx.scene.layout.Pane; import javafx.scene.text.Text; import javafx.scene.shape.Rectangle; import javafx.scene.paint.Color; import java.util.Collections; public class ShowRectangle extends Application { public void start(Stage primaryStage) { Pane pane = new Pane(); Rectangle r1 = new Rectangle(25, 10, 60, 30); r1.setStroke(Color.BLACK); r1.setFill(Color.WHITE); pane.getChildren().add(new Text(10, 27, "r1")); pane.getChildren().add(r1); Rectangle r2 = new Rectangle(25, 50, 60, 30); pane.getChildren().add(new Text(10, 67, "r2")); pane.getChildren().add(r2); for (int i = 0; i < 4; i++) { Rectangle r = new Rectangle(100, 50, 100, 30); r.setRotate(i * 360 / 8); r.setStroke(Color.color(Math.random(), Math.random(), Math.random())); r.setFill(Color.WHITE); pane.getChildren().add(r); } Scene scene = new Scene(pane, 250, 150); primaryStage.setScene(scene); primaryStage.show(); }...// main 54
55
C IRC LE 5555
56
E LLIP SE (centerX, centerY) radiusY radiusX 5656
57
ArcArc (centerX, centerY) radiusXradiusX 57 radiusYradiusY length startAngle 0 degree 57
58
P OLYGON AND P OLYLINE javafx.scene.shape.Polygon +Polygon() +Polygon(double... points) +getPoints(): ObservableList Creates an empty polygon. Creates a polygon with the given points. Returns a list of double values as x- and y-coordinates of the points. The getter and setter methods for property values and a getter for property itself are provided in the class, but omitted in the UML diagram for brevity. 5858
59
FXML FXML is a declarative XML-based language created by Oracle Corporation for defining the user interface of a JavaFX 2.0 application. It can be edited and created using the JavaFX Scene Builder 2 (downloaded separately from J2SE) Create a new JavaFX project in Netbeans and you will get 3 files: an FXML file with the UI design, a main application.java file that loads the FXML and a controller for the event handlers for the UI Nodes. 5959
60
FXML DOCUMENT : "htp://javafx.com/fxml/1"http://javafx.com/javafx/8 <Label fx:id="label" minHeight="16" minWidth="69" text="Welcome to FXML" /> 6060
61
import javafx.application.Application; import javafx.stage.Stage; import javafx.scene.Scene; import javafx.fxml.FXMLLoader; import javafx.scene.Parent; public class JavaFXApplication5 extends Application { @Override public void start(Stage stage) throws Exception { Parent root = FXMLLoader.load(getClass().getResource("FXMLDocument.fxml")); Scene scene = new Scene(root); stage.setScene(scene); stage.show(); } public static void main(String[] args) { launch(args); } import java.net.URL; import java.util.ResourceBundle; import javafx.fxml.FXML; import javafx.fxml.Initializable; import javafx.scene.control.Label; public class FXMLDocumentController implements Initializable { @FXML private Label label; @Override public void initialize(URL url, ResourceBundle rb) { } 1 } 5561
62
T HE I MAGE AND I MAGE V IEW C LASSES 62
63
(c) Paul Fodor and Pearson Inc. 25 import javafx.application.Application; import javafx.stage.Stage; import javafx.scene.Scene; import javafx.scene.layout.Pane; import javafx.scene.layout.HBox; import javafx.scene.image.Image; import javafx.scene.image.ImageView; import javafx.geometry.Insets; public class ShowImage extends Application { @Override public void start(Stage primaryStage) { // Create a pane to hold the image views Pane pane = new HBox(10); pane.setPadding(new Insets(5, 5, 5, 5)); Image image = new Image("paul.jpg"); pane.getChildren().add(new ImageView(image)); ImageView imageView2 = new ImageView(image); imageView2.setFitHeight(100); imageView2.setFitWidth(100); imageView2.setRotate(90); pane.getChildren().add(imageView2); Scene scene = new Scene(pane); primaryStage.setTitle("ShowImage"); primaryStage.setScene(scene); primaryStage.show(); } public static void main(String[] args) { launch(args); } } 63
64
J AVA ’ S E VENT H ANDLING An event source is a GUI control JavaFX: Button, ChoiceBox, ListView, etc. http://docs.oracle.com/javase/8/javafx/user-interface-tutorial/ui_controls.htm different types of sources: can detect different types of events can register different types of listeners (handlers) 6464
65
J AVA ’ S E VENT H ANDLING When the user interacts with a control (source): an event object is constructed the event object is sent to all registered listener objects the listener object (handler) responds as you defined it to 6565
66
E VENT L ISTENERS (E VENT H ANDLER ) Defined by you, the application programmer you customize the response How? Inheritance & Polymorphism You define your own listener class implement the appropriate interface define responses in all necessary methods 6666
67
E VENT O BJECTS Contain information about the event Like what? location of mouse click event source that was interacted with etc. Listeners use them to properly respond different methods inside a listener object can react differently to different types of interactions 6767
68
H ANDLING GUI E VENTS Source object: button. An event is generated by external user actions such as mouse movements, mouse clicks, or keystrokes. An event can be defined as a type of signal to the program that something has happened. Listener object contains a method for processing the event. 68
69
E VENT C LASSES 69
70
E VENT I NFORMATION An event object contains whatever properties are pertinent to the event: the source object of the event using the getSource() instance method in the EventObject class. The subclasses of EventObject deal with special types of events, such as button actions, window events, component events, mouse movements, and keystrokes. 70
71
S ELECTED U SER A CTIONS AND H ANDLERS 71
72
(c) Paul Fodor and Pearson Inc. import javafx.application.Application; import javafx.stage.Stage; import javafx.scene.Scene; import javafx.scene.layout.BorderPane; import javafx.scene.layout.HBox; import javafx.scene.layout.StackPane; import javafx.scene.control.Button; import javafx.event.ActionEvent; import javafx.event.EventHandler; import javafx.geometry.Pos;...import javafx.scene.paint.Color; import javafx.scene.shape.Circle; public class ControlCircle extends Application { private CirclePane circlePane = new CirclePane(); @Override public void start(Stage primaryStage) { HBox hBox = new HBox(); Button btEnlarge = new Button("Enlarge"); Button btShrink = new Button("Shrink"); hBox.getChildren().add(btEnlarge); hBox.getChildren().add(btShrink); btEnlarge.setOnAction(new EnlargeHandler()); BorderPane borderPane = new BorderPane(); borderPane.setCenter(circlePane); borderPane.setBottom(hBox); BorderPane.setAlignment(hBox, Pos.CENTER); Scene scene = new Scene(borderPane, 200, 150); primaryStage.setScene(scene); primaryStage.show(); } C ONTROL C IRCLE PROGRAM THAT USES TWO BUTTONS TO CONTROL THE SIZE OF A CIRCLE 58 72
73
(c) Paul Fodor and Pearson Inc. C ONTROL C IRCLE PROGRAM THAT USES TWO BUTTONS TO CONTROL THE SIZE OF A CIRCLE // Inner Class class EnlargeHandler implements EventHandler { @Override public void handle(ActionEvent e) { circlePane.enlarge(); } class CirclePane extends StackPane { private Circle circle = new Circle(50); public CirclePane() { getChildren().add(circle); circle.setStroke(Color.BLACK); circle.setFill(Color.WHITE); } public void enlarge() { circle.setRadius(circle.getRadius() + 2); } public void shrink() { circle.setRadius(circle.getRadius() > 2 ? circle.getRadius() - 2 : circle.getRadius()); } } 59 73
74
C ONTROL N ODES Input control nodes: 7474
75
L ABELED CLASS A label is a display area for a short text, a node, or both It is often used to label other controls (usually text fields) Labels and buttons share many common properties: these common properties are defined in the Labeled class 7575
76
L ABEL CLASS 7676
77
import javafx.application.Application; import javafx.stage.Stage; import javafx.scene.Scene; import javafx.scene.control.ContentDisplay; import javafx.scene.control.Label; import javafx.scene.image.Image; import javafx.scene.image.ImageView; import javafx.scene.layout.HBox; import javafx.scene.layout.StackPane; import javafx.scene.paint.Color; import javafx.scene.shape.Circle; import javafx.scene.shape.Rectangle; import javafx.scene.shape.Ellipse; public class LabelWithGraphic extends Application { @Override public void start(Stage primaryStage) { ImageView us = new ImageView(new Image("us.jpg")); Label lb1 = new Label("US\n50 States", us); lb1.setStyle("-fx-border-color: green; -fx-border-width: 2"); lb1.setContentDisplay(ContentDisplay.BOTTOM); lb1.setTextFill(Color.RED); Label lb2 = new Label("Circle", new Circle(50, 50, 25)); lb2.setContentDisplay(ContentDisplay.TOP); lb2.setTextFill(Color.ORANGE); Label lb3 = new Label("Retangle", new Rectangle(10, 10, 50, 25)); lb3.setContentDisplay(ContentDisplay.RIGHT); Label lb4 = new Label("Ellipse", new Ellipse(50, 50, 50, 25)); lb4.setContentDisplay(ContentDisplay.LEFT); 7777
78
Ellipse ellipse = new Ellipse(50, 50, 50, 25); ellipse.setStroke(Color.GREEN); ellipse.setFill(Color.WHITE); StackPane stackPane = new StackPane(); stackPane.getChildren().addAll(ellipse, new Label("JavaFX")); Label lb5 = new Label("A pane inside a label", stackPane); lb5.setContentDisplay(ContentDisplay.BOTTOM); HBox pane = new HBox(20); pane.getChildren().addAll(lb1, lb2, lb3, lb4, lb5); Scene scene = new Scene(pane, 700, 150); primaryStage.setTitle("LabelWithGraphic"); primaryStage.setScene(scene); primaryStage.show(); } public static void main(String[] args) { launch(args); } 7878
79
(c) Paul Fodor and Pearson Inc. B UTTON B ASE AND B UTTON A button is a control that triggers an action event when clicked. JavaFX provides regular buttons, toggle buttons, check box buttons, and radio buttons. The common features of these buttons are defined in ButtonBase and Labeled classes. 7979
80
import javafx.application.Application; import javafx.stage.Stage; import javafx.geometry.Pos; import javafx.scene.Scene; import javafx.scene.control.Button; import javafx.scene.image.ImageView; import javafx.scene.layout.BorderPane; import javafx.scene.layout.HBox; import javafx.scene.layout.Pane; import javafx.scene.text.Text; public class ButtonDemo extends Application { @Override public void start(Stage primaryStage) { Scene scene = new Scene(getPane(), 450, 200); primaryStage.setTitle("ButtonDemo"); primaryStage.setScene(scene); primaryStage.show(); } protected Text text = new Text(50, 50, "JavaFX Programming"); protected BorderPane getPane() { HBox paneForButtons = new HBox(20); Button btLeft = new Button("Left", new ImageView("image/left.gif")); Button btRight = new Button("Right", new ImageView("image/right.gif")); paneForButtons.getChildren().addAll(btLeft, btRight); paneForButtons.setAlignment(Pos.CENTER); paneForButtons.setStyle("-fx-border-color: green"); BorderPane pane = new BorderPane(); pane.setBottom(paneForButtons); 8080
81
Pane paneForText = new Pane(); paneForText.getChildren().add(text); pane.setCenter(paneForText); btLeft.setOnAction(e -> text.setX(text.getX() - 10)); btRight.setOnAction(e -> text.setX(text.getX() + 10)); return pane; } public static void main(String[] args) { launch(args); } 8181
82
(c) Paul Fodor and Pearson Inc. C HECK B OX A CheckBox is used for the user to make a selection (square box). CheckBox inherits all the properties from ButtonBase and Labeled: onAction, text, graphic, alignment, graphicTextGap, textFill, contentDisplay. 8282
83
import javafx.event.ActionEvent; import javafx.event.EventHandler; import javafx.geometry.Insets; import javafx.scene.control.CheckBox; import javafx.scene.layout.BorderPane; import javafx.scene.layout.VBox; import javafx.scene.text.Font; import javafx.scene.text.FontPosture; import javafx.scene.text.FontWeight; public class CheckBoxDemo extends ButtonDemo { @Override // Override the getPane() method in the super class protected BorderPane getPane() { BorderPane pane = super.getPane(); Font fontBoldItalic = Font.font("Times New Roman", FontWeight.BOLD, FontPosture.ITALIC, 20); Font fontBold = Font.font("Times New Roman", FontWeight.BOLD, FontPosture.REGULAR, 20); Font fontItalic = Font.font("Times New Roman", FontWeight.NORMAL, FontPosture.ITALIC, 20); Font fontNormal = Font.font("Times New Roman", FontWeight.NORMAL, FontPosture.REGULAR, 20); text.setFont(fontNormal); VBox paneForCheckBoxes = new VBox(20); paneForCheckBoxes.setPadding(new Insets(5, 5, 5, 5)); paneForCheckBoxes.setStyle("-fx-border-color: green"); 8383
84
CheckBox chkBold = new CheckBox("Bold"); CheckBox chkItalic = new CheckBox("Italic"); paneForCheckBoxes.getChildren().addAll(chkBold, chkItalic); pane.setRight(paneForCheckBoxes); EventHandler handler = e -> { if (chkBold.isSelected() && chkItalic.isSelected()) { text.setFont(fontBoldItalic); // Both check boxes checked } else if (chkBold.isSelected()) { text.setFont(fontBold); // The Bold check box checked } else if (chkItalic.isSelected()) { text.setFont(fontItalic); // The Italic check box checked } else { text.setFont(fontNormal); // Both check boxes unchecked } }; chkBold.setOnAction(handler); chkItalic.setOnAction(handler); return pane; // Return a new pane } // the start method is inherited from the superclass ButtonDemo public static void main(String[] args) { launch(args); } 8484
85
R ADIO B UTTON Radio buttons allow to choose a single item from a group of choices. Radio buttons display a circle that is either filled (if selected) or blank (if not selected). 8585
86
(c) Paul Fodor and Pearson Inc. import static javafx.application.Application.launch; import javafx.geometry.Insets; import javafx.scene.control.RadioButton; import javafx.scene.control.ToggleGroup; import javafx.scene.layout.BorderPane; import javafx.scene.layout.VBox; import javafx.scene.paint.Color; public class RadioButtonDemo extends CheckBoxDemo { @Override // Override the getPane() method in the super class protected BorderPane getPane() { BorderPane pane = super.getPane(); VBox paneForRadioButtons = new VBox(20); paneForRadioButtons.setPadding(new Insets(5, 5, 5, 5)); paneForRadioButtons.setStyle("-fx-border-color: green"); RadioButton rbRed = new RadioButton("Red"); RadioButton rbGreen = new RadioButton("Green"); RadioButton rbBlue = new RadioButton("Blue"); paneForRadioButtons.getChildren().addAll(rbRed, rbGreen, rbBlue); pane.setLeft(paneForRadioButtons); ToggleGroup group = new ToggleGroup(); rbRed.setToggleGroup(group); rbGreen.setToggleGroup(group); rbBlue.setToggleGroup(group); rbRed.setOnAction(e -> { if (rbRed.isSelected()) { text.setFill(Color.RED); } }); 116116 86
87
rbGreen.setOnAction(e -> { if (rbGreen.isSelected()) { text.setFill(Color.GREEN); } }); rbBlue.setOnAction(e -> { if (rbBlue.isSelected()) { text.setFill(Color.BLUE); } }); return pane; } // the start method is inherited from the superclass ButtonDemo public static void main(String[] args) { launch(args); } 8787
88
T EXT F IELD A text field can be used to enter or display a string.TextField is a subclass of TextInputControl. 8888
89
(c) Paul Fodor and Pearson Inc. import static javafx.application.Application.launch; import javafx.geometry.Insets; import javafx.geometry.Pos; import javafx.scene.control.Label; import javafx.scene.control.TextField; import javafx.scene.layout.BorderPane; public class TextFieldDemo extends RadioButtonDemo{ @Override protected BorderPane getPane() { BorderPane pane = super.getPane(); BorderPane paneForTextField = new BorderPane(); paneForTextField.setPadding(new Insets(5, 5, 5, 5)); paneForTextField.setStyle("-fx-border-color: green"); paneForTextField.setLeft(new Label("Enter a new message: ")); TextField tf = new TextField(); tf.setAlignment(Pos.BOTTOM_RIGHT); paneForTextField.setCenter(tf); pane.setTop(paneForTextField); tf.setOnAction(e -> text.setText(tf.getText())); return pane; } public static void main(String[] args) { launch(args); } } 119 89
90
T EXT A REA A TextArea enables the user to enter multiple lines of text. 9090
91
C OMBO B OX A combo box, also known as a choice list or drop-down list, contains a list of items from which the user can choose. 9191
92
L IST V IEW 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. 9292
93
(c) Paul Fodor and Pearson Inc. import javafx.application.Application; import javafx.stage.Stage; import javafx.scene.Scene; import javafx.scene.control.ListView; import javafx.scene.control.ScrollPane; import javafx.scene.control.SelectionMode; import javafx.scene.image.ImageView; import javafx.scene.layout.BorderPane; import javafx.scene.layout.FlowPane; import javafx.collections.FXCollections; public class ListViewDemo extends Application { // Declare an array of Strings for flag titles private String[] flagTitles = {"United States of America", "Canada", "China", "Denmark", "France", "Germany", "India"}; // Declare an ImageView array for the national flags private ImageView[] ImageViews = { new ImageView("image/us.gif"), new ImageView("image/ca.gif"), new ImageView("image/china.gif"), new ImageView("image/denmark.gif"), new ImageView("image/fr.gif"), new ImageView("image/germany.gif"), new ImageView("image/india.gif") }; @Override public void start(Stage primaryStage) { ListView lv = new ListView<>(FXCollections.observableArrayList(flagTitles)); 123 lv.setPrefSize(400, 400); 93
94
lv.getSelectionModel().setSelectionMode(SelectionMode.MULTIPLE); // Create a pane to hold image views FlowPane imagePane = new FlowPane(10, 10); BorderPane pane = new BorderPane(); pane.setLeft(new ScrollPane(lv)); pane.setCenter(imagePane); lv.getSelectionModel().selectedItemProperty().addListener( ov -> { imagePane.getChildren().clear(); for (Integer i: lv.getSelectionModel().getSelectedIndices()) { imagePane.getChildren().add(ImageViews[i]); } }); Scene scene = new Scene(pane, 450, 170); primaryStage.setTitle("ListViewDemo"); primaryStage.setScene(scene); primaryStage.show(); } public static void main(String[] args) { launch(args); } 9494
95
Thank You 95
Similar presentations
© 2025 SlidePlayer.com Inc.
All rights reserved.