0% found this document useful (0 votes)
6 views89 pages

JavaFX

The document provides a comprehensive guide on using JavaFX for creating GUI applications in Java, covering topics such as creating a basic window, handling user events, using anonymous inner classes and lambda expressions, switching scenes, creating alert boxes, and communicating between multiple windows. Each topic includes code examples and explanations of key concepts like event handling, layout management, and scene transitions. The document serves as a practical introduction to building interactive applications with JavaFX.

Uploaded by

afsahhaseeb9
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
6 views89 pages

JavaFX

The document provides a comprehensive guide on using JavaFX for creating GUI applications in Java, covering topics such as creating a basic window, handling user events, using anonymous inner classes and lambda expressions, switching scenes, creating alert boxes, and communicating between multiple windows. Each topic includes code examples and explanations of key concepts like event handling, layout management, and scene transitions. The document serves as a practical introduction to building interactive applications with JavaFX.

Uploaded by

afsahhaseeb9
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 89

JavaFX is a platform for making really amazing looking GUI applications in Java.

Topic#01 Creating a Basic Window


package javafxtopics;

import javafx.application.Application;
import static javafx.application.Application.launch;
import javafx.event.ActionEvent;
import javafx.event.EventHandler;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.layout.StackPane;
import javafx.stage.Stage;

public class JavaFXTopics extends Application {


public static void main(String[] args) {
launch(args);//This is the method inside the Aplication class
}

@Override //start is Overriden method because we are inheritng it from the application class
public void start(Stage primaryStage) throws Exception {//All the code we write in here
that's the main JavaFX code
primaryStage.setTitle("Title of the window");//"Title of the window" is the Title name of
the Stage
Button button = new Button();//Here name of the Button is "button"
//we have a button and now no text on it

button.setText("Click me");//setting text on the button e.g.Click me

//To display anything on the screen need to make a layout(Layout is essantially just how you
want everything arranged on your screen)
StackPane layout = new StackPane();//StackPane is the really simple layout it's going to
position this button in the middle
layout.getChildren().add(button);//to organized everything in position call getChildren
and add the button by using add

Scene scene = new Scene(layout,350,250);//This first parameters scenes take is the layout
how do you want stuff arrranged in your scene and other two parameters are the size of your
scene 350 is the width and 250 is the height
primaryStage.setScene(scene);//setting the scene in the Window
primaryStage.show();//It just displays it to the user

//Window is called "Stage" and the content in the Window is called the "Scene"

}
}

Output:

Topic#02 Handle User Events


Whenever we click this button we want to perform so kind of action so our program becomes
interactive. So to handle these types of events we need to implement an interface called
EventHandler.
package javafxtopics;

import javafx.application.Application;
import static javafx.application.Application.launch;
import javafx.event.ActionEvent;
import javafx.event.EventHandler;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.layout.StackPane;
import javafx.stage.Stage;

public class JavaFXTopics extends Application implements EventHandler<ActionEvent> {

/*For EventHandler there are bunch of different types of events For e.g. there is a button
click and there are Mouse events whenever the
user moves their mouse around ,there is also touch events for touch devices whenever user
touch screen*/
//but of a simple button click we use <ActionEvent>
Button button;//Create button Here name of the Button is "button"

public static void main(String[] args) {


launch(args);//This is the method inside the Aplication class
}

@Override //start is Overriden method because we are inheritng it from the application class
public void start(Stage primaryStage) throws Exception {//All the code we write in here
that's the main JavaFX code
primaryStage.setTitle("Title of the window");//"Title of the window" is the Title name of
the Stage
button = new Button();//initialize the button
//we have a button and now no text on it

button.setText("Click me");//setting text on the button e.g.Click me

button.setOnAction(this);//This class will handle the button events

//To display anything on the screen need to make a layout(Layout is essantially just how you
want everything arranged on your screen)
StackPane layout = new StackPane();//StackPane is the really simple layout it's going to
position this button in the middle
layout.getChildren().add(button);//to organized everything in position call getChildren
and add the button by using add

Scene scene = new Scene(layout, 350, 250);//This first parameters scenes take is the
layout how do you want stuff arrranged in your scene and other two parameters are the size of
your scene 350 is the width and 250 is the height
primaryStage.setScene(scene);//setting the scene in the Window
primaryStage.show();//It just displays it to the user

//Window is called "Stage" and the content in the Window is called the "Scene"
}

@Override
public void handle(ActionEvent event) {/*Handle method is going to be called whenever
user clicks the button so whenever they click the button
that is called an event)e.g. MouseEvents,TouchEvents etc...*/
if (event.getSource() == button) {//This is uesd for identify the particular button(it
matches what particular button is click)
System.out.println("Ok! Button has click!");//If it mathces the button then verify and
print the message that button has click
//if we have another buttons then we use else if condition
}
}
}
Output:

Topic#03 Anonymous Inner Classes and Lamda Expressions


Alternatives ways of handling user events
package javafxtopics;

import javafx.application.Application;
import static javafx.application.Application.launch;
import javafx.event.ActionEvent;
import javafx.event.EventHandler;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.layout.StackPane;
import javafx.stage.Stage;

public class JavaFXTopics extends Application{

/*For EventHandler there are bunch of different types of events For e.g. there is a button
click and there are Mouse events whenever the
user moves their mouse around ,there is also touch events for touch devices whenever user
touch screen*/
//but of a simple button click we use <ActionEvent>
Button button;//Create button Here name of the Button is "button"

public static void main(String[] args) {


launch(args);//This is the method inside the Aplication class
}

@Override //start is Overriden method because we are inheritng it from the application class
public void start(Stage primaryStage) throws Exception {//All the code we write in here
that's the main JavaFX code
primaryStage.setTitle("Title of the window");//"Title of the window" is the Title name of
the Stage
button = new Button();//initialize the button
//we have a button and now no text on it

button.setText("Click me");//setting text on the button e.g.Click me


//THis class will handle the button events
//Anonymous inner class code
/* button.setOnAction(new EventHandler<ActionEvent>(){//instead of implementing
EventHandler we pass in Parameter this is called as anonymous inner class
@Override
public void handle(ActionEvent event){//whenever button click occured,we needed to
call this handle method and it was inside the EventHandler interface
System.out.println("I am an anonymous inner class!");
}
}
);*/

/*(reason of using this code is that it is the little bit cleaner and not having your code spread
out all over the place,whenever you use
anonymous inner classes you don't have to check the event source)
but if we use this anonymous code for multiple buttons it creates the problem that's why in
this condition we use lambda expressions*/

//instead of implementing anything or using an anonymous inner class use this Lamda
expression code

//Lambda Expression Code


// button.setOnAction(e-> System.out.println("Lambda Expression code!"));for one line code
button.setOnAction(e-> {
System.out.println("Lambda Expression code!");
System.out.println("Cograts!Button is working");
});//It is easier than writing any code or implementing the interface
//e represents the event and the paramter write to the left hand side and any code want to run
goes on right side

//To display anything on the screen need to make a layout(Layout is essantially just how you
want everything arranged on your screen)
StackPane layout = new StackPane();//StackPane is the really simple layout it's going to
position this button in the middle
layout.getChildren().add(button);//to organized everything in position call getChildren
and add the button by using add

Scene scene = new Scene(layout, 350, 250);//This first parameters scenes take is the
layout how do you want stuff arrranged in your scene and other two parameters are the size of
your scene 350 is the width and 250 is the height
primaryStage.setScene(scene);//setting the scene in the Window
primaryStage.show();//It just displays it to the user

//Window is called "Stage" and the content in the Window is called the "Scene"
}
}

Output:
Topic#04 Switching Scenes
package javafxtopics;

import javafx.application.Application;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.control.Label;
import javafx.scene.layout.StackPane;
import javafx.scene.layout.VBox;
import javafx.stage.Stage;

public class JavaFXTopics extends Application{


Stage window;//rename of the stage is window
Scene scene1,scene2;//name of the scenes
public static void main(String[] args) {
launch(args);//This is the method inside the Aplication class
}

@Override //start is Overriden method because we are inheritng it from the application class
public void start(Stage primaryStage) throws Exception {//Primary Stage is the entire
window
window=primaryStage;//refer entire window as window

//How to switch between scenes


Label label1=new Label("Welcome to the first scene");//add a label(A label is just a little
chunk of text)
Button button1=new Button("Go to scene2");//Create button1
button1.setOnAction(e -> window.setScene(scene2));//It changes the view or scene, it
goes from scene1 to scene2 when the button is clicked

//Layout 1 -> children are laid out in vertical column(For the first scene I 'll layout
everything in a vertical column)
VBox layout1=new VBox(20);/*VBox is a layout that stacks all the objects on the top
e.g.label1 in the column and 20 is the space amount
pixels so they are not like buttered up*/
layout1.getChildren().addAll(label1,button1);//we want to add label1 and button1
scene1=new Scene(layout1,300,200);//set layout for scene1

//Create button2 for scene2


Button button2=new Button("This scene sucks,Go back to scene1");
button2.setOnAction(e->window.setScene(scene1));//whenever you click button2,the
window changes to scene1

//Layout 2
StackPane layout2=new StackPane();//just to switch things up a little bit use StackPane,in
stackPane we dont need any parameters at all
layout2.getChildren().add(button2);//add button2 to this layout
scene2=new Scene(layout2,600,300);//setup our scene2 and it is 600 by 300 bigger

//name of th window
window.setTitle("Title here");
//What seen you want to display first you can put it
window.setScene(scene1);
//display to the user
window.show();

//Window is called "Stage" and the content in the Window is called the "Scene"
}
}

Output:
Topic#05 Creating Alert Boxes
How to add multiple windows in the same program.
package javafxtopics;
import javafx.application.Application;
import static javafx.application.Application.launch;
import javafx.event.ActionEvent;
import javafx.event.EventHandler;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.layout.StackPane;
import javafx.stage.Stage;

