Unit-5 JAVA FX Programming
Unit-5 JAVA FX Programming
JAVAFX EVENT
HANDLING, CONTROLS
AND COMPONENTS
Basics of JAVAFX
Layouts
Menus
GUI
Graphical User Interface (GUI)
provides user-friendly human interaction
Building Java GUIs require use of frameworks:
AWT (1996)
Swing (1998)
Extremely powerful, many extensions available
Complex to master, requires low-level handling
Hard to create visually pleasing applications
JavaFX (part of Java since JSE 8, 2014) includes:
GUI components
Event Programming
Graphics
How do GUIs work?
Render GUI
After calling the start() method, the launcher waits for the
JavaFX application to end and then calls the stop() method.
Terminating the JavaFX
application
As soon as the last window of the JavaFX application is clos
ed, the JavaFX application is stopped implicitly.
The user can turn off this function by passing the Boolean
value “False” to the static method setImplicitExit().
This method should always be called from a static context
only.
The user can also stop a JavaFX application explicitly by
practicing any of the two methods,
Platform.exit() or
System.exit(int).
JavaFX Tooling
JavaFX is supported in Netbeans.
See: http://netbeans.org/features/javafx/
Project management, composer, Language editor
StackPane Organizes nodes in the form of a stack i.e. one onto another
Properties
Type Property Setter Methods Description
Node Bottom setBottom() Add the node to the bottom of the screen
Node Centre setCentre() Add the node to the centre of the screen
Node Left setLeft() Add the node to the left of the screen
Node Right setRight() Add the node to the right of the screen
Node Top setTop() Add the node to the top of the screen
JavaFX BorderPane
Constructors
There are the following constructors in the class.
BorderPane() : create the empty layout
BorderPane(Node Center) : create the layout with the
center node
BorderPane(Node Center, Node top, Node right, Node
bottom, Node left) : create the layout with all the nodes
JavaFX Layouts
import javafx.application.Application;
import javafx.stage.*;
import javafx.scene.*;
import javafx.scene.control.*;
import javafx.scene.layout.*;
public class Layout1 extends Application{
public static void main(String[] s) {
launch(s);
}
public void start(Stage ps) throws Exception{
ps.setTitle("Border Pane");
BorderPane bp=new BorderPane();
Button b1=new Button("First"); bp.setTop(b1);
Button b2=new Button("Second"); bp.setBottom(b2);
Button b3=new Button("Third"); bp.setRight(b3);
Button b4=new Button("Four"); bp.setLeft(b4);
Button b5=new Button("Five"); bp.setCenter(b5);
Scene s1=new Scene(bp,500,500);
ps.setScene(s1);
ps.show(); } }
JavaFX Layouts
JavaFX HBox
HBox layout pane arranges the nodes in a single row.
It is represented by javafx.scene.layout.HBox class.
Properties
Property Description Setter Methods
Constructors
The HBox class contains two constructors that are given below.
new HBox() : create HBox layout with 0 spacing
new Hbox(Double spacing) : create HBox layout with a spacing
value
JavaFX Layouts
import javafx.application.Application;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.layout.HBox;
import javafx.stage.Stage;
public class Label_Test extends Application {
Constructors
The class contains only one constructor that is given below.
Public GridPane(): creates a gridpane with 0 hgap/vgap.
JavaFX GridPane
import javafx.application.Application;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.control.Label;
import javafx.scene.control.TextField;
import javafx.scene.layout.GridPane;
import javafx.stage.Stage;
public class Label_Test extends Application {
public void start(Stage primaryStage) throws Exception {
Label first_name=new Label("First Name");
Label last_name=new Label("Last Name");
TextField tf1=new TextField();
TextField tf2=new TextField();
Button Submit=new Button ("Submit");
GridPane root=new GridPane();
Scene scene = new Scene(root,400,200);
root.addRow(0, first_name,tf1); root.addRow(1, last_name,tf2);
root.addRow(2, Submit); primaryStage.setTitle("Grid Pane Example");
primaryStage.setScene(scene); primaryStage.show();
}
public static void main(String[] args) {
launch(args);
} }
JavaFX GridPane
JavaFX StackPane
The StackPane layout pane places all the nodes into a single stack
where every new node gets placed on the top of the previous node.
It is represented by javafx.scene.layout.StackPane class.
Properties
The class contains only one property that is given below along with
its setter method.
Constructors
The class contains two constructors that are given below.
StackPane()
StackPane(Node? Children)
WindowEvent
JavaFX – Event Handling
Source object: button
For Example,
Button bt = new Button(“Click the button");
bt.setOnAction(new EventHandler<ActionEvent>()
{
public void handle (ActionEvent ae)
{
…
}
}
….
Separate classes also create for event handlers and that class object
assigned to source object.
JavaFX – Event Handling
import javafx.application.Application;
import javafx.stage.Stage;
import javafx.scene.Scene;
import javafx.scene.layout.HBox;
import javafx.scene.control.Button;
import javafx.event.ActionEvent;
import javafx.scene.control.Alert;
import javafx.event.EventHandler;
import javafx.geometry.Pos;
public class HandleEvent extends Application {
public void start(Stage primaryStage) {
HBox pane = new HBox(10);
Button btOK = new Button("OK");
Button btCancel = new Button("Cancel");
OKHandlerClass handler1 = new OKHandlerClass();
btOK.setOnAction(handler1);
CancelHandlerClass handler2 = new CancelHandlerClass();
btCancel.setOnAction(handler2);
pane.getChildren().addAll(btOK, btCancel);
Scene scene = new Scene(pane);
primaryStage.setScene(scene);
primaryStage.show();
} }
JavaFX – Event Handling
class OKHandlerClass implements EventHandler<ActionEvent>
{
public void handle(ActionEvent e)
{
Alert a = new Alert(Alert.AlertType.INFORMATION);
a.setContentText("OK button clicked");
System.out.println("OK button clicked");
a.show();
}
}
class CancelHandlerClass implements EventHandler<ActionEvent>
{
public void handle(ActionEvent e)
{
Alert a = new Alert(Alert.AlertType.CONFIRMATION);
a.setContentText("CANCEL button clicked");
System.out.println("Cancel button clicked. ");
a.show();
}}
JavaFX – Event Handling
JavaFX – Event Handling
Mouse Event − This is an input event that occurs when a mouse is
clicked. It is represented by the class named MouseEvent. It includes
actions like mouse clicked, mouse pressed, mouse released, mouse
moved, mouse entered target, mouse exited target, etc.
The Node class has a wide range of event listeners for the different
types of events.
Handily they are prefixed by what event they listen for, so all mouse
event listeners begin with .onMouse, all key event listeners begin
with .onKey.
The mouseEvent object that got passed in contains information
about the event such as the x & y position.
The events you get are:
1. Mouse Pressed
2. Mouse Dragged
3. Mouse Released
4. Mouse Clicked
JavaFX – Event Handling
setOnMousePressed(new EventHandler() {
public void handle(MouseEvent e) {
pageClickEvent = true; }
});
setOnMouseDragged(new EventHandler() {
public void handle(MouseEvent e) {
pageClickEvent = false; }
});
setOnMouseReleased(new EventHandler() {
public void handle(MouseEvent e) {
if (pageClickEvent) {
goTo(page);
pageClickEvent = false;
} }
});
JavaFX – Event Handling
import javafx.application.Application;
import javafx.event.EventHandler;
import javafx.scene.Group;
import javafx.scene.Scene;
import javafx.scene.input.MouseEvent;
import javafx.scene.paint.Color;
import javafx.scene.shape.Path;
import javafx.stage.Stage;
public class MouseEv extends Application {
Path path;
public static void main(String[] args) {
launch(args);
}
public void start(Stage primaryStage) {
Group root = new Group();
Scene scene = new Scene(root, 300, 250);
path = new Path();
path.setStrokeWidth(1);
path.setStroke(Color.BLACK);
JavaFX – Event Handling
scene.setOnMouseClicked(mouseHandler);
scene.setOnMouseDragged(mouseHandler);
scene.setOnMouseEntered(mouseHandler);
scene.setOnMouseExited(mouseHandler);
scene.setOnMouseMoved(mouseHandler);
scene.setOnMousePressed(mouseHandler);
scene.setOnMouseReleased(mouseHandler);
root.getChildren().add(path);
primaryStage.setScene(scene);
primaryStage.show();
}
JavaFX – Event Handling
EventHandler<MouseEvent> mouseHandler = new EventHandler<MouseEvent>()
{
public void handle(MouseEvent mouseEvent)
{
System.out.println(mouseEvent.getEventType() + “\n"
+ "X : Y - " + mouseEvent.getX() + " : " + mouseEvent.getY() +" \n"
+ "SceneX : SceneY - " + mouseEvent.getSceneX() + " : " +
mouseEvent.getSceneY() + " \n” + "ScreenX : ScreenY - " +
mouseEvent.getScreenX() + " : " + mouseEvent.getScreenY());
}};
}
JavaFX – Event Handling
JavaFX – Event Handling
Key Event − This is an input event that indicates the key stroke
occurred on a node. It is represented by the class named KeyEvent.
This event is generated when a key is pressed, released, or typed.
Depending on the type of the event it is passed
to onKeyPressed, onKeyTyped or onKeyReleased function.
"Key typed" events are higher-level and generally do not depend on
the platform or keyboard layout.
In the simplest case, a key typed event is produced by a single key
press (e.g., 'a').
No key typed events are generated for keys that don't generate
Unicode characters (e.g., action keys, modifier keys, etc.).
"Key pressed" and "key released" events are lower-level and
depend on the platform and keyboard layout.
JavaFX – Event Handling
textField.setOnKeyPressed(new EventHandler<KeyEvent>()
{
public void handle(KeyEvent ke)
{
if (ke.getCode().equals(KeyCode.ENTER))
{
…..
} } });
method explanation
getItems() returns the items of the menu
//creating MenuBar
ManuBar menubar = new MenuBar();
//creating Menu
Menu MenuName = new Menu("Menu Name");
//creating Menu Item
MenuItem MenuItem1 = new MenuItem("Menu Item 1 Name");
//adding Menu Item to the Menu
MenuName.getItems().add(MenuItem1);
//adding Menu to the MenuBar
menubar.getMenus().add(MenuName);
JavaFX – Menu
import javafx.application.Application;
import javafx.scene.Scene; import javafx.scene.control.*;
import javafx.scene.layout.BorderPane; import javafx.stage.Stage;
public class MenuExample extends Application {
public static void main(String[] args) {
launch(args);
}
public void start(Stage primaryStage) throws Exception {
BorderPane root = new BorderPane();
Scene scene = new Scene(root,200,300);
MenuBar menubar = new MenuBar();
Menu FileMenu = new Menu("File");
MenuItem filemenu1=new MenuItem("new");
MenuItem filemenu2=new MenuItem("Save");
MenuItem filemenu3=new MenuItem("Exit");
Menu EditMenu=new Menu("Edit");
MenuItem EditMenu1=new MenuItem("Cut");
MenuItem EditMenu2=new MenuItem("Copy");
MenuItem EditMenu3=new MenuItem("Paste");
EditMenu.getItems().addAll(EditMenu1,EditMenu2,EditMenu3);
root.setTop(menubar);
FileMenu.getItems().addAll(filemenu1,filemenu2,filemenu3);
menubar.getMenus().addAll(FileMenu,EditMenu);
primaryStage.setScene(scene); primaryStage.show(); } }
JavaFX – Menu
JavaFX – Menu
import javafx.scene.layout.VBox;
import javafx.stage.Stage;
public class AddingSubMenu extends Application {
public void start(Stage primaryStage) {
primaryStage.setTitle("Adding Items to Menu Bar");
MenuBar menuBar=new MenuBar(); //creating menu bar
//creating menu for adding menu items
Menu menu=new Menu("Show");
MenuItem companyName=new MenuItem("PSNACET"); //creating menu items
MenuItem aboutPSNA=new MenuItem("About PSNACET");
MenuItem feeStructure=new MenuItem("Fee Structure");
//sub menu items for the courses
MenuItem javCourse=new MenuItem("Java");
MenuItem pythonCourse=new MenuItem("Python");
MenuItem cCourse=new MenuItem("C");
MenuItem angularCourse=new MenuItem("Angular JS");
//adding menu items to the menu
menu.getItems().add(companyName);
menu.getItems().add(aboutPSNA);
menu.getItems().add(feeStructure);
JavaFX – Menu
//adding sub menu items to the course menu
Menu subMenuCourse=new Menu("All Courses");
subMenuCourse.getItems().add( javCourse);
subMenuCourse.getItems().add(pythonCourse);
subMenuCourse.getItems().add(cCourse);
subMenuCourse.getItems().add(angularCourse);
menu.getItems().add(subMenuCourse);
//adding menu to the menu bar
menuBar.getMenus().add(menu);
//creating VBox for adding all menu bar
VBox vBox=new VBox(menuBar);
//adding scroll pane to the scene
Scene scene = new Scene(vBox, 401, 201);
primaryStage.setScene(scene);
//showing the output
primaryStage.show();
}
public static void main(String[] args) {
//invoking main method from JVM
launch(args);
} }
JavaFX – Menu
JavaFX – Menu
import javafx.application.Application; import javafx.event.ActionEvent;
import javafx.event.EventHandler; import javafx.scene.Scene;
import javafx.scene.control.Label; import javafx.scene.control.Menu;
import javafx.scene.control.MenuBar; import javafx.scene.control.MenuItem;
import javafx.scene.layout.Vbox; import javafx.stage.Stage;
public class AddingMenuEvent extends Application {
public void start(Stage primaryStage) {
primaryStage.setTitle("Adding Events to Menu items");
MenuBar menuBar=new MenuBar(); //creating menu bar
Menu menu=new Menu("Show"); //creating menu for adding menu items
MenuItem companyName=new MenuItem("PSNACET"); //creating menu items
MenuItem courses=new MenuItem("Courses");
MenuItem aboutPSNACET=new MenuItem("About PSNACET");
MenuItem feeStructure=new MenuItem("Fee Structure");
//adding menu items to the menu
menu.getItems().add(companyName);
menu.getItems().add(courses);
menu.getItems().add(aboutPSNACET);
menu.getItems().add(feeStructure);
menuBar.getMenus().add(menu); //adding menu to the menu bar
Label selectionLabel=new Label(); //creating label for adding menu item selection
JavaFX – Menu
EventHandler<ActionEvent> event = new EventHandler<ActionEvent>() {
public void handle(ActionEvent e)
{
selectionLabel.setText(“ You have " +((MenuItem)e.getSource()).getText() +" item
selected");
} };
companyName.setOnAction(event); //adding event to the menu items
courses.setOnAction(event);
aboutPSNACET.setOnAction(event);
feeStructure.setOnAction(event);
//creating VBox for adding all menu bar
VBox vBox=new VBox(menuBar, selectionLabel);
//adding scroll pane to the scene
Scene scene = new Scene(vBox, 401, 201);
primaryStage.setScene(scene);
//showing the output
primaryStage.show();
}
public static void main(String[] args) {
//invoking main method from JVM
launch(args); }}
JavaFX – Menu
JavaFX – Menu