You are on page 1of 44

JavaFX

JavaFX
A media/graphics framework for creating GUIs in Java applications.
Enables developers to design , create, test, debug, and deploy rich
client applications that operate consistently across diverse platforms.
More powerful than Swing
Used to create both desktop and web applications
Make use of FXML- new XML based mark-up
mark language for defining UIs
Steps
Import javafx.application.Application
Inherit Application in your class
Override the start method in the Application
• here u can start scene, layout or widgets
to start our java application , call this inside main method
• launch(args); );//calls the application constructor which interns starts the
application
Show the stage
JavaFX Terms
Control- set of objects.
Eg.Buttons,labels , Text
objects –Controls are
added to the layouts
Layouts-how the controls
are arranged
Scene- Layouts are added
to the scene
Stage- Scene is added to
the stage. Stage can have
several scenes
Event-triggered on some
action. Event handlers does
this.Eg:An event behind
every button
@Override
Example 1 public void start(Stage primaryStage) throws Ex
Button btn=new Button("Click me");
StackPane sp=new StackPane();
sp.getChildren().add(btn);
import javafx.application.Application;
Scene scene=new Scene(sp);
import javafx.scene.control.Button; primaryStage.setScene(scene);
import javafx.scene.layout.StackPane; primaryStage.setTitle("My First JavaFX App");
import javafx.stage.Stage; primaryStage.setWidth(500);
primaryStage.setHeight(300);
import javafx.scene.Scene;
primaryStage.show();
}
public class JavaFXApplication3 extends Application { }

public static void main(String[] args) {


launch(args);
}
ample:2 //StackPane sp=new StackPane();
x.application.Application;
VBox sp=new VBox();
x.scene.control.Button;
sp.getChildren().addAll(btn,exit);
x.scene.layout.StackPane;
Scene scene=new Scene(sp);
x.stage.Stage;
primaryStage.setScene(scene);
x.scene.Scene;
primaryStage.setTitle("My First JavaFX App"
x.event.EventHandler;
primaryStage.setWidth(500);
x.event.ActionEvent; primaryStage.setHeight(300);
x.scene.layout.VBox; primaryStage.show();
}
JavaFXApplication3 extends Application {
public JavaFXApplication3() {
tic void main(String[] args) { }
rgs); }

de
d start(Stage primaryStage) throws Exception {
btn=new Button("Click me");
exit=new Button("Exit");
OnAction(new EventHandler<ActionEvent>(){
ic void handle(ActionEvent event){
System.out.println("HelloWorld");
out-defines the way in which the components
e seen on the stage
Description
rPane Organizes nodes in top, left, right, centre and the bottom of
screen.
ane Organizes the nodes in the horizontal rows according to the
available horizontal spaces. Wraps the nodes to the next line
the horizontal space is less than the total width of the nodes
ne Organizes the nodes in the form of rows and columns.
Organizes the nodes in a single row.
It is the base class for all the layout classes.
Pane Organizes nodes in the form of a stack i.e. one onto another
Organizes nodes in a vertical column.
Layout
rPane
erPane arranges the nodes at the left, right, centre, top and bottom of the screen.
ented by javafx.scene.layout.BorderPane class.
class provides various methods like setRight(),
setRight setLeft(), setCenter(), setBottom
p()
() which are used to set the position for the specified nodes.
ntiate BorderPane class to create the BorderPane layout.

Property Setter Methods Description


Bottom setBottom() Add the node to the bottom of the screen

Centre setCentre() Add the node to the centre of the screen

eft setLeft() Add the node to the left of the screen

Right setRight() Add the node to the right of the screen

Top setTop() Add the node to the top of the screen


GridPane
GridPane sp=new GridPane();
sp.add(btn1, 0, 0);
sp.add(btn2, 0, 1);
sp.add(btn3, 1, 0);
sp.add(btn4, 1, 1);
sp.add(btn, 0, 2);
sp.add(exit, 0, 3);
sp.setVgap(10);
sp.setHgap(10);
BorderPane
BorderPane sp=new BorderPane();
();
sp.setCenter(btn);
sp.setTop(exit);
sp.setBottom(btn1);
sp.setLeft(btn2);
sp.setRight(btn3);
Anchor Pane
similar to a border pane
lets you position nodes relative to one of the edges of the pane
In a border pane, the layout area is divided into five distinct areas: top, right, bottom, left, and
center. An anchor pane does not divide the layout into distinct areas. Instead, every node in the
layout can be tied — or anchored — to one or more of the four edges of the layout area. When a
node is anchored to an edge, the anchor pane will position the node as close as possible to that
edge after allowing for other nodes.
A node can be anchored to more than one edge. For example, a node can be anchored to the top
and right edges, which will place the node in the top-right
top corner of the layout.
If a node is anchored to opposite edges (top and bottom or left and right), the node will be pulled
toward both edges of the layout. This results in the node being stretched as the size of the layout
increases.
More than one node can be anchored to each edge. In that case, the nodes will overlap as they
would in a stack pane.
Methods of AnchorPane
ample: • Add a Label named label to the anchor_pane.
• Also add a Button named button and set the top, bot
right anchor using
the setTopAnchor(), setBottomAnchor(), setLeftAnch
RightAnchor functions respectively.
RightAnchor()
abel = new Label("this is AnchorPane example"); • Set the min height and width using
orPane anchor_pane = new AnchorPane(label); the setMinHeight() and setMinWidth() function.
nchor to the label
chorPane.setTopAnchor(label, 120.0);
chorPane.setLeftAnchor(label, 10.0);
chorPane.setRightAnchor(label, 230.0);
chorPane.setBottomAnchor(label, 120.0);
tton button = new Button("button ");
anchor to the button
chorPane.setTopAnchor(button, 125.0);
chorPane.setLeftAnchor(button, 220.0);
chorPane.setRightAnchor(button, 110.0);
chorPane.setBottomAnchor(button, 125.0);
chor_pane.getChildren().add(button);
chor_pane.setMinHeight(400);
hor_pane.setMinWidth(400);
ge.setScene(scene);
e.show();
TilePane
TilePane is a layout component which lays out its child components in
a grid of equally sized cells. The JavaFX TilePane layout component is
represented by the class javafx.scene.layout.TilePane
ample: TilePane
d start(Stage primaryStage) throws Exception {
ryStage.setTitle("TilePane Experiment");
TilePane tilePane = new TilePane();
tilePane.setHgap
tilePane.setHgap(10);
n button1 = new Button("Button 1"); tilePane.setVgap
tilePane.setVgap(10);
n button2 = new Button("Button 2"); tilePane.getChildren
tilePane.getChildren().add(button1);
tilePane.getChildren
tilePane.getChildren().add(button2);
n button3 = new Button("Button 3"); tilePane.getChildren
tilePane.getChildren().add(button3);
n button4 = new Button("Button 4"); tilePane.getChildren
tilePane.getChildren().add(button4);
n button5 = new Button("Button 5"); tilePane.getChildren
tilePane.getChildren().add(button5);
tilePane.getChildren
tilePane.getChildren().add(button6);
n button6 = new Button("Button 6"); tilePane.setTileAlignment
tilePane.setTileAlignment(Pos.TOP_LEFT);

Scene scene = new Scene(tilePane, 200, 100);


primaryStage.setScene
primaryStage.setScene(scene);
primaryStage.show
primaryStage.show();
}

public static void main(String[] args) {


Application.launch
Application.launch(args);
}
Stage Methods
primaryStage.show();
primaryStage.setScene(sc);
primaryStage.setTitle(value);
primaryStage.getTitle();
primaryStage.setWidth(value);
primaryStage.setHeight(value);
primaryStage.getWidth();
primaryStage.getHeight();
primaryStage.setFullScreen(true);
primaryStage.isFullScreen();
primaryStage.close();
Other Controls……
Label
Label is a part of JavaFX package
display a short text or an
Constructor for the Label class are:

Label(): Creates an empty label


Label(String t):: Creates Label with given text.
Label(String t, Node g):: Creates a Label with the given text and graphi
image, it is a non-editable
editable text control
bel and Text l.setTextFill(Color.ORANGE
Color.ORANGE);
Label b = new Label("", iw);
b.setMinWidth(1);
afx.scene.paint.Color; //Setting font to the label b.setMinHeight(1);
afx.scene.text.Font; //Font font = Font.font
Font.font("Brush Script MT", btn.setOnAction(new
FontWeight.BOLD, FontPosture.REGULAR,
FontPosture.REGULAR 25);EventHandler<ActionEvent>(){
s JavaFXApplication3 extends
n{
l.setFont(new
(new Font("Arial", 24)); public void handle(ActionE
// create a input stream l.setText(t.getText());
atic void main(String[] args) { FileInputStream input = new
args); FileInputStream("C:\\UsersUsers\\Admin\\Documents\\NetBeansPr
}
ojects\\FirstJava\\home.jpg");
home.jpg"); });
// load the image VBox sp=new VBox ();
ide
Image i = new Image(input); sp.getChildren().addAll(btn,t,l,
oid start(Stage primaryStage) throws // displays ImageView the image as is
{ Scene scene=new Scene(sp);
ImageView iw = new ImageView(i); primaryStage.setScene(scene)
btn=new Button("Click me"); iw.setX(170);//Setting
(170);//Setting the position of the imageprimaryStage.setTitle("My Firs
=new Label(); iw.setY(10); primaryStage.setWidth(500);
eld t=new TextField(); //resizes the image to have width of 150 while preserving
primaryStage.setHeight(300);
the ratio primaryStage.show();
axWidth(200);
iw.setFitWidth(150);
(150); }
WrapText(true); iw.setPreserveRatio(true)
(true); }
xt("My Label"); // create a label
Alignment(TextAlignment.CENTER);
TextField and Password
TextField uname=new TextField ();
PasswordField pwd=new PasswordField ();
VBox root=new VBox();
root.getChildren().addAll(uname,pwd
uname,pwd);
Scene sc = new Scene(root, 200, 200);
primaryStage.setScene(sc);
primaryStage.show();
Button Methods
Btn.setText(“Text”);
Btn.setWrapText(true);
Btn.setDisable(true);
Add image to the button
FileInputStream input = new FileInputStream(“Path
FileInputStream of image");
Image i = new Image(input);
ImageView iw = new ImageView(i); );
Button btn=new Button(“Submit”,iw iw);
method explanation

Radiobutton getText()
returns the textLabel for
button

Label l=new Label(); returns whether the


isSelected()
ToggleGroup group=new ToggleGroup(); radiobutton is selected or
RadioButton opt1=new RadioButton("Roger");
RadioButton opt2=new RadioButton("Reinhard");
RadioButton opt3=new RadioButton("Andrea");
setSelected(boole sets whether the radiobu
RadioButton opt4=new RadioButton("Emmauelle");
an b) selected or not
RadioButton opt5=new RadioButton("Jennifer");
opt1.setToggleGroup(group); setToggleGroup(T sets the toggle group for
opt2.setToggleGroup(group); oggleGroup tg) radio button
opt3.setToggleGroup(group);
opt4.setToggleGroup(group);
opt4.setToggleGroup(group); Toggles the state of the ra
VBox root=new VBox(); button if and only if the
root.getChildren().addAll(l,opt1,opt2,opt3,opt4,opt5); fire() RadioButton has not alrea
selected or is not part of
ToggleGroup.
on click of a Radio Button
Scene sc = new Scene(root, 200,, 200);
// add a change listener
group.selectedToggleProperty().addListener
addListener(new ChangeListener<Toggle>()
{
public void changed(ObservableValue
ObservableValue<? extends Toggle> ob, Toggle o, To
{
RadioButton rb = (RadioButton
RadioButton)group.getSelectedToggle();

if (rb != null) {
String s = rb.getText();

// change the label


l.setText(s + " selected");
}
}
});
// set the scene
s.setScene(sc);
s.show();
on click of a Button Button btn=new
=new Button("submit");
btn.setOnAction(new
(new EventHandler<ActionEvent>(){
public void handle(ActionEvent
handle( event)
{

if(opt1.isSelected()){
l.setText(opt1.getText()+"Selected");
(opt1.getText()+"Selected");
l.setFont(new
(new Font("Arial",20));
}
else
l.setText("Choose
("Choose an option");
}
});

Scene sc=new
=new Scene(root,200,200);
primaryStage.setScene
primaryStage.setScene(sc);
primaryStage.show
primaryStage.show();
}
CheckBox
Label l=new Label();
CheckBox opt1=new CheckBox("Tagore");
("Tagore");
CheckBox opt2=new CheckBox("Raman");
("Raman");
CheckBox opt3=new CheckBox("Khorana");
("Khorana");
CheckBox opt4=new CheckBox("Teresa");
("Teresa");
CheckBox opt5=new CheckBox("Chandrasekhar");
("Chandrasekhar");
CheckBox opt6=new CheckBox("Abhijit");
("Abhijit");
VBox root=new VBox();
Button btn=new
=new Button("submit");
root.getChildren().addAll(l,btn,opt1,opt2,opt3,opt4,opt5,opt6);
(l,btn,opt1,opt2,opt3,opt4,opt5,opt6);
nAction(new
ndler<ActionEvent>(){
if(opt5.isSelected()){
blic void handle(ActionEvent event){
selecteditems+=opt6.getText();
String selecteditems="";
selecteditems+=" "; }
f(opt1.isSelected()){
selecteditems+=opt1.getText();
if(
if(selecteditems.isEmpty())
l.setText("Select your option");
selecteditems+=" ";
else
f(opt2.isSelected()){
l.setText("You have selected"+ selectedi
selecteditems+=opt2.getText(); }
selecteditems+=" "; });
Scene sc=new
=new Scene(root,200,200);
f(opt3.isSelected()){ primaryStage.setScene
primaryStage.setScene(sc);
selecteditems+=opt3.getText(); primaryStage.show
primaryStage.show();
selecteditems+=" ";

f(opt4.isSelected()){
selecteditems+=opt4.getText();
selecteditems+=" ";
ComboBox
ComboBox<String> desert=new ComboBox<String>();
ComboBox
desert.getItems().add("Cake");
desert.getItems().add("Cookies");
().add("Cookies");
desert.getItems().add("Doughnuts");
().add("Doughnuts");
desert.getItems().add("Pies");
ComboBox
etOnAction(new EventHandler<ActionEvent
ActionEvent>()

public void handle(ActionEvent event){


if(desert.getValue()==null){
l.setText("Select your option");
}
VBox root=new VBox();
else
root.getChildren().addAll(btn,l,d
l.setText(desert.getValue()); Scene sc=new Scene(root,300,2
} primaryStage.setScene(sc);
primaryStage.show();
);
OnMouseClick Event
1=new Label("Move your mouse here");
bel l2=new Label();
setOnMouseClicked(new EventHandler<Event>(){
<Event>(){

BorderPane root=new BorderPan


@Override root.setCenter(l1);
public void handle(Event event) { root.setTop(l2);
Scene sc=new Scene(root,30
l2.setText(l1.getText());
primaryStage.setScene(sc);
l2.setTextFill(Color.RED); primaryStage.show();
l2.setFont(new Font("Arial",20));
}
stView • ListView<String>
<String> Country=new ListView<>();
• Country.getItems().add("Ram
().add("Ram Nath Kovind");//add all elements to the list
• Country.getItems().add("
().add("Pranab Mukherjee");
• Country.getItems().add("
().add("Pratibha");
• Country.getItems().add("Abdul
().add("Abdul Kalam");
• Country.getItems().add("K
().add("K R Narayanan");
• Country.getItems().add("Shankar
().add("Shankar Dayal Sharma");
• Country.getItems().add("R.
().add("R. Venkataraman");
• Country.getItems().add("
().add("Giani Zail Singh");
• Country.getItems().add("
().add("Neelam Sanjeeva Reddy");
• Country.getItems().add("
().add("Fakhruddin Ali Ahmed");
• Country.getItems().add("V.
().add("V. V. Giri");
• Country.getItems().add("
().add("Zakir Husain");
• Country.getItems().add("
().add("Radhakrishnan");
• Country.getItems().add("
().add("Rajendra Prasad");
• Button bt1=new Button("Submit");
stView
setOnAction(event -> {
ObservableList selectedIndices = Country.getSelectionModel().getSelectedIndic
Country.getSelectionModel
for(Object o : selectedIndices){
System.out.println(Country.getSelectionModel
Country.getSelectionModel().getSelectedItem());
}
});
//enables user to select multiple values from list
Country.getSelectionModel().setSelectionMode
setSelectionMode(SelectionMode.MULTIPLE);
VBox root=new VBox(Country,bt1);
Scene sc=new Scene(root,700,500);
primaryStage.setScene(sc);
primaryStage.show();
HyperLink
Hyperlink vit=new Hyperlink
(“https://www.youtube.com/channel/UCA9pirjKrKlg2bCvPKRDkyg
www.youtube.com/channel/UCA9pirjKrKlg2bCvPKRDkyg”);
vit.setOnAction(e -> {
System.out.println("The
("The Hyperlink was clicked!");
});
VBox root=new Vbox(vit);
Scene sc = new Scene(root, 200, 200);
200
primaryStage.setScene(sc);
primaryStage.show();
Switching between scenes
witching between Scenes--Example-1
vafx.application.Application; @Override
public void start(Stage primaryStage) throws Exce
vafx.scene.Scene;
Label l1=new Label("You are welcome to scene
vafx.scene.control.Button; Button btn1=new Button("Go to Scene2");
vafx.scene.control.Label; btn1.setOnAction(e->primaryStage.setScene(sc
vafx.scene.layout.StackPane; VBox root1=new VBox(100);
vafx.scene.layout.VBox; root1.getChildren().addAll(l1,btn1);
vafx.stage.Stage; scene1=new Scene(root1,500,400);

Label l2=new Label("You are welcome to scene


ss Switchscene1 extends Application{
Button btn2=new Button("Go to Scene1");
scene1,scene2; btn2.setOnAction(e->primaryStage.setScene(sc
static void main(String[] args) { StackPane root2=new StackPane();
ch(args); root2.getChildren().addAll(l2,btn2);
scene2=new Scene(root2,100,100);

primaryStage.setScene(scene1);
primaryStage.show();
}
}
Switching between Scenes-Example
Example-2
// Defining the Submit button
s Scenedemo extends Button submit = new Button("Su
n{ primaryStage throws Exception { submit.setOnAction(e -> {
public void start(Stage primaryStage)
dow; window = primaryStage; first = firstName.getText();
tton; window.setTitle("Flight
("Flight Assistant"); last = lastName.getText();
//scene 1 createNewScene();
arButton; // Creating a GridPane container });
ne, scene1; GridPane grid = new GridPane(); GridPane.setConstraints(submit
grid.setPadding(new
(new Insets(50, 50, 50, 50)); grid.getChildren().add(submit);
, last;
grid.setVgap(5);
grid.setHgap(5); // Defining the Clear button
ic void main(String[] args) clearButton = new Button("Clea
// Defining the Name text field GridPane.setConstraints(clearBu
final TextField firstName = new TextField();
TextField clearButton.setOnAction(event
args);
firstName.setPromptText("Enter
("Enter your first name."); firstName.clear();
GridPane.setConstraints(firstName
firstName, 0, 0); lastName.clear();
grid.getChildren().add(firstName); ); });
grid.getChildren().add(clearButt
// Defining the Last Name text field scene = new Scene(grid, 300, 15
final TextField lastName = new TextField();
TextField primaryStage.setScene(scene);
lastName.setPromptText("Enter
("Enter your last name."); primaryStage.show();
GridPane.setConstraints(lastName
lastName, 0, 1);
grid.getChildren().add(lastName); ); }
lic void createNewScene() {
abel title = new Label();
tle.setText("Welcome
("Welcome " + first + " " + last + " to Java Programming!");
tle.setFont(Font.font("Times New Roman", 38));

/ button showing pending request


utton = new Button();
utton.setText("Goto Previous Scene");
/ switch to scene 2
utton.setOnAction(e -> window.setScene(scene));

/ Layout 1 and adding elements to the layout


Box layout2 = new VBox(200);
ayout2.getChildren().addAll(title,button);
ayout2.setAlignment(Pos.CENTER);

/ setting the layout size for the first scene


cene1 = new Scene(layout2, 900, 650);
window.setScene(scene1);
ox root = new VBox(5);
ot.setPadding(new Insets(5));
enuBar menuBar = new MenuBar();
Example: A scene with
enuBar.getMenus().add(new Menu("File"));
multiple layouts
xtArea textArea = new TextArea();
Box.setVgrow(textArea, Priority.ALWAYS);//The vertical
riority for the child.

nchorPane bottomRow = new AnchorPane();


bel table1 = new Label("Table 1");
ble1.setStyle("-fx-background-color: gray");
ble1.setMinSize(200, 200);
bel table2 = new Label("Table 2");
ble2.setStyle("-fx-background-color: gray");
ble2.setMinSize(200, 200);

chorPane.setLeftAnchor(table1, 0.0);
chorPane.setRightAnchor(table2, 0.0);
ttomRow.getChildren().addAll(table1, table2);
ot.getChildren().addAll(menuBar, textArea, bottomRow);
bottomRow
ene scene = new Scene(root, 800, 800);
maryStage.setScene(scene);
maryStage.show();
ateTimePicker // show week numbers
class Datetime extends Application { d.setShowWeekNumbers(true);
static void main(String[] args) { // when datePicker is pressed
d.setOnAction(event);
unch(args);

// add button and label


erride r.getChildren().add(d);
c void start(Stage primaryStage) throws Exception { r.getChildren().add(l);
create a tile pane
Scene sc = new Scene(r, 200, 200);
primaryStage.setScene(sc);
ePane r = new TilePane();
primaryStage.show();
bel l = new Label("no date selected"); }
tePicker d = new DatePicker();
entHandler<ActionEvent> event = new EventHandler<ActionEvent
ActionEvent>() {
public void handle(ActionEvent e)
}
{
// get the date picker value
LocalDate i = d.getValue();
// get the selected date
l.setText("Date :" + i);
}
JavaFX CSS Styling

JavaFX enables you to style JavaFX components using CSS, just like
you can style HTML element in web pages with CSS.
Scene Specific CSS Stylesheet
scene.getStylesheets().add("style1/button
().add("style1/button-styles.css");
//tells
tells JavaFX to look for a stylesheet file called button-styles.css
button
which is located in a directory called style1 .
JavaFX CSS Styling

Parent Specific CSS Stylesheets


Button button1 = new Button("Button 1");
Button button2 = new Button("Button 2");
VBox vbox = new VBox(button1,
(button1, button2);
vbox.getStylesheets().add("style1/button
().add("style1/button-styles.css");
/This code will set the style1/button-styles.css
style1/button stylesheet on the VBox.
/The stylesheet will thus be applied to the two buttons inside the
VBox.
JavaFX CSS Styling

Component Style Property


Example that sets the style property for a JavaFX Button :

Button button2 = new Button("Button 2");


button2.setStyle("-fx-background-color:: #0000ff");

This example sets the background color CSS property in the style
property to a blue color.
JavaFX CSS Styling
Button button3 = new Button("Button 3");
button3 .setStyle("-fx-background
background-color: pink; -fx-text-fill: white;");
Example
Button btn1 = new Button();
btn1.setText("Red");
btn1.setOnAction(new EventHandler<ActionEvent>()
EventHandler {
@Override
public void handle(ActionEvent
ActionEvent event) {
System.out.println("Red Color");
Color
btn1.setStyle("-fx-background
background-color: red; -fx-text-fill: white;");
}
});

You might also like