public class JavaFXTopics extends Application {


public static void main(String[] args) {
launch(args);//This is the method inside the Aplication class
}

@Override //start is Overriden method because we are inheritng it from the application class
public void start(Stage primaryStage) throws Exception {//All the code we write in here
that's the main JavaFX code
primaryStage.setTitle("Title of the window");//"Title of the window" is the Title name of
the Stage
Button button = new Button();//Here name of the Button is "button"
//we have a button and now no text on it

button.setText("Click me");//setting text on the button e.g.Click me


button.setOnAction(e-> AlertBox.display("Title Here", "Wow!this alert box is
amazing"));

//To display anything on the screen need to make a layout(Layout is essantially just how you
want everything arranged on your screen)
StackPane layout = new StackPane();//StackPane is the really simple layout it's going to
position this button in the middle
layout.getChildren().add(button);//to organized everything in position call getChildren
and add the button by using add

Scene scene = new Scene(layout,350,250);//This first parameters scenes take is the layout
how do you want stuff arrranged in your scene and other two parameters are the size of your
scene 350 is the width and 250 is the height
primaryStage.setScene(scene);//setting the scene in the Window
primaryStage.show();//It just displays it to the user

//Window is called "Stage" and the content in the Window is called the "Scene"
}
}

package javafxtopics;
import javafx.stage.*;
import javafx.scene.*;
import javafx.scene.layout.*;
import javafx.scene.control.*;
import javafx.geometry.*;
class AlertBox {

//it is the static method so we dont need to create any objects


public static void display(String title,String message){/*pass 2 strings 1 is the title of the
Output:

Topic#06 Communicating Between Windows


How multiple windows communicate with one another and how to create confirmation box.

package javafxtopics;
import javafx.application.Application;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.layout.StackPane;
import javafx.stage.Stage;

public class JavaFXTopics extends Application {


public static void main(String[] args) {
launch(args);//This is the method inside the Aplication class
}

@Override //start is Overriden method because we are inheritng it from the application class
public void start(Stage primaryStage) throws Exception {//All the code we write in here
that's the main JavaFX code
primaryStage.setTitle("Title of the window");//"Title of the window" is the Title name of
the Stage
Button button = new Button();//Here name of the Button is "button"
//we have a button and now no text on it

button.setText("Click me");//setting text on the button e.g.Click me


button.setOnAction(e-> {
boolean result=ConfirmBox.display("Title Here", "Are you sure you want to submit
the form");//asnwer store in the variable
System.out.println(result);//display the result on the command/console
});

//To display anything on the screen need to make a layout(Layout is essantially just how you
want everything arranged on your screen)
StackPane layout = new StackPane();//StackPane is the really simple layout it's going to
position this button in the middle
layout.getChildren().add(button);//to organized everything in position call getChildren
and add the button by using add

Scene scene = new Scene(layout,350,250);//This first parameters scenes take is the layout
how do you want stuff arrranged in your scene and other two parameters are the size of your
scene 350 is the width and 250 is the height
primaryStage.setScene(scene);//setting the scene in the Window
primaryStage.show();//It just displays it to the user

//Window is called "Stage" and the content in the Window is called the "Scene"
}
}

package javafxtopics;
import javafx.stage.*;
import javafx.scene.*;
import javafx.scene.layout.*;
import javafx.scene.control.*;
import javafx.geometry.*;
class ConfirmBox{
static boolean answer;//to store the answer that user press yes or no
//it is the static method so we dont need to create any objects
public static boolean display(String title,String message){//method will return boolean value
of answer
/*pass 2 strings 1 is the title of the new window and one is the message that we want
to display to the user */

Stage window=new Stage();//making a new window


window.initModality(Modality.APPLICATION_MODAL);//we are going to block input
events or user interaction with other windows
window.setTitle(title);//Title pf the window
window.setMinWidth(250);//min width of the window 250 pixels
// window.setMinHeight(200);
//Label label1=new Label(message);
Label label1=new Label();
label1.setText(message);

//create 2 buttons for yes and no


Button yesButton=new Button("Yes");
Button noButton=new Button("No");
yesButton.setOnAction(e->{
answer=true;//when the user clicks the yes button we set the answer to the yes
window.close();//after click the es button pop up window will close
});
noButton.setOnAction(e->{
answer=false;//when the user clicks the no button we set the answer to the yes
window.close();//after click the non button pop up window will close
});

//create layout
VBox layout=new VBox(10);
layout.getChildren().addAll(label1,yesButton,noButton);
layout.setAlignment(Pos.CENTER);//it sets the position of everything in center
Scene scene=new Scene(layout);
window.setScene(scene);
window.showAndWait();//before it returns to the previous window it needs to be closed

return answer;//when all the pop up program is done running ,actually need to return that
answer

//THis method not only creates pop up box but also whenever they close it,it gets the
answer and it returns it to console
/*if Little message you want to display ,use like AlertBox class however if you want to
get input from the user and pass it along into
main program use confirm box*/
}
}

Output:
Topic#07 Closing the Window Properly
package javafxtopics;

import javafx.application.Application;
import static javafx.application.Application.launch;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.layout.StackPane;
import javafx.stage.Stage;

public class JavaFXTopics extends Application {


Stage window;
Button button;
public static void main(String[] args) {
launch(args);//This is the method inside the Aplication class
}

@Override //start is Overriden method because we are inheritng it from the application class
public void start(Stage primaryStage) throws Exception {//All the code we write in here
that's the main JavaFX code
window=primaryStage;
window.setTitle("Title of the window");//"Title of the window" is the Title name of the
Stage
window.setOnCloseRequest(e-> {
e.consume();//the user wanted to request the close program by clicking on min bar but
we are going to consume that event and hold hold yes or no button manually
closeProgram();//this method gets called whenever the user requests to close the
window, not click on close Program button e.g.it click on min bar
});
button = new Button("Close Program");//Here name of the Button is "button" and text on
the button is "Close Program"
button.setOnAction(e->closeProgram());//this method gets called whenever the user cicks
on the button

//To display anything on the screen need to make a layout(Layout is essantially just how you
want everything arranged on your screen)
StackPane layout = new StackPane();//StackPane is the really simple layout it's going to
position this button in the middle
layout.getChildren().add(button);//to organized everything in position call getChildren
and add the button by using add

Scene scene = new Scene(layout,350,250);//This first parameters scenes take is the layout
how do you want stuff arrranged in your scene and other two parameters are the size of your
scene 350 is the width and 250 is the height
window.setScene(scene);//setting the scene in the Window
window.show();//It just displays it to the user

//Window is called "Stage" and the content in the Window is called the "Scene"
}

private void closeProgram(){


//System.out.println("File is saved!");//the file will be saved whenever this method is
called
//window.close();
Boolean answer =ConfirmBox.display("Title","Are you sure you want to exit?");
if(answer){//if the user click on yes button window will be close
window.close();
}
}
}

package javafxtopics;
import javafx.stage.*;
import javafx.scene.*;
import javafx.scene.layout.*;
import javafx.scene.control.*;
import javafx.geometry.*;
class ConfirmBox{
static boolean answer;//to store the answer that user press yes or no
//it is the static method so we dont need to create any objects
public static boolean display(String title,String message){//method will return boolean value
of answer
/*pass 2 strings 1 is the title of the new window and one is the message that we want
to display to the user */

Stage window=new Stage();//making a new window


window.initModality(Modality.APPLICATION_MODAL);//we are going to block input
events or user interaction with other windows
window.setTitle(title);//Title pf the window
window.setMinWidth(250);//min width of the window 250 pixels
// window.setMinHeight(200);
//Label label1=new Label(message);
Label label1=new Label();
label1.setText(message);

//create 2 buttons for yes and no


Button yesButton=new Button("Yes");
Button noButton=new Button("No");
yesButton.setOnAction(e->{
answer=true;//when the user clicks the yes button we set the answer to the yes
window.close();//after click the es button pop up program will close
});

noButton.setOnAction(e->{
answer=false;//when the user clicks the no button we set the answer to the yes
window.close();//after click the non button pop up window will close
});

//create layout
VBox layout=new VBox(10);
layout.getChildren().addAll(label1,yesButton,noButton);
layout.setAlignment(Pos.CENTER);//it sets the position of everything in center
Scene scene=new Scene(layout);
window.setScene(scene);
window.showAndWait();//before it returns to the previous window it needs to be closed

return answer;//when all the pop up program is done running ,actually need to return that
answer

//THis method not only creates pop up box but also whenever they close it,it gets the
answer and it returns it to console
/*if Little message you want to display ,use like AlertBox class however if you want to
get input from the user and pass it along into
main program use confirm box*/
}
}
Output:
If the user clicks on yes button program will closed

If the user clicks on no button program will not be closed

If the user clicks on min bar then it consume the event and hold yes or no manually by
using e.consume
If we not use e.consume then our program will close by click on min bar.
Topic#08 Embedding Layouts

How to use multiple layouts by embedding VBox, HBox, and Sample Border Pane.
package javafxtopics;

import javafx.application.Application;
import javafx.scene.Scene;
import javafx.scene.layout.HBox;
import javafx.scene.control.Button;
import javafx.scene.layout.BorderPane;
import javafx.scene.layout.StackPane;
import javafx.scene.layout.VBox;
import javafx.stage.Stage;

public class JavaFXTopics extends Application {


Stage window;
public static void main(String[] args) {
launch(args);//This is the method inside the Aplication class
}
@Override //start is Overriden method because we are inheritng it from the application class
public void start(Stage primaryStage) throws Exception {//All the code we write in here
that's the main JavaFX code
window=primaryStage;
window.setTitle("Title of the window");//"Title of the window" is the Title name of the
Stage
HBox topMenu=new HBox();//HBox is used to create top Menu Bar Button Horizontally
Button buttonA=new Button("File");//first button
Button buttonB=new Button("Edit");//second button
Button buttonC=new Button("View");//third button
//create layout of Box
topMenu.getChildren().addAll(buttonA,buttonB,buttonC);//Add all the children to the
layout

VBox leftMenu=new VBox();//VBox is used to create left Menu Bar Button Vertically
Button buttonD=new Button("D");//first button
Button buttonE=new Button("E");//second button
Button buttonF=new Button("F");//third button
//create layout of Box
leftMenu.getChildren().addAll(buttonD,buttonE,buttonF);//Add all the children to the
layout
/*So now we havw 2 layouts one is horizontal where we have 3 buttons left and right and
second layout which is vertical which we call
left menu where we have 3 buttons* stacked on the top of each other*/

//Create Border Pane layout which is completly different layout


BorderPane borderPane=new BorderPane();
//call 2 methods
borderPane.setTop(topMenu);/*the first method is the setTop and inside we can pass in
an entire layout of HBox so for the "top" of
Borderpane we put the "topMenu" in there, we are taking 3 buttons we are sticking in the
"top"*/
borderPane.setLeft(leftMenu);/*and in 2nd method we take our vertical left menu and
stick it for the "left" in BorderPane.*/

Scene scene = new Scene(borderPane,350,250);//This first parameters scenes take is the


layout how do you want stuff arrranged in your scene and other two parameters are the size of
your scene 350 is the width and 250 is the height
window.setScene(scene);//setting the scene in the Window
window.show();//It just displays it to the user

//Window is called "Stage" and the content in the Window is called the "Scene"

//If you want to start making more complex layouts then you can embeded or embeding
layouts within another
}
}

Output:

Topic#09 GridPane
Grid pane is a way that you can arrange items in grid.
package javafxtopics;

import javafx.application.Application;
import javafx.geometry.Insets;
import javafx.scene.Scene;
import javafx.scene.control.*;
import javafx.scene.layout.GridPane;
import javafx.stage.Stage;

public class JavaFXTopics extends Application {


Stage window;
public static void main(String[] args) {
launch(args);//This is the method inside the Aplication class
}
@Override //start is Overriden method because we are inheritng it from the application class
public void start(Stage primaryStage) throws Exception {//All the code we write in here
that's the main JavaFX code
window=primaryStage;
window.setTitle("Title of the window");//"Title of the window" is the Title name of the
Stage
//made a grid layout
GridPane grid=new GridPane();
//padding between entire layout in the border of the window of ten pixels
grid.setPadding(new Insets(10,10,10,10));/*The first thing of the GridPane layout is to set
Padding and this takes Insets object as
parameter and 10 is the amount of padding that you want to add to each edge s0 it puts
the10 pixel padding around your entire
layout in the window*/
//spacing vertically is 8
grid.setVgap(8);//set vertical spacing
//spacing horizontally is 10
grid.setHgap(10);//set horizontal spacing each gap

//adding some items


//name label
//we made an item that we want to add now ,where do we want to add it what column
what row
Label nameLabel=new Label("Username : ");
/*so we call a method called set constraints so this takes 3 parameters 1st one is the child(
what item do you want to the grid that is the label) and other 2 is what cloumn and
what row,in other words the position where you want to add it*/
GridPane.setConstraints(nameLabel,0,0);//it add the item in 0 row and 0 column in other
words this label is appear in the top left of the grid

//Name input, which is the area that they type their name so we take the TextField
TextField nameInput=new TextField("Bucky");// we have default text in there so it it
gives the default text but We can also create it blank
//after done to create the item ,add it to the grid setconstraints
GridPane.setConstraints(nameInput,1,0);//it add the item which is nameInput in 0 row
and 1 column

//Password Label
Label passLabel=new Label("Password : ");
GridPane.setConstraints(passLabel,0,1);//it add the item in 1 row and 0 column
//pass input, which is the area that they type their Password so we take the TextField
TextField passInput=new TextField();
passInput.setPromptText("password");/*when the user click this "passwrod" this little
grey indicator dissapear,so this the difference
between above default text which is not dissapear by clicking and setPromptText method
which disappear the grey indicator by clicking*/
GridPane.setConstraints(passInput,1,1);//it add the item in 1 row and 1 column

//create login button


Button loginButton=new Button("Login In");
GridPane.setConstraints(loginButton,1,2);//it add the item in 2 row and 1 column

//add everything to the grid


grid.getChildren().addAll(nameLabel,nameInput,passLabel,passInput,loginButton);
//grid is 350 by 200 big
Scene scene = new Scene(grid,350,200);//This first parameters scenes take is the
layout ,what stuff you want to arrranged in your scene and other two parameters are the size of
your scene 350 is the width and 200 is the height
window.setScene(scene);//setting the scene in the Window
window.show();//It just displays it to the user

//Window is called "Stage" and the content in the Window is called the "Scene"

}
}

Output:

Horizontal gap

Vertical gap

Topic#10 Extract And Validate Input


How to get data from form fields and how to validate them.
package javafxtopics;

import javafx.application.Application;
import javafx.geometry.Insets;
import javafx.scene.Scene;
import javafx.scene.control.*;//For Button and TextFiled etc
import javafx.scene.layout.VBox;
import javafx.stage.Stage;

