JavaFX
JavaFX
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;
@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
//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:
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;
/*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"
@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
//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:
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;
/*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"
@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
/*(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
//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;
@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
//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
//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;
@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
//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 {
package javafxtopics;
import javafx.application.Application;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.layout.StackPane;
import javafx.stage.Stage;
@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
//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 */
//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;
@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"
}
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 */
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 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;
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*/
//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;
//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
//Window is called "Stage" and the content in the Window is called the "Scene"
}
}
Output:
Horizontal gap
Vertical gap
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;
@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*/
//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;
@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;
@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");
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”.
@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
//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
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:
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;
@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());
//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;
Stage window;
//create Tree View
TreeView<String> tree;
@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
//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
}
});
//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:
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;
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
//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;
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
hBox.getChildren().addAll(nameInput,priceInput,quantityInput,addButton,deleteButton);//add
all the items to the layout
}
//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
Output:
padding
spacing
Add cache in the table:
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;
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..."));
//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;
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"));
//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;
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"));
//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;
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"));
}
Output:
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;
@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
//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:
@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
//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
//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;
@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
//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
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
//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;
@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 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;
}
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;
@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 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 is called "Stage" and the content in the Window is called the "Scene"
}
}
Output:
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;
@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 layout
VBox vBox=new VBox(10,userInput,bottomText);//10 is the spacing
vBox.setAlignment(Pos.CENTER);
//Window is called "Stage" and the content in the Window is called the "Scene"
}
}
Output:
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*/
Output:
}
}
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
}
/*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.*?>
Output:
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.*?>
<!--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>
<!--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: