Kaynaklar

This is a perfect playlist for learning JavaFX

Hello window

For creating a basic window.

package com.example.javafxtest;

import javafx.application.Application;
import javafx.fxml.FXMLLoader;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.layout.FlowPane;
import javafx.stage.Stage;

import java.io.IOException;

public class HelloApplication extends Application {
    @Override
    public void start(Stage stage) throws IOException {
        stage.setTitle("This is my window");
        stage.show();
    }

    public static void main(String[] args) {
        launch();
    }
}

We can add a button to empty window:

    public void start(Stage stage) throws IOException {
        stage.setTitle("This is my window");

        Button button = new Button();
        button.setText("Click ME");

        StackPane layout = new StackPane();
        layout.getChildren().add(button);

        Scene scene = new Scene(layout,300, 600);
        stage.setScene(scene);
        stage.show();
    }

Button Click

public class HelloApplication extends Application implements EventHandler<ActionEvent> {

    public static void main(String[] args) {
        launch();
    }

    Button BClickMe;

    @Override
    public void start(Stage stage) throws IOException {
        stage.setTitle("This is my window");

        BClickMe = new Button();
        BClickMe.setText("Click ME");
        BClickMe.setOnAction(this); // We have to call this for implement click functionality.
        //BClickMe.setOnAction(e->System.out.println("This is a lambda expression."));
        // we can implement same functionality by a lambda function

        StackPane layout = new StackPane();
        layout.getChildren().add(BClickMe);

        Scene scene = new Scene(layout,300, 300);
        stage.setScene(scene);
        stage.show();
    }

    // we implement EventHandler<ActionEvent>
    // with this function we can handle our buttons
    @Override
    public void handle(ActionEvent actionEvent) {
        if(actionEvent.getSource() == BClickMe)
            BClickMe_OnClick();
    }

    public void BClickMe_OnClick(){
        System.out.println("Button was clicked;");
    }

}

Scenes

In this example, we change the scene.

public class HelloApplication extends Application implements EventHandler<ActionEvent> {

    public static void main(String[] args) {
        launch();
    }

    Stage window;
    Scene scene1, scene2;
    Button button1,button2;

    @Override
    public void start(Stage stage) throws IOException {

        window = stage;

        Label label1 = new Label("Welcome to GCN show");
        Label label2 = new Label("Welcome to Pandora's box");

        button1 = new Button("Go to scene 2");
        button1.setOnAction(this);
        button2 = new Button("Go to scene 1");
        button2.setOnAction(this);

        VBox layout1 = new VBox(20);
        layout1.getChildren().addAll(label1,button1);
        VBox layout2 = new VBox(20);
        layout2.getChildren().addAll(label2,button2);

        scene1 = new Scene(layout1,300,300);
        scene2 = new Scene(layout2,600,600);


        window.setScene(scene1);
        window.setTitle("Scene Example");
        window.show();

    }

    // we implement EventHandler<ActionEvent>
    // with this function we can handle our buttons
    @Override
    public void handle(ActionEvent actionEvent) {
        if(actionEvent.getSource() == button1) button1_OnClick();
        if(actionEvent.getSource() == button2) button2_OnClick();
    }

    public void button1_OnClick(){
        window.setScene(scene2);
    }
    public void button2_OnClick(){
        window.setScene(scene1);
    }

}

Message box

We will create a separate window.

Modality

A stage has one of the following modalities:

  • Modality.NONE – a stage that does not block any other window.
  • Modality.WINDOW_MODAL – a stage that blocks input events from being delivered to all windows from its owner (parent) to its root. Its root is the closest ancestor window without an owner.
  • Modality.APPLICATION_MODAL – a stage that blocks input events from being delivered to all windows from the same application, except for those from its child hierarchy.

When a window is blocked by a modal stage its Z-order relative to its ancestors is preserved, and it receives no input events and no window activation events, but continues to animate and render normally. Note that showing a modal stage does not necessarily block the caller. The show() method returns immediately regardless of the modality of the stage. Use the showAndWait() method if you need to block the caller until the modal stage is hidden (closed). The modality must be initialized before the stage is made visible.