public class JavaFXTopics extends Application {


Stage window;
public static void main(String[] args) {
launch(args);//This is the method inside the Aplication class
}

@Override //start is Overriden method because we are inheritng it from the application class
public void start(Stage primaryStage) throws Exception {//All the code we write in here
that's the main JavaFX code
window=primaryStage;
window.setTitle("Title of the window");//"Title of the window" is the Title name of the
Stage

//Name input, which is the area that they type their name so we take the TextField
TextField nameInput=new TextField();//We create it blank here but we can write default
text in there so it it gives the default text
Button button=new Button("Click me");

//whenever we click this button just extract that and print it out in the terminal
//Validate the value that is Integer or not
button.setOnAction(e-> isInt(nameInput,nameInput.getText()));/*whenever you want to
extract the information from a form element
just put the name of the element i.e."nameInput" , with text field*/
VBox layout=new VBox(10);/*VBox is used to create top menu bar vertically e.g.label1
in the column and 20 is the space amount
pixels so they are not like buttered up*/

layout.setPadding(new Insets(20,20,20,20));/*set Padding and this takes Insets object as


parameter and 20 is the amount of padding that you want to add to each edge s0 it puts
the 20 pixel padding around your entire
layout in the window*/

layout.getChildren().addAll(nameInput,button);//add nameInput and button in the layout


Scene scene = new Scene(layout,350,200);//This first parameters scenes take is the
layout ,what stuff you want to arrranged in your scene and other two parameters are the size of
your scene 300 is the width and 200 is the height
window.setScene(scene);//setting the scene in the Window
window.show();//It just displays it to the user

//Window is called "Stage" and the content in the Window is called the "Scene"

//create validtation method that the value that user enter is int or not
private boolean isInt(TextField input,String message){
try{
int age=Integer.parseInt(input.getText());//whatever they typed in its trying to convert
ii in to integer
System.out.println("User is "+age);
return true;

}
catch(NumberFormatException e){//if accidentally user type their name it cannot be
converted into Integer that's why it throws error
System.out.println("Error : "+message+" is not a number.");
return false;

}
}
}

Output:
Topic#11 CheckBox
How to work with check box.
package javafxtopics;
import javafx.application.Application;
import javafx.geometry.Insets;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.control.CheckBox;
import javafx.scene.layout.StackPane;
import javafx.scene.layout.VBox;
import javafx.stage.Stage;

public class JavaFXTopics extends Application {


Stage window;
Scene scene;
Button button;
public static void main(String[] args) {
launch(args);//This is the method inside the Aplication class
}

@Override //start is Overriden method because we are inheritng it from the application class
public void start(Stage primaryStage) throws Exception {//All the code we write in here
that's the main JavaFX code
window=primaryStage;
window.setTitle("Bucky's Meat subs");//"Title of the window" is the Title name of the
Stage

//make Checkboxes
CheckBox box1=new CheckBox("Burger");//"Duaa and Sadaf" it is the text that appears
to the right of the checkbox
CheckBox box2=new CheckBox("Fries");
box2.setSelected(true);//If you want to make that type of checkbox which is already
checked by default

button = new Button("Order Now");//Here name of the Button is "button" and setting text
on the button e.g.Order Now
button.setOnAction(e-> handleOptions(box1,box2));
//We are using Vbox so checkboxes are appear to the right of each other
VBox layout=new VBox(10);/*VBox is used to create top menu bar vertically e.g.label1
in the column and 20 is the space amount
pixels so they are not like buttered up*/
layout.setPadding(new Insets(20,20,20,20));/*set Padding and this takes Insets object as
parameter and 20 is the amount of padding that you want to add to each edge s0 it puts
the 20 pixel padding around your entire
layout in the window*/
layout.getChildren().addAll(box1,box2,button);//add nameInput and button in the layout
Scene scene = new Scene(layout,350,200);//This first parameters scenes take is the
layout ,what stuff you want to arrranged in your scene and other two parameters are the size of
your scene 350 is the width and 200 is the height
window.setScene(scene);//setting the scene in the Window
window.show();//It just displays it to the user

//Window is called "Stage" and the content in the Window is called the "Scene"
}

//this method is used to whatever options they selected that print out on the screen
//Handle checkbox options
private void handleOptions(CheckBox box1,CheckBox box2){
String message="User's Order : \n";
//check if the checkbox is selected or not,call a method isSeleceted
if(box1.isSelected()){//it is return true if the box1 is checked and return false if it is not
checked
message+="Burger\n";
}
if(box2.isSelected()){//it is return true if the box2 is checked and return false if it is not
checked
message+="Fries";
}
System.out.println(message);
}
}

Output:
Topic#12 Choice Box(Drop Down Menu)
Functionality with button
A drop down list is called a Choice Box.
In this code we learn How you use drop-down lists how you add items to them , how you set
default values and how you extract the user’s choice or selected items.

package javafxtopics;
import javafx.application.Application;
import javafx.geometry.Insets;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.control.ChoiceBox;
import javafx.scene.layout.VBox;
import javafx.stage.Stage;

public class JavaFXTopics extends Application {


Stage window;
Scene scene;
Button button;
public static void main(String[] args) {
launch(args);//This is the method inside the Aplication class
}

@Override //start is Overriden method because we are inheritng it from the application class
public void start(Stage primaryStage) throws Exception {//All the code we write in here that's
the main JavaFX code
window=primaryStage;
window.setTitle("Choice Box Demo");//"Title of the window" is the Title name of the Stage

button = new Button("Click me");//Here name of the Button is "button" and setting text on the
button e.g.Click me
//create ChoiceBox,initially it is a blank drop down list
ChoiceBox<String> choiceBox=new ChoiceBox<>();//you can have a bunch of different
types of data in the choice box BUT you cannot use the mix types of data in the chioce box
//getItems return the ObservableList object which you can add items to
choiceBox.getItems().add("Apples");
choiceBox.getItems().add("Bananas");
choiceBox.getItems().addAll("Pear","Ham","MeatBalls");

//you can set a value of choiceBox to get a reference to your drop down but we need that type
of value that is already exists
choiceBox.setValue("Apples");

//implement some kind of method to extract the value from it


button.setOnAction(e-> getChoice(choiceBox));

VBox layout=new VBox(10);/*VBox is used to create top menu bar vertically e.g.label1 in
the column and 20 is the space amount
pixels so they are not like buttered up*/
layout.setPadding(new Insets(20,20,20,20));/*set Padding and this takes Insets object as
parameter and 20 is the amount of padding that you want to add to each edge s0 it puts the 20
pixel padding around your entire
layout in the window*/
layout.getChildren().addAll(choiceBox,button);//add nameInput and button in the layout
Scene scene = new Scene(layout,350,200);//This first parameters scenes take is the
layout ,what stuff you want to arrranged in your scene and other two parameters are the size of
your scene 350 is the width and 200 is the height
window.setScene(scene);//setting the scene in the Window
window.show();//It just displays it to the user

//Window is called "Stage" and the content in the Window is called the "Scene"
}
//To get the value of the selected items
private void getChoice(ChoiceBox<String> choiceBox){/*wehnever you're creaating your drop
down list you can copy "ChoiceBox<String> choiceBox" and use it in a parameter
whenever you are validating the data*/
String food=choiceBox.getValue();//Its get the currently selected value whatever option the
user selected
//print the selected option on the screen
System.out.println(food);//if user not selected any item it print the by default value e.g. we set
Apple

}
}

Output:
When the user does not select any item. It When user select any one item.
Print the by default value which is “apples”.

When user select multiples item.


Topic#13 Listening for Selection Changes(Means it does not need button
to print on the console, it is selected and print on the console whenever you choose any one
from drop down menu) :
How you listen for changes on the drop down menu.
package javafxtopics;
import javafx.application.Application;
import javafx.geometry.Insets;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.control.ChoiceBox;
import javafx.scene.layout.VBox;
import javafx.stage.Stage;

public class JavaFXTopics extends Application {


Stage window;
Scene scene;
Button button;
public static void main(String[] args) {
launch(args);//This is the method inside the Aplication class
}

@Override //start is Overriden method because we are inheritng it from the application class
public void start(Stage primaryStage) throws Exception {//All the code we write in here
that's the main JavaFX code
window=primaryStage;
window.setTitle("Choice Box Demo");//"Title of the window" is the Title name of the
Stage

//create ChoiceBox,initially it is a blank drop down list


ChoiceBox<String> choiceBox=new ChoiceBox<>();//you can have a bunch of different
types of data in the choice box BUT you cannot use the mix types of data in the chioce box
//getItems return the ObservableList object which you can add items to
choiceBox.getItems().add("Apples");
choiceBox.getItems().add("Bananas");
choiceBox.getItems().addAll("Pear","Ham","MeatBalls");

//you can set a value of choiceBox to get a reference to your drop down but we need that
type of value that is already exists
choiceBox.setValue("Apples");

//so in order to simulate emitting an event whenever the user clicks or chooses one of
these items

//Listen for selection changes


choiceBox.getSelectionModel().selectedItemProperty().addListener((v,oldValue,newValue) -
>System.out.println(newValue));//different types of lists have different types of selection
models whenever you are using a drop down list you can only select one item
//selectedItemProperty() this is the item that user selected from that list
/*So with menu items, click their selected item so "addListener" event occurs and three
parameters emit and we use in this
Lambda Expression so the parameter go to the left hand side and the body of the function
or the code you want to execute goes on the
right hand side."v" stands for observable it is the property of the item itself,2nd is the old
value for e.g.if you had apple selected
by default and now you select the ham so ham is the new value which prints on the
console and apples is the old value.So whenever they
select the new item they print the new value on screen because we want to print the new
value here but we can also print the old value
old value is the item that was selected before,System.out.println(oldValue)*/

VBox layout=new VBox(10);/*VBox is used to create top menu bar vertically e.g.label1
in the column and 20 is the space amount
pixels so they are not like buttered up*/
layout.setPadding(new Insets(20,20,20,20));/*set Padding and this takes Insets object as
parameter and 20 is the amount of padding that you want to add to each edge s0 it puts
the 20 pixel padding around your entire
layout in the window*/
layout.getChildren().addAll(choiceBox);//add nameInput and button in the layout
Scene scene = new Scene(layout,350,200);//This first parameters scenes take is the
layout ,what stuff you want to arrranged in your scene and other two parameters are the size of
your scene 350 is the width and 200 is the height
window.setScene(scene);//setting the scene in the Window
window.show();//It just displays it to the user

//Window is called "Stage" and the content in the Window is called the "Scene"
}
}
Output:

Topic#14 Combo Box(Functionality with Button)


Combo Box is essentially a really awesome drop down menu. These combo box can actually
generate actions so we don’t have to stick listeners on them. With a regular drop down menu
click button drop down got some options but with a combo box you can either select one of these
options or type one in yourself.
package javafxtopics;
import javafx.application.Application;
import javafx.geometry.Insets;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.control.ComboBox;
import javafx.scene.layout.VBox;
import javafx.stage.Stage;

public class JavaFXTopics extends Application {


Stage window;
Scene scene;
Button button;
ComboBox <String> comboBox;
public static void main(String[] args) {
launch(args);//This is the method inside the Aplication class
}
@Override //start is Overriden method because we are inheritng it from the application class
public void start(Stage primaryStage) throws Exception {//All the code we write in here
that's the main JavaFX code
window=primaryStage;
window.setTitle("Combo Box Demo");//"Title of the window" is the Title name of the
Stage

button = new Button("Submit");//Here name of the Button is "button" and setting text on
the button e.g.Submit
comboBox=new ComboBox<>();
//add items to the comboBox
comboBox.getItems().addAll(// //getItems return the ObservableList object which
you can add items to
"Red",
"Green",
"Blue"
);
//add prompt text,prompt text is the default text
comboBox.setPromptText("What is your favourite Colour?");
button.setOnAction(e-> printMovie());

VBox layout=new VBox(10);/*VBox is used to create top menu bar vertically e.g.label1
in the column and 20 is the space amount
pixels so they are not like buttered up*/
layout.setPadding(new Insets(20,20,20,20));/*set Padding and this takes Insets object as
parameter and 20 is the amount of padding that you want to add to each edge s0 it puts
the 20 pixel padding around your entire
layout in the window*/
layout.getChildren().addAll(comboBox,button);//add comboBox and button in the layout
Scene scene = new Scene(layout,350,200);//This first parameters scenes take is the
layout ,what stuff you want to arrranged in your scene and other two parameters are the size of
your scene 350 is the width and 200 is the height
window.setScene(scene);//setting the scene in the Window
window.show();//It just displays it to the user

//Window is called "Stage" and the content in the Window is called the "Scene"
}
//printout a Movie name
private void printMovie(){
System.out.println(comboBox.getValue());//which item the user will select it extract that
value from it
}

}
Output:
Topic#14 Combo Box(Functionality without Button)
package javafxtopics;
import javafx.application.Application;
import javafx.geometry.Insets;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.control.ComboBox;
import javafx.scene.layout.VBox;
import javafx.stage.Stage;

public class JavaFXTopics extends Application {


Stage window;
Scene scene;
ComboBox <String> comboBox;
public static void main(String[] args) {
launch(args);//This is the method inside the Aplication class
}

@Override //start is Overriden method because we are inheritng it from the application class
public void start(Stage primaryStage) throws Exception {//All the code we write in here
that's the main JavaFX code
window=primaryStage;
window.setTitle("Combo Box Demo");//"Title of the window" is the Title name of the
Stage
//create comboBox
comboBox=new ComboBox<>();
//add items to the comboBox
comboBox.getItems().addAll(// //getItems return the ObservableList object which
you can add items to
"Red",
"Green",
"Blue"
);
//add prompt text,prompt text is the default text
comboBox.setPromptText("What is your favourite Colour?");
/*whenever you do this, the promptText get overriden and not only you can select the
given items but
you can edit your own custom item*/
//comboBox.setEditable(true);
//Combo Box generate their own actions
comboBox.setOnAction(e-> System.out.println("User selected :
"+comboBox.getValue()));

VBox layout=new VBox(10);/*VBox is used to create top menu bar vertically e.g.label1
in the column and 20 is the space amount
pixels so they are not like buttered up*/
layout.setPadding(new Insets(20,20,20,20));/*set Padding and this takes Insets object as
parameter and 20 is the amount of padding that you want to add to each edge s0 it puts
the 20 pixel padding around your entire
layout in the window*/
layout.getChildren().addAll(comboBox);//add comboBox and button in the layout
Scene scene = new Scene(layout,350,200);//This first parameters scenes take is the
layout ,what stuff you want to arrranged in your scene and other two parameters are the size of
your scene 350 is the width and 200 is the height
window.setScene(scene);//setting the scene in the Window
window.show();//It just displays it to the user

//Window is called "Stage" and the content in the Window is called the "Scene"
}
}
Output:
1)you can edit your own custom item. 2) you can select the given items