https://docs.oracle.com/javase/8/javafx/api/javafx/stage/Stage.html

package com.example.javafxtest;

import javafx.application.Application;
import javafx.event.ActionEvent;
import javafx.event.EventHandler;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.control.Label;
import javafx.scene.layout.VBox;
import javafx.stage.Stage;

import java.io.IOException;

public class HelloApplication extends Application implements EventHandler<ActionEvent> {

    public static void main(String[] args) {
        launch();
    }

    Stage window;
    Scene scene1;
    Button button1;

    @Override
    public void start(Stage stage) throws IOException {
        window = stage;

        Label label1 = new Label("This is our first window");
        button1 = new Button("Show the message box ;)");
        button1.setOnAction(this);

        VBox layout1 = new VBox(20);
        layout1.getChildren().addAll(label1,button1);

        scene1 = new Scene(layout1,300,300);

        window.setScene(scene1);
        window.setTitle("Scene Example");
        window.show();
    }

    // we implement EventHandler<ActionEvent>
    // with this function we can handle our buttons
    @Override
    public void handle(ActionEvent actionEvent) {
        if(actionEvent.getSource() == button1) button1_OnClick();
    }

    public void button1_OnClick(){
        MessageBox.display("This is message box", "This is a non very important message for inform the user");
    }


}

package com.example.javafxtest;

import javafx.stage.*;
import javafx.scene.*;
import javafx.scene.layout.*;
import javafx.scene.control.*;
import javafx.geometry.*;


public class MessageBox {

    public static void display(String title, String message)
    {
        Stage window = new Stage();

        window.initModality(Modality.APPLICATION_MODAL);
        window.setTitle(title);
        window.setMinWidth(250);

        Label label = new Label();
        label.setText(message);
        Button closeButton = new Button("Close");
        closeButton.setOnAction(e -> window.close());

        VBox layout = new VBox(2);
        layout.getChildren().addAll(label,closeButton);
        layout.setAlignment(Pos.CENTER);

        Scene scene = new Scene(layout);
        window.setScene(scene);
        window.showAndWait();


    }
}

Take a return value from the window

We will create a separate window and we will take a return value from it.



public class HelloApplication extends Application implements EventHandler<ActionEvent> {

    public static void main(String[] args) {
        launch();
    }

    Stage window;
    Scene scene1;
    Button button1;

    @Override
    public void start(Stage stage) throws IOException {
        window = stage;

        Label label1 = new Label("This is our first window");
        button1 = new Button("Show the message box ;)");
        button1.setOnAction(this);

        VBox layout1 = new VBox(20);
        layout1.getChildren().addAll(label1,button1);

        scene1 = new Scene(layout1,300,300);

        window.setScene(scene1);
        window.setTitle("Scene Example");
        window.show();
    }

    // we implement EventHandler<ActionEvent>
    // with this function we can handle our buttons
    @Override
    public void handle(ActionEvent actionEvent) {
        if(actionEvent.getSource() == button1) button1_OnClick();
    }

    public void button1_OnClick(){
        boolean result = ConfirmBox.display("This is message box", "This is a non very important message for inform the user");
        System.out.println(result);
    }
}

public class ConfirmBox {
    static boolean answer;
    public static boolean display(String title, String message)
    {
        Stage window = new Stage();

        window.initModality(Modality.APPLICATION_MODAL);
        window.setTitle(title);
        window.setMinWidth(250);

        Label label = new Label();
        label.setText(message);


        Button yesButton = new Button("Yes");
        yesButton.setOnAction(e -> {
            answer = true;
            window.close();
        });

        Button noButton = new Button("No");
        noButton.setOnAction(e -> {
            answer = false;
            window.close();
        });

        HBox buttonLayout = new HBox(2);
        buttonLayout.getChildren().addAll(yesButton,noButton);
        buttonLayout.setAlignment(Pos.BASELINE_RIGHT);

        VBox layout = new VBox(2);
        layout.getChildren().addAll(label,buttonLayout);
        layout.setAlignment(Pos.CENTER);

        Scene scene = new Scene(layout);
        window.setScene(scene);
        window.showAndWait();

        return answer;
    }
}