Topic#15 ListView
List View is a little bit different than other lists because first of all it’s not a drop down and
another reason that is different is unlike a drop down list where you can select only one item
from the list whenever you have a list view you can select multiple items. It is similar to a combo
box.
package javafxtopics;
import javafx.application.Application;
import javafx.collections.ObservableList;
import javafx.geometry.Insets;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.control.ListView;
import javafx.scene.control.SelectionMode;
import javafx.scene.layout.VBox;
import javafx.stage.Stage;
public class JavaFXTopics extends Application {
Stage window;
Scene scene;
Button button;
ListView <String> listView;
public static void main(String[] args) {
launch(args);//This is the method inside the Aplication class
}

@Override //start is Overriden method because we are inheritng it from the application class
public void start(Stage primaryStage) throws Exception {//All the code we write in here
that's the main JavaFX code
window=primaryStage;
window.setTitle("Combo Box Demo");//"Title of the window" is the Title name of the
Stage
VBox layout=new VBox(10);/*VBox is used to create top menu bar vertically e.g.label1
in the column and 20 is the space amount
pixels so they are not like buttered up*/
button=new Button("Submit");

listView=new ListView<>();
//add items to the listView
listView.getItems().addAll("Mechanical Engineering","Software Engineering","Civil
Engineering","Electrical Engineering");//no matter you are adding the items for the first time
or it already has items in it
//set the selection Model
//if you want to select multiple ones use Selection mode multiple and the first thing is to
select the getSelectionModel() before you can edit it
listView.getSelectionModel().setSelectionMode(SelectionMode.MULTIPLE);

button.setOnAction(e->buttonClicked());

layout.setPadding(new Insets(20,20,20,20));/*set Padding and this takes Insets object as


parameter and 20 is the amount of padding that you want to add to each edge s0 it puts
the 20 pixel padding around your entire
layout in the window*/
layout.getChildren().addAll(listView,button);//add comboBox and button in the layout
Scene scene = new Scene(layout,350,200);//This first parameters scenes take is the
layout ,what stuff you want to arrranged in your scene and other two parameters are the size of
your scene 350 is the width and 200 is the height
window.setScene(scene);//setting the scene in the Window
window.show();//It just displays it to the user

//Window is called "Stage" and the content in the Window is called the "Scene"
}
//print out selected items
//all the lists that work with in javaFX are of type Observble lists
private void buttonClicked(){
String message="";//String message will be the message that is print out in the terminal
ObservableList <String> fields;/*all of the lists that you work with in JavaFX are of types
Observable list so throught this we can grab
whatever items the user selected store them inside in observable list object*/
fields=listView.getSelectionModel().getSelectedItems();//in order to get the item which
user selected we use getSelectionModel and getSelectedItems method
//loop through each field that the user selected
for(String f:fields){//we treat each fields one by one because we use list
message+=f+"\n";//one by one field is store inside the variable or the String message
}
//print out message in the terminal
System.out.println(message);

Output:
If user wants to select multiples then press shift and
select the items one by one.
Topic#16 Tree View
A tree view is special type of list JavaFX because you can take your list items and arrange them
in a hierarchy. So whenever we create a main tree we always need a root so every tree has one
singe root. So if we have a root we can start adding branches to it and your branches can have
other branches or you can have a single item on branch. And whenever you have an item that
does not have any children called a leaf.
package javafxtopics;

import javafx.application.Application;
import javafx.collections.ObservableList;
import javafx.geometry.Insets;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.control.ListView;
import javafx.scene.control.SelectionMode;
import javafx.scene.control.TreeItem;
import javafx.scene.control.TreeView;
import javafx.scene.layout.StackPane;
import javafx.scene.layout.VBox;
import javafx.stage.Stage;

public class JavaFXTopics extends Application {

Stage window;
//create Tree View
TreeView<String> tree;

public static void main(String[] args) {


launch(args);//This is the method inside the Aplication class
}

@Override //start is Overriden method because we are inheritng it from the application class
public void start(Stage primaryStage) throws Exception {//All the code we write in here
that's the main JavaFX code
window = primaryStage;
window.setTitle("Tree View");//"Title of the window" is the Title name of the Stage
//add the items including the roots in any branch
TreeItem<String> root, berry, Apple;//strawberry and apple are branches we sticking
these on the root

//setup the root


root = new TreeItem<>("Fruits");//root is the container for all our branches
root.setExpanded(true);//setExpanded is the property whenever a program first starts we
are set everything to expanded bydefault
//Strawberry branch
//whenever you are building the branch on tree you make an item and then you select
what is the parent of it to be
//whenver we have 2 items in the same location those are called either siblings
berry = makeBranch("berry", root);//this takes 2 parameters the first is what you want the
name of the item and the second one is what is the parent of the item
//add bunch of items to branch "berry"
makeBranch("red berry", berry);
makeBranch("blue berry", berry);
makeBranch("purple berry", berry);
makeBranch("black berry", berry);

//apple branch
Apple = makeBranch("Apple", root);//this takes 2 parameters the first is what you want
the name of the item and the second one is what is the parent of the item
//add bunch of items to branch "apple"
makeBranch("red Apple", Apple);
makeBranch("green Apple", Apple);

//create tree
tree = new TreeView<>(root);//tree need a main trunk so we pass the parameter "root
tree.setShowRoot(true);//if we set tree.setShowRoot(false);it does n't show root before
see branches e.g.the berry and apple
//in order to print the item on console whenever the user clicks ,we use listener in the tree
//Lambda is a short hand way of making a function,in this parameters go to the left hand
side and body go to the right side
tree.getSelectionModel().selectedItemProperty().addListener((v,oldValue,newValue)->{
if(newValue!=null){
System.out.println(newValue.getValue());//value of the item is newvalue.getValue
}
});

StackPane layout = new StackPane();


layout.getChildren().add(tree);
Scene scene = new Scene(layout, 350, 300);//This first parameters scenes take is the
layout ,what stuff you want to arrranged in your scene and other two parameters are the size of
your scene 350 is the width and 300 is the height
window.setScene(scene);//setting the scene in the Window
window.show();//It just displays it to the user

//Window is called "Stage" and the content in the Window is called the "Scene"
}

//create branches
public TreeItem<String> makeBranch(String title,TreeItem<String> parent) {//our branch is
tree items,everything on out tree is an item so we are make one of these branches and return
that item
TreeItem<String> item=new TreeItem<String>(title);/*so it takes the first value
whatever we pass in e.g red apple,green apple,black berry
it makes these the new list item*/
item.setExpanded(true);//because we use this method for each branch for e.g.berry have
subitems so bydefault all of these will expanded
parent.getChildren().add(item);//in each of these items we want to stick on its main
parent branch
//Our branch has built at that point
return item;//item return the branch
}

}
Output:

Topic#17 Table View(Simple Table View)


How to make a table using JavaFX. Table is like a spreadsheet where you have your data and is
arranged in rows and columns.
package javafxtopics;

import javafx.application.Application;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.geometry.Insets;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.control.TableColumn;
import javafx.scene.control.TableView;
import javafx.scene.control.TextField;
import javafx.scene.control.cell.PropertyValueFactory;
import javafx.scene.layout.VBox;
import javafx.stage.Stage;

public class JavaFXTopics extends Application {

Stage window;
//make the table and in this mention what type of data you want to store
TableView<Product> table;//whenever you create a table you need to have atleast one
column otherwise you get a bunch of errors so in this table we will have 3 columns
name,price and for the quantity
public static void main(String[] args) {
launch(args);//This is the method inside the Aplication class
}

@Override //start is Overriden method because we are inheritng it from the application class
public void start(Stage primaryStage) throws Exception {//All the code we write in here
that's the main JavaFX code
window = primaryStage;
window.setTitle("Table View");//"Title of the window" is the Title name of the Stage

//setup the columns


//name column
TableColumn<Product,String> nameColumn=new TableColumn<>("Name");/*It takes 2
parameters the first is the type of data in your table and
second is what type of data is going to be in this column and "Name" is the name of the
column*/
nameColumn.setMinWidth(200);//min width of this column is 200 if you don't do this
look like all the columns bunch together
nameColumn.setCellValueFactory(new PropertyValueFactory<>("name"));//for the name
column use the name property of our object and get all the values of "name"
//(new PropertyValueFactory<>("name")),write exact the name of the property in bracket
//price column
TableColumn<Product,Double> priceColumn=new TableColumn<>("Price");
priceColumn.setMinWidth(100);
priceColumn.setCellValueFactory(new PropertyValueFactory<>("price"));
//quantity column
TableColumn<Product,Integer> quantityColumn=new TableColumn<>("Quantity");
quantityColumn.setMinWidth(100);
quantityColumn.setCellValueFactory(new PropertyValueFactory<>("quantity"));

//stick the columns in the table


table =new TableView<>();
//loading all of our data what data do you want to use for your table
table.setItems(getProduct());////getProduct()is load all of our data
//add the columns to the table
table.getColumns().addAll(nameColumn,priceColumn,quantityColumn);

VBox vBox = new VBox();


//add table to a layout
vBox.getChildren().addAll(table);
Scene scene = new Scene(vBox);/*VBox is a layout that stacks all the objects on the top
e.g.label1 in the column and 20 is the space
amount pixels so they are not like buttered up*/

window.setScene(scene);//setting the scene in the Window


window.show();//It just displays it to the user

//Window is called "Stage" and the content in the Window is called the "Scene"
}/*We make a new class because it is a good idea to take your data and stick inside a new
class ,sor we are making a little spread sheet app and
in this class i have a store and we are selling the products*/
//This method is get all of the products and return the list
public ObservableList<Product> getProduct(){//data type is the name of your class so we
store product object in here
ObservableList<Product>
products=FXCollections.observableArrayList();//observableArrayList() is the type of
observable list to store java objects inside
//add a bunch of products to it
products.add(new Product("laptop",1000.0,20));
products.add(new Product("computer",2.49,100));
products.add(new Product("RAM",2000.0,208));
products.add(new Product("SSD",1.49,5));
return products;//return abservable list of product object

}
//so in the table we can sort out all the items and grab one of these you can drag into a new
location

}
Product Class

package javafxtopics;
public class Product {
//properties that are associated with our products e.d name ,price,quantity etc
private String name;
private double price;//price type will be doube incase if we will need decimal places
private int quantity;//quantatiy how many items we have we can also say amount,inventory
inplace of quantity
//make 2 overload constructor
/*The 1st constructor is to take all the properties and give them a default value so whenever
we create a product its have a blank value which
is default value.*/
public Product(){
this.name="";
this.price=0;
this.quantity=0;
}
//The 1st constructor take 3 parameters name price and quantity
public Product(String name,double price,int quantity){
//pass the value whatever value we will pass in the constructor
this.name=name;
this.price=price;
this.quantity=quantity;
}
//insert all the getters and setters
public void setName(String name){
this.name=name;
}
public String getName(){
return name;
}
public void setPrice(double price){
this.price=price;
}
public double getPrice(){
return price;
}
public void setQuantity(int quantity){
this.quantity=quantity;
}
public int getQuantity(){
return quantity;
}
/*we cannot change the set and get methods that don't follow convention e.g. getTheName
because it'll break JavaFx.Whenever we make tables
need to follow this naming convention*/
}
//This product class is done now we can store a bunch of products in JavaFXTopics class
Output: We can also perform sorting.
Topic#19 Adding and Deleting Table View Rows(Editable Tables)
package javafxtopics;

import javafx.application.Application;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.geometry.Insets;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.control.TableColumn;
import javafx.scene.control.TableView;
import javafx.scene.control.TextField;
import javafx.scene.control.cell.PropertyValueFactory;
import javafx.scene.layout.HBox;
import javafx.scene.layout.VBox;
import javafx.stage.Stage;

public class JavaFXTopics extends Application {

Stage window;
//make the table and in this mention what type of data you want to store
TableView<Product> table;//whenever you create a table you need to have atleast one
column otherwise you get a bunch of errors so in this table we will have 3 columns
name,price and for the quantity
//input new row
TextField nameInput,priceInput,quantityInput;
public static void main(String[] args) {
launch(args);//This is the method inside the Aplication class
}

@Override //start is Overriden method because we are inheritng it from the application class
public void start(Stage primaryStage) throws Exception {//All the code we write in here
that's the main JavaFX code
window = primaryStage;
window.setTitle("Tree View");//"Title of the window" is the Title name of the Stage

//setup the columns


//name column
TableColumn<Product,String> nameColumn=new TableColumn<>("Name");/*It takes 2
parameters the first is the type of data in your table and
second is what type of data is going to be in this column and "Name" is the name of the
column*/
nameColumn.setMinWidth(200);//min width of this column is 200 if you don't do this
look like all the columns bunch together
nameColumn.setCellValueFactory(new PropertyValueFactory<>("name"));//for the name
column use the name property of our object and get all the values of "name"
//(new PropertyValueFactory<>("name")),write exact the name of the property in bracket
//price column
TableColumn<Product,Double> priceColumn=new TableColumn<>("Price");
priceColumn.setMinWidth(100);
priceColumn.setCellValueFactory(new PropertyValueFactory<>("price"));
//quantity column
TableColumn<Product,Integer> quantityColumn=new TableColumn<>("Quantity");
quantityColumn.setMinWidth(100);
quantityColumn.setCellValueFactory(new PropertyValueFactory<>("quantity"));
//we have 3 inputs whatever item they want to add their store
//name input
nameInput=new TextField();
nameInput.setPromptText("Name");//it provides a light grey indicator to a user what
actually user supposed to be typing in there
//price input
priceInput=new TextField();
priceInput.setPromptText("Price");
//quantity input
quantityInput=new TextField();
quantityInput.setPromptText("Quantity");
//make add and delete buttons
Button addButton=new Button("Add");
//when user clicks the add button
addButton.setOnAction(e-> addButtonClicked());
Button deleteButton=new Button("Delete");
//when user clicks the delete button
deleteButton.setOnAction(e-> deleteButtonClicked());
////create HBox to stick all the new items
HBox hBox=new HBox();
//set padding of layout
hBox.setPadding(new Insets(10,10,10,10));//top,right.bottom,and left padding around the
entire layout
hBox.setSpacing(10);//the items within the layout is still going to be pressed up against
each other so in order to take care that we use setSpacing(10)

hBox.getChildren().addAll(nameInput,priceInput,quantityInput,addButton,deleteButton);//add
all the items to the layout

//stick the columns in the table


table =new TableView<>();
//loading all of our data what data do you want to use for your table
table.setItems(getProduct());////getProduct()is load all of our data
//add the columns to the table
table.getColumns().addAll(nameColumn,priceColumn,quantityColumn);

VBox vBox = new VBox();


//add table to a layout
vBox.getChildren().addAll(table,hBox);
Scene scene = new Scene(vBox);/*VBox is a layout that stacks all the objects on the top
e.g.label1 in the column and 20 is the space
amount pixels so they are not like buttered up*/

window.setScene(scene);//setting the scene in the Window


window.show();//It just displays it to the user
//Window is called "Stage" and the content in the Window is called the "Scene"
}/*We make a new class because it is a good idea to take your data and stick inside a new
class ,sor we are making a little spread sheet app and
in this class i have a store and we are selling the products*/

//add button clicked


public void addButtonClicked(){
Product product=new Product();//whenever we are using user data to create a new object
we want to make sure that they typed in eht right data
product.setName(nameInput.getText());//whatever they type in nameInput field we are
use that as a name
product.setPrice(Double.parseDouble(priceInput.getText()));/*whatever they type
something in priceInput field,by default it's a string so
its give an error ,even if they typed in a number it will still show an error because it is the
string bydefault so we need to parse it
into a double before use it as a product object and the set the products price*/
product.setQuantity(Integer.parseInt(quantityInput.getText()));//get the quantity input
value and convert it into an integer
//add new product item to the table
table.getItems().add(product);//get all the items that are already on table and add new
item to the table
//clear all input fields to save the time ,because if we click add button its add the item to
the table but all of their data is still in those input fields
nameInput.clear();
priceInput.clear();
quantityInput.clear();
}

//delete button clicked


public void deleteButtonClicked(){
ObservableList<Product> productsSelected,allProducts;//get the list to get the list of
whatever item the they selected and get the all items currently in the table
allProducts=table.getItems();//get the all items currently in the table
productsSelected=table.getSelectionModel().getSelectedItems();/*return any time that
user selected ,getSelectionModel() can only select
one item but we can change that if want to select multiple items at a time*/
productsSelected.forEach(allProducts::remove);//all products that user selected remove
them from all products
}
//This method is get all of the products and return the list
public ObservableList<Product> getProduct(){//data type is the name of your class so we
store product object in here
ObservableList<Product>
products=FXCollections.observableArrayList();//observableArrayList() is the type of
observable list to store java objects inside
//add a bunch of products to it
products.add(new Product("laptop",1000.0,20));
products.add(new Product("computer",2.49,100));
products.add(new Product("RAM",2000.0,208));
products.add(new Product("SSD",1.49,5));
return products;//return abservable list of product object

}
//so in the table we can sort out all the items and you can also rearranging the locations of
columns

Product Class
package javafxtopics;
public class Product {
//properties that are associated with our products e.d name ,price,quantity etc
private String name;
private double price;//price type will be doube incase if we will need decimal places
private int quantity;//quantatiy how many items we have we can also say amount,inventory
inplace of quantity

//make 2 overload constructor


/*The 1st constructor is to take all the properties and give them a default value so whenever
we create a product its have a blank value which
is default value.*/
public Product(){
this.name="";
this.price=0;
this.quantity=0;
}
//The 1st constructor take 3 parameters name price and quantity
public Product(String name,double price,int quantity){
//pass the value whatever value we will pass in the constructor
this.name=name;
this.price=price;
this.quantity=quantity;
}
//insert all the getters and setters
public void setName(String name){
this.name=name;
}
public String getName(){
return name;
}
public void setPrice(double price){
this.price=price;
}
public double getPrice(){
return price;
}
public void setQuantity(int quantity){
this.quantity=quantity;
}
public int getQuantity(){
return quantity;
}
/*we cannot change the set and get methods that don't follow convention e.g. getTheName
because it'll break JavaFx.Whenever we make tables
need to follow this naming convention*/
}
//This product class is done now we can store a bunch of products

Output:
padding

spacing
Add cache in the table:

Delete cache in the table:


Topic#21 Making Menus
How to build menus at the top of the application.
package javafxtopics;

import javafx.application.Application;
import javafx.scene.Scene;
import javafx.scene.control.Menu;
import javafx.scene.control.MenuBar;
import javafx.scene.control.MenuItem;
import javafx.scene.layout.BorderPane;
import javafx.stage.Stage;

public class JavaFXTopics extends Application {

Stage window;
BorderPane layout;//it gives the top ,left ,center,right and bottom so you can just take you
entire menu bar and stick it on the top
public static void main(String[] args) {
launch(args);//This is the method inside the Aplication class
}

@Override //start is Overriden method because we are inheritng it from the application class
public void start(Stage primaryStage) throws Exception {//All the code we write in here
that's the main JavaFX code
window = primaryStage;
window.setTitle("Making Menus");//"Title of the window" is the Title name of the Stage

//create menu
//File menu
Menu fileMenu=new Menu("File");//Menu constructor takes 1 parameter which is a
string and write in the name of the menu
//add items to the menu
fileMenu.getItems().add(new MenuItem("New Project..."));/*getItems()get the items
what what items are already in the menu and then add the new item in it and if the item you
want to add is the first item so still call the getItems()method.Add() allows you to add one
item in the menu and in order to create a
menu item we call a "new MenuItem() and give the title of the menu item*/
/*whenever a menu name have dot in it,it means that it means that whenever you click it a
new window or a new dialog box is open and whenever
this has arrow in it,it means it have submenus in it and whenever has nothing, it means it
has no option*/
fileMenu.getItems().add(new MenuItem("New Module..."));
fileMenu.getItems().add(new MenuItem("Import Project..."));

//main menu bar to add the menu and menu items in it


MenuBar menuBar=new MenuBar();//here we don't need to add the title because here we
add the menu only
//add menu to the menu bar
menuBar.getMenus().addAll(fileMenu);

layout = new BorderPane();


//stick the menu bar in the top section of the Border Pane
layout.setTop(menuBar);
Scene scene = new Scene(layout,400,300);//set layout in the scene and 400 is the width
and 300 is the height*/

window.setScene(scene);//setting the scene in the Window


window.show();//It just displays it to the user

//Window is called "Stage" and the content in the Window is called the "Scene"
}

Output:
Menu bar

Menu nameu
name

Menu itemsu
name
Topic#22 Handling Menu Clicks
package javafxtopics;

import javafx.application.Application;
import javafx.scene.Scene;
import javafx.scene.control.Menu;
import javafx.scene.control.MenuBar;
import javafx.scene.control.MenuItem;
import javafx.scene.control.SeparatorMenuItem;
import javafx.scene.layout.BorderPane;
import javafx.stage.Stage;

public class JavaFXTopics extends Application {

Stage window;
BorderPane layout;//it gives the top ,left ,center,right and bottom so you can just take you
entire menu bar and stick it on the top
public static void main(String[] args) {
launch(args);//This is the method inside the Aplication class
}

@Override //start is Overriden method because we are inheritng it from the application class
public void start(Stage primaryStage) throws Exception {//All the code we write in here
that's the main JavaFX code
window = primaryStage;
window.setTitle("Making Menus");//"Title of the window" is the Title name of the Stage
//create menu
//File menu
Menu fileMenu=new Menu("File");//Menu constructor takes 1 parameter which is a
string and write in the name of the menu
//create "fileMenu" item
MenuItem newFile=new MenuItem("New");
//wehenver the user clcik on "New" it emits an event,and it print the message in the
terminal
newFile.setOnAction(e-> System.out.println("Create a new file..."));
//add the menu item to the menu
fileMenu.getItems().add(newFile);//it is short way of add the menu item in the menu
//add item to the file menu
/*getItems()get the items what what items are already in the menu and then add the new
item in it and if the item you
want to add is the first item so still call the getItems()method.Add() allows you to add one
item in the menu*/
/*whenever a menu name have dot in it,it means that it means that whenever you click it a
new window or a new dialog box is open and whenever
this has arrow in it,it means it have submenus in it and whenever has nothing, it means it
has no option*/
fileMenu.getItems().add(new MenuItem("Open..."));//we can also add the menu item in
the menu like this
fileMenu.getItems().add(new MenuItem("Save..."));
//separator between save and settings,separators are menu items,reason to use the
separators is to group related items together
fileMenu.getItems().add(new SeparatorMenuItem());
fileMenu.getItems().add(new MenuItem("Settings..."));
//separator between settings and Exit
fileMenu.getItems().add(new SeparatorMenuItem());
fileMenu.getItems().add(new MenuItem("Exit..."));

//Edit Menu
Menu editMenu=new Menu("_Edit");// means if we press alt and then e "edit" menu will
open,basically it is a shortcut to open a menu
//add items to the "edit" menu
editMenu.getItems().add(new MenuItem("Cut"));
editMenu.getItems().add(new MenuItem("Copy"));

//disable the menu items


MenuItem paste=new MenuItem("Paste");
//wehenver the user click on "Paste" it emits an event,and it print the message in the
terminal
paste.setOnAction(e-> System.out.println("Pasting some crap"));
//if we want to disable the paste option for the user
paste.setDisable(true);
//add the menu item to "Edit" menu
editMenu.getItems().add(paste);

//main menu bar to add the menu and menu items in it


MenuBar menuBar=new MenuBar();//here we don't need to add the title because here we
add the menu only
//add menu to the menu bar
menuBar.getMenus().addAll(fileMenu,editMenu);

layout = new BorderPane();


//stick the menu bar in the top section of the Border Pane
layout.setTop(menuBar);
Scene scene = new Scene(layout,400,300);//set layout in the scene and 400 is the width
and 300 is the height*/

window.setScene(scene);//setting the scene in the Window


window.show();//It just displays it to the user

//Window is called "Stage" and the content in the Window is called the "Scene"
}

}
Output:
Topic#23 Check menu Items
package javafxtopics;

import javafx.application.Application;
import javafx.scene.Scene;
import javafx.scene.control.CheckMenuItem;
import javafx.scene.control.Menu;
import javafx.scene.control.MenuBar;
import javafx.scene.control.MenuItem;
import javafx.scene.control.SeparatorMenuItem;
import javafx.scene.layout.BorderPane;
import javafx.stage.Stage;

public class JavaFXTopics extends Application {

Stage window;
BorderPane layout;//it gives the top ,left ,center,right and bottom so you can just take you
entire menu bar and stick it on the top
public static void main(String[] args) {
launch(args);//This is the method inside the Aplication class
}

@Override //start is Overriden method because we are inheritng it from the application class
public void start(Stage primaryStage) throws Exception {//All the code we write in here
that's the main JavaFX code
window = primaryStage;
window.setTitle("Making Menus");//"Title of the window" is the Title name of the Stage
//create menu
//File menu
Menu fileMenu=new Menu("File");//Menu constructor takes 1 parameter which is a
string and write in the name of the menu
//create "fileMenu" item
MenuItem newFile=new MenuItem("New");
//wehenver the user clcik on "New" it emits an event,and it print the message in the
terminal
newFile.setOnAction(e-> System.out.println("Create a new file..."));
//add the menu item to the menu
fileMenu.getItems().add(newFile);//it is short way of add the menu item in the menu
//add item to the file menu
/*getItems()get the items what what items are already in the menu and then add the new
item in it and if the item you
want to add is the first item so still call the getItems()method.Add() allows you to add one
item in the menu*/
/*whenever a menu name have dot in it,it means that it means that whenever you click it a
new window or a new dialog box is open and whenever
this has arrow in it,it means it have submenus in it and whenever has nothing, it means it
has no option*/
fileMenu.getItems().add(new MenuItem("Open..."));//we can also add the menu item in
the menu like this
fileMenu.getItems().add(new MenuItem("Save..."));
//separator between save and settings,separators are menu items,reason to use the
separators is to group related items together
fileMenu.getItems().add(new SeparatorMenuItem());
fileMenu.getItems().add(new MenuItem("Settings..."));
//separator between settings and Exit
fileMenu.getItems().add(new SeparatorMenuItem());
fileMenu.getItems().add(new MenuItem("Exit..."));

//Edit Menu
Menu editMenu=new Menu("_Edit");// means if we press alt and then e "edit" menu will
open,basically it is a shortcut to open a menu
//add items to the "edit" menu
editMenu.getItems().add(new MenuItem("Cut"));
editMenu.getItems().add(new MenuItem("Copy"));

//disable the menu items


MenuItem paste=new MenuItem("Paste");
//wehenver the user click on "Paste" it emits an event,and it print the message in the
terminal
paste.setOnAction(e-> System.out.println("Pasting some crap"));
//if we want to disable the paste option for the user
paste.setDisable(true);
//add the menu item to "Edit" menu
editMenu.getItems().add(paste);
//create help menu
Menu helpMenu=new Menu("Help");
//create menu item
//how to use check menu items
CheckMenuItem showLines=new CheckMenuItem("Show Line Numbers");//on or off
decide whether user want to show the line numbers or not
showLines.setOnAction(e->{
//implement checked and unchecked logic
//if the user chcecked-it then it display the line numbers
if(showLines.isSelected()){
System.out.println("Program will now display line numbers");
}
//if the user unchcecked-it then it display the line numbers
else{
System.out.println("Hiding line number");
}
});

//set an item that is checked by default


CheckMenuItem autoSave=new CheckMenuItem("Enable Autosave");/*if the user
selected this then the program automatically saved but if they
unchecked it then they have to save*/
autoSave.setSelected(true);//this is selected bydefault
//add menu item to the help menu
helpMenu.getItems().addAll(showLines,autoSave);
//main menu bar to add the menu and menu items in it
MenuBar menuBar=new MenuBar();//here we don't need to add the title because here we
add the menu only
//add menu to the menu bar
menuBar.getMenus().addAll(fileMenu,editMenu,helpMenu);

layout = new BorderPane();


//stick the menu bar in the top section of the Border Pane
layout.setTop(menuBar);
Scene scene = new Scene(layout,400,300);//set layout in the scene and 400 is the width
and 300 is the height*/

window.setScene(scene);//setting the scene in the Window


window.show();//It just displays it to the user

//Window is called "Stage" and the content in the Window is called the "Scene"
}

Output:
Topic#24 Radio menu Item
Radio menu item is little bit different from checkbox menu item , they are a group of checkboxes
but you can only have one selected at a time for e.g. in game we can only choose one option
form easy, medium and hard we can’t choose easy and hard at the same time.
package javafxtopics;

import javafx.application.Application;
import javafx.scene.Scene;
import javafx.scene.control.CheckMenuItem;
import javafx.scene.control.Menu;
import javafx.scene.control.MenuBar;
import javafx.scene.control.MenuItem;
import javafx.scene.control.RadioMenuItem;
import javafx.scene.control.SeparatorMenuItem;
import javafx.scene.control.ToggleGroup;
import javafx.scene.layout.BorderPane;
import javafx.stage.Stage;

public class JavaFXTopics extends Application {

Stage window;
BorderPane layout;//it gives the top ,left ,center,right and bottom so you can just take you
entire menu bar and stick it on the top
public static void main(String[] args) {
launch(args);//This is the method inside the Aplication class
}

@Override //start is Overriden method because we are inheritng it from the application class
public void start(Stage primaryStage) throws Exception {//All the code we write in here
that's the main JavaFX code
window = primaryStage;
window.setTitle("Radio Menu Item");//"Title of the window" is the Title name of the
Stage

//create menu
//File menu
Menu fileMenu=new Menu("File");//Menu constructor takes 1 parameter which is a
string and write in the name of the menu
//create "fileMenu" item
MenuItem newFile=new MenuItem("New");
//wehenver the user clcik on "New" it emits an event,and it print the message in the
terminal
newFile.setOnAction(e-> System.out.println("Create a new file..."));
//add the menu item to the menu
fileMenu.getItems().add(newFile);//it is short way of add the menu item in the menu
//add item to the file menu
/*getItems()get the items what what items are already in the menu and then add the new
item in it and if the item you
want to add is the first item so still call the getItems()method.Add() allows you to add one
item in the menu*/
/*whenever a menu name have dot in it,it means that it means that whenever you click it a
new window or a new dialog box is open and whenever
this has arrow in it,it means it have submenus in it and whenever has nothing, it means it
has no option*/
fileMenu.getItems().add(new MenuItem("Open..."));//we can also add the menu item in
the menu like this
fileMenu.getItems().add(new MenuItem("Save..."));
//separator between save and settings,separators are menu items,reason to use the
separators is to group related items together
fileMenu.getItems().add(new SeparatorMenuItem());
fileMenu.getItems().add(new MenuItem("Settings..."));
//separator between settings and Exit
fileMenu.getItems().add(new SeparatorMenuItem());
fileMenu.getItems().add(new MenuItem("Exit..."));

//Edit Menu
Menu editMenu=new Menu("_Edit");// means if we press alt and then e "edit" menu will
open,basically it is a shortcut to open a menu
//add items to the "edit" menu
editMenu.getItems().add(new MenuItem("Cut"));
editMenu.getItems().add(new MenuItem("Copy"));

//disable the menu items


MenuItem paste=new MenuItem("Paste");
//wehenver the user click on "Paste" it emits an event,and it print the message in the
terminal
paste.setOnAction(e-> System.out.println("Pasting some crap"));
//if we want to disable the paste option for the user
paste.setDisable(true);
//add the menu item to "Edit" menu
editMenu.getItems().add(paste);

//create help menu


Menu helpMenu=new Menu("Help");
//create menu item
//how to use check menu items
CheckMenuItem showLines=new CheckMenuItem("Show Line Numbers");//on or off
decide whether user want to show the line numbers or not
showLines.setOnAction(e->{
//implement checked and unchecked logic
//if the user chcecked-it then it display the line numbers
if(showLines.isSelected()){
System.out.println("Program will now display line numbers");
}
//if the user unchcecked-it then it display the line numbers
else{
System.out.println("Hiding line number");
}
});

//set an item that is checked by default


CheckMenuItem autoSave=new CheckMenuItem("Enable Autosave");/*if the user
selected this then the program automatically saved but if they
unchecked it then they have to save*/
autoSave.setSelected(true);//this is selected bydefault
//add menu item to the help menu
helpMenu.getItems().addAll(showLines,autoSave);

//Difficulty Radio Menu Items


//Make a menu
Menu difficultyMenu=new Menu("Difficulty");
ToggleGroup diffcultyToggle=new ToggleGroup();/*sticking all of the item inside the
toggle group and that will give the functionality
where the user can only select one item at a time*/
//create Radio Menu Items
RadioMenuItem easy=new RadioMenuItem("Easy");
RadioMenuItem medium=new RadioMenuItem("Medium");
RadioMenuItem hard=new RadioMenuItem("Hard");
//add menuItems to the group
easy.setToggleGroup(diffcultyToggle);//set toggle group to "difficulty toggle"
medium.setToggleGroup(diffcultyToggle);
hard.setToggleGroup(diffcultyToggle);
//add all the items to the menu
difficultyMenu.getItems().addAll(easy,medium,hard);

//main menu bar to add the menu and menu items in it


MenuBar menuBar=new MenuBar();//here we don't need to add the title because here we
add the menu only
//add menu to the menu bar
menuBar.getMenus().addAll(fileMenu,editMenu,helpMenu,difficultyMenu);

layout = new BorderPane();


//stick the menu bar in the top section of the Border Pane
layout.setTop(menuBar);
Scene scene = new Scene(layout,400,300);//set layout in the scene and 400 is the width
and 300 is the height*/

window.setScene(scene);//setting the scene in the Window


window.show();//It just displays it to the user
//Window is called "Stage" and the content in the Window is called the "Scene"
}

}
Output:

User can select only item to it at a time.

Topic#25 CSS Themes And Styles


Colors Code

How to use CSS with JavaFX. JavaFX also has a couple other style sheets built-in.
package javafxtopics;

import java.io.File;
import javafx.application.Application;
import javafx.geometry.Insets;
import javafx.scene.Scene;
import javafx.scene.control.*;
import javafx.scene.layout.GridPane;
import javafx.stage.Stage;

public class JavaFXTopics extends Application {


Stage window;
public static void main(String[] args) {
launch(args);//This is the method inside the Aplication class
}

@Override //start is Overriden method because we are inheritng it from the application class
public void start(Stage primaryStage) throws Exception {//All the code we write in here
that's the main JavaFX code
window=primaryStage;
window.setTitle("Title of the window");//"Title of the window" is the Title name of the
Stage
//made a grid layout
GridPane grid=new GridPane();
//padding between entire layout in the border of the window of ten pixels
grid.setPadding(new Insets(10,10,10,10));/*The first thing of the GridPane layout is to set
Padding and this takes Insets object as
parameter and 10 is the amount of padding that you want to add to each edge s0 it puts
the10 pixel padding around your entire
layout in the window*/
//spacing vertically is 8
grid.setVgap(8);//set vertical spacing
//spacing horizontally is 10
grid.setHgap(10);//set horizontal spacing each gap
//adding some items
//name label
//we made an item that we want to add now ,where do we want to add it what column
what row
Label nameLabel=new Label("Username : ");
/*so we call a method called set constraints so this takes 3 parameters 1st one is the child(
what item do you want to the grid that is the label) and other 2 is what cloumn and
what row,in other words the position where you want to add it*/
GridPane.setConstraints(nameLabel,0,0);//it add the item in 0 row and 0 column in other
words this label is appear in the top left of the grid

//Name input, which is the area that they type their name so we take the TextField
TextField nameInput=new TextField("Bucky");// we have default text in there so it it
gives the default text but We can also create it blank
//after done to create the item ,add it to the grid setconstraints
GridPane.setConstraints(nameInput,1,0);//it add the item which is nameInput in 0 row
and 1 column

//Password Label
Label passLabel=new Label("Password : ");
GridPane.setConstraints(passLabel,0,1);//it add the item in 1 row and 0 column
//pass input, which is the area that they type their Password so we take the TextField
TextField passInput=new TextField();
passInput.setPromptText("password");/*when the user click this "passwrod" this little
grey indicator dissapear,so this the difference
between above default text which is not dissapear by clicking and setPromptText method
which disappear the grey indicator by clicking*/
GridPane.setConstraints(passInput,1,1);//it add the item in 1 row and 1 column

//create login button


Button loginButton=new Button("Login In");
GridPane.setConstraints(loginButton,1,2);//it add the item in 2 row and 1 column
//add everything to the grid
grid.getChildren().addAll(nameLabel,nameInput,passLabel,passInput,loginButton);
//grid is 350 by 200 big
Scene scene = new Scene(grid,350,200);//This first parameters scenes take is the
layout ,what stuff you want to arrranged in your scene and other two parameters are the size of
your scene 350 is the width and 200 is the height

//add the CSS fie


/*
This is for Adding the css styling functionality working,
add the css file name as it is.
*/
//Because we are using NETBEANS IDE thats why this method will apply.
File cssFile = new File("src\\javafxtopics\\Viper.css");
//MakIng an absolute path.
String filepath = "file:///" + cssFile.getAbsolutePath().replace("\\", "/").replace(" ",
"%20");
scene.getStylesheets().add(filepath);

window.setScene(scene);//setting the scene in the Window


window.show();//It just displays it to the user

//Window is called "Stage" and the content in the Window is called the "Scene"

}
}
//antime you want to work with a new custom style it's always a good idea to add a new CSS
file

Viper.css file

/*
start styling for individual widgets*/
.root{
/*start writing the properties and their values*/
-fx-background-color:#BA8BAF /*you can use any hex color*/
-fx-font-size 11pt;
}

Output:

Topic#26 CSS Inline Styles and Selectors


package javafxtopics;
import java.io.File;
import javafx.application.Application;
import javafx.geometry.Insets;
import javafx.scene.Scene;
import javafx.scene.control.*;
import javafx.scene.layout.GridPane;
import javafx.stage.Stage;

public class JavaFXTopics extends Application {


Stage window;
public static void main(String[] args) {
launch(args);//This is the method inside the Aplication class
}

@Override //start is Overriden method because we are inheritng it from the application class
public void start(Stage primaryStage) throws Exception {//All the code we write in here
that's the main JavaFX code
window=primaryStage;
window.setTitle("Title of the window");//"Title of the window" is the Title name of the
Stage
//made a grid layout
GridPane grid=new GridPane();
//padding between entire layout in the border of the window of ten pixels
grid.setPadding(new Insets(10,10,10,10));/*The first thing of the GridPane layout is to set
Padding and this takes Insets object as
parameter and 10 is the amount of padding that you want to add to each edge s0 it puts
the10 pixel padding around your entire
layout in the window*/
//spacing vertically is 8
grid.setVgap(8);//set vertical spacing
//spacing horizontally is 10
grid.setHgap(10);//set horizontal spacing each gap

//adding some items


//name label
//we made an item that we want to add now ,where do we want to add it what column
what row
Label nameLabel=new Label("Username : ");

//whenever you use the inline style,you can take a style and apply it to a single element or
a single item on your page
//nameLabel.setStyle("-fx-text-fill: YELLOW");//you can also write in hex code form
e.g.-fx-text-fill: E8E8E8

/*so we call a method called set constraints so this takes 3 parameters 1st one is the child(
what item do you want to the grid that is the label) and other 2 is what cloumn and
what row,in other words the position where you want to add it*/
GridPane.setConstraints(nameLabel,0,0);//it add the item in 0 row and 0 column in other
words this label is appear in the top left of the grid

//Name input, which is the area that they type their name so we take the TextField
TextField nameInput=new TextField("Bucky");// we have default text in there so it it
gives the default text but We can also create it blank
//after done to create the item ,add it to the grid setconstraints
GridPane.setConstraints(nameInput,1,0);//it add the item which is nameInput in 0 row
and 1 column

//Password Label
Label passLabel=new Label("Password : ");
GridPane.setConstraints(passLabel,0,1);//it add the item in 1 row and 0 column
//pass input, which is the area that they type their Password so we take the TextField
TextField passInput=new TextField();
passInput.setPromptText("password");/*when the user click this "passwrod" this little
grey indicator dissapear,so this the difference
between above default text which is not dissapear by clicking and setPromptText method
which disappear the grey indicator by clicking*/
GridPane.setConstraints(passInput,1,1);//it add the item in 1 row and 1 column

//create login button


Button loginButton=new Button("Login In");
GridPane.setConstraints(loginButton,1,2);//it add the item in 2 row and 1 column
//add everything to the grid
grid.getChildren().addAll(nameLabel,nameInput,passLabel,passInput,loginButton);
//grid is 350 by 200 big
Scene scene = new Scene(grid,350,200);//This first parameters scenes take is the
layout ,what stuff you want to arrranged in your scene and other two parameters are the size of
your scene 350 is the width and 200 is the height

//add the CSS fie


/*
This is for Adding the css styling functionality working,
add the css file name as it is.
*/
//Because we are using NETBEANS IDE thats why this method will apply.
File cssFile = new File("src\\javafxtopics\\Viper.css");

//MakIng an absolute path.


String filepath = "file:///" + cssFile.getAbsolutePath().replace("\\", "/").replace(" ",
"%20");
scene.getStylesheets().add(filepath);

window.setScene(scene);//setting the scene in the Window


window.show();//It just displays it to the user

//Window is called "Stage" and the content in the Window is called the "Scene"

}
}
//antime you want to work with a new custom style it's always a good idea to add a new CSS
file
Viper.css file

/*
start styling for individual widgets*/
.root{
/*start writing the properties and their values*/
-fx-background-color:#BA8BAF /*you can use any hex color*/
-fx-font-size 11pt;
}
/*if we want to apply same style in each label*/
.label{
-fx-text-fill:#E8E8E8;/*e.g."change the label text e.g. "username",e.t.c*/
}
/*If you want to change the buttons,you can change the background color and also the
roundness of the corner*/
.button{
-fx-background-color:aqua;/*it gives a "aqua" background to the buttons and if anytime you
want a gradient call linear Gradient*/
/*-fx-background-color:linear-gradient(#dc9656,#ab4642);*/
-fx-text-fill: #FFFFFF ;
/*change the roundness and border radius of button*/
-fx-background-radius: 4;/*round the button by 6 pixels,the higher the number the more
rounded your button*/
}

Output:
Topic#27 CSS Custom Style Classes And Selectors
How to make your own custom classes instead of built-in class.
package javafxtopics;

import java.io.File;
import javafx.application.Application;
import javafx.geometry.Insets;
import javafx.scene.Scene;
import javafx.scene.control.*;
import javafx.scene.layout.GridPane;
import javafx.stage.Stage;

public class JavaFXTopics extends Application {


Stage window;
public static void main(String[] args) {
launch(args);//This is the method inside the Aplication class
}

@Override //start is Overriden method because we are inheritng it from the application class
public void start(Stage primaryStage) throws Exception {//All the code we write in here
that's the main JavaFX code
window=primaryStage;
window.setTitle("Title of the window");//"Title of the window" is the Title name of the
Stage
//made a grid layout
GridPane grid=new GridPane();
//padding between entire layout in the border of the window of ten pixels
grid.setPadding(new Insets(10,10,10,10));/*The first thing of the GridPane layout is to set
Padding and this takes Insets object as
parameter and 10 is the amount of padding that you want to add to each edge s0 it puts
the10 pixel padding around your entire
layout in the window*/
//spacing vertically is 8
grid.setVgap(8);//set vertical spacing
//spacing horizontally is 10
grid.setHgap(10);//set horizontal spacing each gap

//adding some items


//name label
//we made an item that we want to add now ,where do we want to add it what column
what row
Label nameLabel=new Label("Username : ");
//APPLY bold-label ID to nameLabel to bold the label
nameLabel.setId("bold-label");

//whenever you use the inline style,you can take a style and apply it to a single element or
a single item on your page
//nameLabel.setStyle("-fx-text-fill: YELLOW");//you can also write in hex code form
e.g.-fx-text-fill: E8E8E8

/*so we call a method called set constraints so this takes 3 parameters 1st one is the child(
what item do you want to the grid that is the label) and other 2 is what cloumn and
what row,in other words the position where you want to add it*/
GridPane.setConstraints(nameLabel,0,0);//it add the item in 0 row and 0 column in other
words this label is appear in the top left of the grid

//Name input, which is the area that they type their name so we take the TextField
TextField nameInput=new TextField("Bucky");// we have default text in there so it it
gives the default text but We can also create it blank
//after done to create the item ,add it to the grid setconstraints
GridPane.setConstraints(nameInput,1,0);//it add the item which is nameInput in 0 row
and 1 column

//Password Label
Label passLabel=new Label("Password : ");
GridPane.setConstraints(passLabel,0,1);//it add the item in 1 row and 0 column
//pass input, which is the area that they type their Password so we take the TextField
TextField passInput=new TextField();
passInput.setPromptText("password");/*when the user click this "passwrod" this little
grey indicator dissapear,so this the difference
between above default text which is not dissapear by clicking and setPromptText method
which disappear the grey indicator by clicking*/
GridPane.setConstraints(passInput,1,1);//it add the item in 1 row and 1 column

//create login button


Button loginButton=new Button("Login In");
GridPane.setConstraints(loginButton,1,2);//it add the item in 2 row and 1 column

//create Sign up button


Button signUpButton=new Button("Sign Up");
//if i want to use button-blue class
signUpButton.getStyleClass().add("button-blue");// inherit all the properties from the
“buttons” in Viper class before ovveriden with “button blue”
GridPane.setConstraints(signUpButton,1,3);//it add the item in 2 row and 1 column

//add everything to the grid

grid.getChildren().addAll(nameLabel,nameInput,passLabel,passInput,loginButton,signUpButt
on);
//grid is 350 by 200 big
Scene scene = new Scene(grid,350,200);//This first parameters scenes take is the
layout ,what stuff you want to arrranged in your scene and other two parameters are the size of
your scene 350 is the width and 200 is the height

//add the CSS fie


/*
This is for Adding the css styling functionality working,
add the css file name as it is.
*/
//Because we are using NETBEANS IDE thats why this method will apply.
File cssFile = new File("src\\javafxtopics\\Viper.css");

//MakIng an absolute path.


String filepath = "file:///" + cssFile.getAbsolutePath().replace("\\", "/").replace(" ",
"%20");
scene.getStylesheets().add(filepath);

window.setScene(scene);//setting the scene in the Window


window.show();//It just displays it to the user

//Window is called "Stage" and the content in the Window is called the "Scene"

}
}
//antime you want to work with a new custom style it's always a good idea to add a new CSS
file

Viper.css File
/*
start styling for individual widgets*/
.root{
/*start writing the properties and their values*/
-fx-background-color:#BA8BAF /*you can use any hex color*/
-fx-font-size 11pt;
}
/*anytime you want to style all the labels then use the label class and lower case it*/
.label{
-fx-text-fill:#E8E8E8;/*e.g."change the label text e.g. "username",e.t.c*/
}
/*anytime you want to style all the buttons then use the button class and lower case it*/
/*If you want to change the buttons,you can change the background color and also the
roundness of the corner*/
.button{
-fx-background-color:aqua;/*it gives a "aqua" background to the buttons and if anytime you
want a gradient call linear Gradient*/
/*-fx-background-color:linear-gradient(#dc9656,#ab4642);*/
-fx-text-fill: #FFFFFF ;
/*change the roundness and border radius of button*/
-fx-background-radius: 4;/*round the button by 6 pixels,the higher the number the more
rounded your button*/
}
/*making own custom style for a button*/
.button-blue{/*give the button name blue*/
-fx-background-color:#7cafc2;/*it gives a "aqua" background to the buttons and if anytime
you want a gradient call linear Gradient*/
/*-fx-background-color:linear-gradient(#dc9656,#ab4642);*/
-fx-text-fill: #FFFFFF ;
/*change the roundness and border radius of button*/
-fx-background-radius: 4;/*round the button by 6 pixels,the higher the number the more
rounded your button*/
}
/*antime you want to add an ID(own custom style class), use hash sign and name your ID
e.g.bold-label is the ID*/
#bold-label{/*I wanted to apply an ID to the labels to bold them*/
-fx-font-weight:bold;
}

Output:
Topic#28 Properties
Why we need properties in JavaFX. Whenever we are using JavaFX we ca actually treat these
properties as an object.
package javafxtopics;

import javafx.application.Application;
import javafx.scene.Scene;
import javafx.scene.control.*;
import javafx.scene.layout.StackPane;
import javafx.stage.Stage;

public class JavaFXTopics extends Application {


Stage window;
public static void main(String[] args) {
launch(args);//This is the method inside the Aplication class
}

@Override //start is Overriden method because we are inheritng it from the application class
public void start(Stage primaryStage) throws Exception {//All the code we write in here
that's the main JavaFX code
window=primaryStage;
window.setTitle("Title of the window");//"Title of the window" is the Title name of the
Stage

//create a new person and object name is bucky and we does not set any name yet
Person bucky=new Person();
/*setup a listener on "first name", listener will call whenever value of "first name"
changes
and ,it takes 3 parameters "v" is the object ,2nd is the oldValue and 3rd is the new value
e.g.if you are change "bucky"to "sally" then
bucky is the oldvalue and sally is the new value*/
bucky.firstNameProperty().addListener((v,oldValue,newValue)->{
//run a little bit of code after change the value
System.out.println("Name changed to "+newValue );
System.out.println("fisrNameProperty(): "+bucky.firstNameProperty());
System.out.println("getFirstName(): "+bucky.getFirstName());//whenver you want to
gets the user name call getters and setters
});

//create button
Button button=new Button("Submit");
//whenever we click the button it emits an event
button.setOnAction(e-> bucky.setFirstName("Duaa"));

//create a layout
StackPane layout=new StackPane();//StackPane is the really simple layout it's going to
position this button in the middle
//add button to the layout
layout.getChildren().addAll(button);
//layout is 350 by 200 big
Scene scene = new Scene(layout,350,200);//This first parameters scenes take is the
layout ,what stuff you want to arrranged in your scene and other two parameters are the size of
your scene 350 is the width and 200 is the height

window.setScene(scene);//setting the scene in the Window


window.show();//It just displays it to the user

//Window is called "Stage" and the content in the Window is called the "Scene"
}
}
//maybe i have a website or some database and i have a whole bunch of users so to store all
their information inside we use the person class.

Person Class

package javafxtopics;
import javafx.beans.property.SimpleStringProperty;
import javafx.beans.property.StringProperty;

public class Person {


//how to actually treat these values as a propeties
//make a new private value and you use String property and it imports the package
/*create StringProperty(abstract class) Object and SimpleStringProperty is for whenever
you want to create something that you can read and write
from or write to*/
private StringProperty firstName=new
SimpleStringProperty(this,"firstName","");/*"Stringproperty" is not a regular String,it is a
property and is a
abstract class and SimpleStringProperty is the class to create new string properties that you
can read and write to,and it takes three parameters
the first one is this(it refers to the object that contains it and the second one is the name of
object and the third one is the default value of
nothing*/

//returns the StringProperty object itself not the value


public StringProperty firstNameProperty(){
return firstName;
}
//return the firstName value(i.e."Bucky")
public String getFirstName(){
return firstName.get();
}
//set the first name value
public void setFirstName(String firstName){
this.firstName.set(firstName);
}

}
Output:

Topic#29 Binding
In this code we learn, how to take 2 properties and bind them together. So we create an integer
property called X and another one called Y and bind them together. These properties are tied
together or connected so whenever we change the value of X the value of Y automatically
changes.
package javafxtopics;

import javafx.application.Application;
import javafx.beans.property.IntegerProperty;
import javafx.beans.property.SimpleIntegerProperty;
import javafx.scene.Scene;
import javafx.scene.control.*;
import javafx.scene.layout.StackPane;
import javafx.stage.Stage;

public class JavaFXTopics extends Application {


Stage window;
public static void main(String[] args) {
launch(args);//This is the method inside the Aplication class
}

@Override //start is Overriden method because we are inheritng it from the application class
public void start(Stage primaryStage) throws Exception {//All the code we write in here
that's the main JavaFX code
window=primaryStage;
window.setTitle("Title of the window");//"Title of the window" is the Title name of the
Stage

//create an object of IntegerProperty


IntegerProperty x=new SimpleIntegerProperty(3);//x is the object and it has the intial
value of 3
//create another object
IntegerProperty y=new SimpleIntegerProperty();//y is the object and it has no intial value

//bind y to the value of x


y.bind(x.multiply(10));//value of y is bound to the value of x multiplied by 10
//whenever we update the value of x the value of y automatically updated
System.out.println("x : "+x.getValue());
System.out.println("y : "+y.getValue()+"\n");

//set the value of x "9"


x.setValue(9);
System.out.println("x : "+x.getValue());
System.out.println("y : "+y.getValue()+"\n");

//create button
Button button=new Button("Submit");

//create a layout
StackPane layout=new StackPane();//StackPane is the really simple layout it's going to
position this button in the middle
//add button to the layout
layout.getChildren().addAll(button);
//layout is 350 by 200 big
Scene scene = new Scene(layout,350,200);//This first parameters scenes take is the
layout ,what stuff you want to arrranged in your scene and other two parameters are the size of
your scene 350 is the width and 200 is the height

window.setScene(scene);//setting the scene in the Window


window.show();//It just displays it to the user

//Window is called "Stage" and the content in the Window is called the "Scene"
}
}

Output:

Topic#30 Binding Properties Example


For e.g. W can type the user name as input and the label underneath it . And as you are typing
that label and that text it gets updated in real time there’s no need of button it all done with
binding. We can update the user interface in real time.
package javafxtopics;

import javafx.application.Application;
import javafx.geometry.Pos;
import javafx.scene.Scene;
import javafx.scene.control.*;
import javafx.scene.layout.HBox;
import javafx.scene.layout.VBox;
import javafx.stage.Stage;

public class JavaFXTopics extends Application {


Stage window;
public static void main(String[] args) {
launch(args);//This is the method inside the Aplication class
}

@Override //start is Overriden method because we are inheritng it from the application class
public void start(Stage primaryStage) throws Exception {//All the code we write in here
that's the main JavaFX code
window=primaryStage;
window.setTitle("Title of the window");//"Title of the window" is the Title name of the
Stage

//Input and Labels


TextField userInput=new TextField();
userInput.setMaxWidth(200);//width of the textfield
//create 2 labels 1 is for the message e.g. "Welcome to the Site" and 2 is
Label firstLabel=new Label("Welcome to the Site ");
Label secondLabel=new Label();//leave this blank bydefault
//add lables to the HBox layout
HBox bottomText=new HBox(firstLabel,secondLabel);
bottomText.setAlignment(Pos.CENTER);

//create a layout
VBox vBox=new VBox(10,userInput,bottomText);//10 is the spacing
vBox.setAlignment(Pos.CENTER);

secondLabel.textProperty().bind(userInput.textProperty());/*whatever the user input we


call it textProperty,userInput.textProperty()is
the text that they type in Inputfield and we can get it by bind the second label.So
whenever the "userInput" updates that label automatically
updates*/
//layout is 350 by 200 big
Scene scene = new Scene(vBox,350,200);//This first parameters scenes take is the
layout ,what stuff you want to arrranged in your scene and other two parameters are the size of
your scene 350 is the width and 200 is the height

window.setScene(scene);//setting the scene in the Window


window.show();//It just displays it to the user

//Window is called "Stage" and the content in the Window is called the "Scene"
}
}

Output:

Topic#31 Introduction to FXML


FXML is the HTML for Java. You can use it to design the view, in other words the layout or the
interface for the user and then you can stick all of your brains all of the logic in a separate file
called a Controller. Reason to use FXML because it breaks up your view and your logic so, it
organizes your project a little bit easier. FXML is based on XML language
First one is the main that is our starting point.
Second one is the Controller.
And third one is FXML.
Main Class

package fxmlexample;
import java.io.IOException;
import javafx.application.Application;
import javafx.fxml.FXMLLoader;
import javafx.scene.*;
import javafx.stage.Stage;
public class FXMLExample extends Application {
Stage window;
//whenever the program first starts it call main
public static void main(String[] args) {
launch(args);
}
//after main call will "start"
@Override
public void start(Stage primaryStage) throws IOException {
Parent r=FXMLLoader.load(getClass().getResource("FXMLDocument.fxml"));//kick off
the resource which is "FXMLDocument.fxml" file
/*FMXL file tied to the FXMLDocumentController.java*/
window=primaryStage;
window.setTitle("Here Title");
window.setScene(new Scene(r,300,250));
window.show();

}
}

Controller Class

package fxmlexample;
/*whenever we click the button to print something on the terminal e.g.whenever we submit a
form a send it to the database,all the behind the scenes
logic stick into this class*/

public class FXMLDocumentController {


}
FXML file
<?xml version="1.0" encoding="UTF-8"?>
<?import javafx.scene.control.*?>
<?import javafx.scene.layout.*?>

<VBox id="AnchorPane" prefHeight="400.0" prefWidth="600.0"


xmlns:fx="http://javafx.com/fxml/1"
fx:controller="fxmlexample.FXMLDocumentController">

<Label text="i like Coding"/>


<Button text = "Submit"/>
</VBox>

Output:

Topic#32 Controllers in FXML


Main method class
package fxmlexample;
import java.io.IOException;
import javafx.application.Application;
import javafx.fxml.FXMLLoader;
import javafx.scene.*;
import javafx.stage.Stage;
public class FXMLExample extends Application {
Stage window;
//whenever the program first starts it call main
public static void main(String[] args) {
launch(args);
}
//after main call will "start"
@Override
public void start(Stage primaryStage) throws IOException {
Parent r=FXMLLoader.load(getClass().getResource("FXMLDocument.fxml"));//kick off
the resource which is "FXMLDocument.fxml" file
/*FMXL file tied to the FXMLDocumentController.java*/
window=primaryStage;
window.setTitle("Here Title");
window.setScene(new Scene(r,300,250));
window.show();

}
}

Contoller Class
package fxmlexample;

import javafx.scene.control.Button;

/*whenever we click the button to print something on the terminal e.g.whenever we submit a
form a send it to the database,all the behind the scenes
logic stick into this class*/
//only one FXML file can only have a one single controller
public class FXMLDocumentController {

/*whenever we click the button to print something on the terminal e.g.whenever we submit
a form a send it to the database,all the behind the scenes
logic stick into this class*/
public Button button;//it refer to the "FXMLDocument" id "button" to link these
together,because whenever we start our fxml project it find all the ids in the Controller

public void handleButtonClick() {


System.out.println("Run some code the user does enable not see");
button.setText("Stop Touching me!");
}

}
/*id="button" refers to the variable and action(onAction="#handleButtonClick") refers to the
method in the Controller class*/
FXML Document Class

<?import javafx.scene.control.*?>
<?import javafx.scene.layout.*?>

<VBox id="AnchorPane" prefHeight="400.0" prefWidth="600.0"


xmlns:fx="http://javafx.com/fxml/1"
fx:controller="fxmlexample.FXMLDocumentController">

<Label text="i like Coding"/>


<Label>
<text>This is Label 2</text>
</Label>

<Button text = "Submit" fx:id="button" onAction="#handleButtonClick"/>


</VBox>

Output:

Topic#33 Initialize, Binding and Reusable Components


How to use an initializer and how to perform a binding in FXML.
Binding is to tie a property of one object to a property of another object.
Main Class

package fxmlexample;
import java.io.IOException;
import javafx.application.Application;
import javafx.fxml.FXMLLoader;
import javafx.scene.*;
import javafx.stage.Stage;
public class FXMLExample extends Application {
Stage window;
//whenever the program first starts it call main
public static void main(String[] args) {
launch(args);
}
//after main call will "start"
@Override
public void start(Stage primaryStage) throws IOException {
Parent r=FXMLLoader.load(getClass().getResource("FXMLDocument.fxml"));//kick off
the resource which is "FXMLDocument.fxml" file
/*FMXL file tied to the FXMLDocumentController.java*/
window=primaryStage;
window.setTitle("Here Title");
Scene scene=new Scene(r,300,200);
window.setScene(scene);
window.show();

}
}

Controller Class
package fxmlexample;

import java.net.URL;
import java.util.ResourceBundle;
import javafx.fxml.Initializable;
import javafx.scene.control.Button;

/*whenever we click the button to print something on the terminal e.g.whenever we submit a
form a send it to the database,all the behind the scenes
logic stick into this class*/
//only one FXML file can only have a one single controller
public class FXMLDocumentController implements Initializable {//whenever we use
"initilizable" we actually need to implement one method called initialize
@Override
//without call any method manually,it calls initialize
public void initialize(URL location, ResourceBundle resources){
System.out.println("(This is the part of Initializable ) Loading User Data ");
}

FXML File
<?xml version="1.0" encoding="UTF-8"?>
<?import javafx.scene.control.*?>
<?import javafx.scene.layout.*?>

<VBox id="AnchorPane" prefHeight="400.0" prefWidth="600.0"


xmlns:fx="http://javafx.com/fxml/1"
fx:controller="fxmlexample.FXMLDocumentController">

<!-- *************** This is part of Binding ************ -->


<Label text= "This is Label" fx:id="FirstLabel"/> <!--we need to give the id to the label for
the refernce-->

<!--bind the value of first label with the second label-->


<Label text="${FirstLabel.text}"/> <!--whenever we want to bind we first use the dollar
sign and whenever we use dollar sign it means a refernce
to something-->

<!-- ************** This is the part of reusable Components *********** -->

<!--Here we are creating a logic where we create objects which are reusable-->
<!-- whenever we use an object over and over and over again you need to define it as a
reusable object-->
<fx:define> <!--In this tag we define the object which is reusable through code-->
<ToggleGroup fx:id="togglegroup"/>
</fx:define>

<Label text= "Difficulty"/>

<!--Creating our RadioButton and for each raido button you set it to the same toggle group
because toggleGroup is used whever we want to
select one option from 3 options. And anytime we want to reference something use dollar
sign-->
<RadioButton text="Easy" toggleGroup="$togglegroup"/>
<RadioButton text="Medium" toggleGroup="$togglegroup"/>
<RadioButton text="Hard" toggleGroup="$togglegroup"/>
</VBox>

Output:

You might also like