Set on close request

        window = stage;
        window.setOnCloseRequest(e->{
            System.out.println("You press the X");
            window.close();
        });

https://stackoverflow.com/questions/12550548/what-does-e-consume-do-in-java

Grid layout

package com.example.javafxtest;

import javafx.application.Application;
import javafx.event.ActionEvent;
import javafx.event.EventHandler;
import javafx.stage.*;
import javafx.scene.*;
import javafx.scene.layout.*;
import javafx.scene.control.*;
import javafx.geometry.*;

import java.io.IOException;

public class HelloApplication extends Application implements EventHandler<ActionEvent> {

    public static void main(String[] args) {
        launch();
    }

    Stage window;
    //Scene scene1;
    Button button;

    @Override
    public void start(Stage stage) throws IOException {
        window =stage;
        window.setTitle("This is window");

        GridPane grid = new GridPane();
        grid.setPadding(new Insets(10,10,10,10));
        grid.setVgap(8); // gap between two rows
        grid.setHgap(10); // gap between two columns

        // we create the elements
        Label nameLabel = new Label("Username");
        TextField nameInput = new TextField("CrazyBoy66");
        Label passLabel = new Label("Password");
        TextField passInput = new TextField("****");
        button = new Button("Enter");
        button.setOnAction(e->{
            System.out.println(nameInput.getText());
            System.out.println(passInput.getText());
        });

        // we will set the position of the elements
        GridPane.setConstraints(nameLabel,0,0);
        GridPane.setConstraints(nameInput,1,0);
        GridPane.setConstraints(passLabel,0,1);
        GridPane.setConstraints(passInput,1,1);
        GridPane.setConstraints(button,1,2);
        // we add the elements to gridpane
        grid.getChildren().addAll(nameInput,nameLabel,passLabel,passInput,button);

        window.setScene(new Scene(grid,300,300));
        window.show();

    }

    // we already set button action for that reason below this line actually unnecessary
    @Override
    public void handle(ActionEvent actionEvent) {
        if(actionEvent.getSource() == button) button_OnClick();
    }

    public void button_OnClick(){
        boolean result = ConfirmBox.display("This is message box", "This is a non very important message for inform the user");
        System.out.println(result);
    }
}

Checkbox



public class HelloApplication extends Application{

    public static void main(String[] args) {
        launch();
    }

    @Override
    public void start(Stage stage) throws IOException {

        CheckBox cb1 = new CheckBox("option1");
        CheckBox cb2 = new CheckBox("option2");
        CheckBox cb3 = new CheckBox("option3");
        Button button = new Button("Click Me");

        button.setOnAction(e->{
            System.out.println("Selected list:");
            if(cb1.isSelected()) System.out.println("cb1 selected");
            if(cb2.isSelected()) System.out.println("cb2 selected");
            if(cb3.isSelected()) System.out.println("cb3 selected");
        });

        VBox layout = new VBox();
        layout.getChildren().addAll(cb1,cb2,cb3,button);

        stage.setTitle("This is window");
        stage.setScene(new Scene(layout,300,300));
        stage.show();

    }

}

Dropbox

public class HelloApplication extends Application{

    public static void main(String[] args) {
        launch();
    }

    @Override
    public void start(Stage stage) throws IOException {

        ChoiceBox<String> cb = new ChoiceBox<>();
        cb.getItems().addAll("Istanbul","Newyork","Paris");
        cb.setValue("Istanbul");

        Button button = new Button("Select");
        button.setOnAction(e->{
            String str = cb.getValue();
            System.out.println(str);
        });

        VBox layout = new VBox();
        layout.getChildren().addAll(cb,button);

        stage.setTitle("My window");
        stage.setScene(new Scene(layout,200,200));
        stage.show();

    }

}

Combobox




public class HelloApplication extends Application{

    public static void main(String[] args) {
        launch();
    }

    @Override
    public void start(Stage stage) throws IOException {

        ComboBox<String> cb = new ComboBox<String>();
        cb.getItems().addAll("Istanbul","Newyork","Paris");
        // this two lines are important
        cb.setPromptText("What is your favorite city");
        //cb.setEditable(true);

        Button button = new Button("Select");
        button.setOnAction(e->{
            String str = cb.getValue();
            System.out.println(str);
        });

        VBox layout = new VBox();
        layout.getChildren().addAll(cb,button);

        stage.setTitle("My window");
        stage.setScene(new Scene(layout,200,200));
        stage.show();

    }

}

ListView

It allows you to make multiple selections.



public class HelloApplication extends Application{

    public static void main(String[] args) {
        launch();
    }

    @Override
    public void start(Stage stage) throws IOException {

        ListView<String> cb = new ListView<String>();
        cb.getItems().addAll("Istanbul","Newyork","Paris");
        cb.getSelectionModel().setSelectionMode(SelectionMode.MULTIPLE);

        Button button = new Button("Select");
        button.setOnAction(e->{
            ObservableList<String> str = cb.getSelectionModel().getSelectedItems();
            for (String i : str)
                System.out.println(i);
        });

        VBox layout = new VBox();
        layout.getChildren().addAll(cb,button);

        stage.setTitle("My window");
        stage.setScene(new Scene(layout,200,200));
        stage.show();

    }

}

TreeView

package com.example.javafxtest;

import javafx.application.Application;
import javafx.collections.ObservableList;
import javafx.event.ActionEvent;
import javafx.event.EventHandler;
import javafx.stage.*;
import javafx.scene.*;
import javafx.scene.layout.*;
import javafx.scene.control.*;
import javafx.geometry.*;

import java.io.IOException;

public class HelloApplication extends Application{

    public static void main(String[] args) {
        launch();
    }

    @Override
    public void start(Stage stage) throws IOException {
        TreeView<String> tree = new TreeView<String>();

        TreeItem<String> root, bicycle, car;

        // Root
        root = new TreeItem<>();
        root.setExpanded(true);

        // Bucky
        bicycle = makeBranch("Bicycle brands", root);
        bicycle.setExpanded(false);
        makeBranch("giant", bicycle);
        makeBranch("carraro", bicycle);
        makeBranch("bianchi", bicycle);
        makeBranch("kron", bicycle);

        //Megan
        car = makeBranch("Car brands", root);
        makeBranch("ford", car);
        makeBranch("fiat", car);
        makeBranch("tesla", car);
        makeBranch("toyota", car);

        // Create tree
        tree = new TreeView<>(root);
        tree.setShowRoot(false); //hide root node
        tree.getSelectionModel().selectedItemProperty().addListener((v,oldValue,newValue)->{
            if(newValue != null) System.out.println(newValue.getValue());
        });

        stage.setTitle("My window");
        StackPane layout = new StackPane();
        layout.getChildren().add(tree);
        stage.setScene(new Scene(layout,400,400));
        stage.show();

    }
    public TreeItem<String> makeBranch(String name, TreeItem<String> parent){
        TreeItem<String> item = new TreeItem<>(name);
        item.setExpanded(true);
        parent.getChildren().add(item);
        return item;
    }

}

TableView

package com.example.javafxtest;

public class Product {
String name;
int price;
int quantity;

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public int getPrice() {
        return price;
    }

    public void setPrice(int price) {
        this.price = price;
    }

    public int getQuantity() {
        return quantity;
    }

    public void setQuantity(int quantity) {
        this.quantity = quantity;
    }

    public Product() {
        name = "NONE";
        price = 0;
        quantity = 0;
    }

    public Product(String name, int price, int quantity) {
        this.name = name;
        this.price = price;
        this.quantity = quantity;
    }
}
package com.example.javafxtest;

import javafx.application.Application;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.event.ActionEvent;
import javafx.event.EventHandler;
import javafx.scene.control.cell.PropertyValueFactory;
import javafx.stage.*;
import javafx.scene.*;
import javafx.scene.layout.*;
import javafx.scene.control.*;
import javafx.geometry.*;

import java.io.IOException;

public class HelloApplication extends Application{

    public static void main(String[] args) {
        launch();
    }

    TableView<Product> table;
    @Override
    public void start(Stage stage) throws IOException {

        // Name colmun
        TableColumn<Product, String> nameColumn = new TableColumn<>("Name");
        nameColumn.setMinWidth(200);
        nameColumn.setCellValueFactory(new PropertyValueFactory<>("name"));

        // Price colmun
        TableColumn<Product, String> priceColumn = new TableColumn<>("Money");
        priceColumn.setMinWidth(200);
        priceColumn.setCellValueFactory(new PropertyValueFactory<>("price"));

        // Quantity colmun
        TableColumn<Product, String> quantityColumn = new TableColumn<>("Count");
        quantityColumn.setMinWidth(200);
        quantityColumn.setCellValueFactory(new PropertyValueFactory<>("quantity"));


        table = new TableView<>();
        table.setItems(getProduct());
        table.getColumns().addAll(nameColumn,priceColumn,quantityColumn);

        table.getSelectionModel().setSelectionMode(SelectionMode.MULTIPLE);

        Button addButton = new Button("Add");
        Button deleteButton = new Button("Delete");
        addButton.setOnAction(e->addElem());
        deleteButton.setOnAction(e->deleteElem());

        stage.setTitle("My window");
        VBox layout = new VBox();
        layout.getChildren().addAll(table,addButton,deleteButton);
        stage.setScene(new Scene(layout,600,300));
        stage.show();

    }

    public void addElem(){
        Product product = new Product("New product", 10,1);
        table.getItems().add(product);
    }
    public void deleteElem(){
        // delete first elem
        ObservableList<Product> productSelected, allProducts;
        allProducts = table.getItems();
        productSelected = table.getSelectionModel().getSelectedItems();

        productSelected.forEach(allProducts::remove);
    }

    // Get all of the products
    public ObservableList<Product> getProduct(){
        ObservableList<Product> products = FXCollections.observableArrayList();
        products.add(new Product("Laptop",1000,20));
        products.add(new Product("Super Laptop",1700,10));
        products.add(new Product("Desktop",1200,10));
        products.add(new Product("TV",100,24));
        products.add(new Product("DVD",10,200));

        return products;
    }

}

Menu

package com.example.javafxtest;

import javafx.application.Application;
import javafx.collections.ObservableList;
import javafx.event.ActionEvent;
import javafx.event.EventHandler;
import javafx.stage.*;
import javafx.scene.*;
import javafx.scene.layout.*;
import javafx.scene.control.*;
import javafx.geometry.*;

import java.io.IOException;
import java.io.SerializablePermission;

public class HelloApplication extends Application{

    public static void main(String[] args) {
        launch();
    }

    Stage window;
    BorderPane layout;

    @Override
    public void start(Stage stage) throws IOException {
        window = stage;
        window.setTitle("Menu Example");

        // File Menu
        Menu fileMenu = new Menu("_File"); // _mnemonic

        // Menu items
        MenuItem newFile = new MenuItem("New");
        newFile.setDisable(true);
        newFile.setOnAction(e->System.out.println("Hallo there!"));
        fileMenu.getItems().add(newFile);
        //fileMenu.getItems().add(new MenuItem("New"));
        fileMenu.getItems().add(new MenuItem("Save"));
        fileMenu.getItems().add(new MenuItem("Open"));
        fileMenu.getItems().add(new SeparatorMenuItem());
        fileMenu.getItems().add(new MenuItem("Save"));
        fileMenu.getItems().add(new MenuItem("Open"));

        // Main menu bar
        MenuBar menuBar = new MenuBar();
        menuBar.getMenus().add(fileMenu);


        layout = new BorderPane();
        layout.setTop(menuBar);
        Scene scene = new Scene(layout, 500, 300);
        window.setScene(scene);
        window.show();

    }


}


Comments

Leave a Reply

Your email address will not be published. Required fields are marked *