Tuesday, 1 December 2020

JavaFX: ComboBox

Using ComboBox, a popup list is shown to users providing them with a choice that they may select from.

 

ComboBox class provides following constructors to get an instance of ComboBox.

 

public ComboBox()

Creates a default ComboBox instance with an empty items.

 

public ComboBox(ObservableList<T> items)

Creates a default ComboBox instance with the provided items list.

 

How to add items to a ComboBox?

comboBox.getItems().addAll("Cricket", "Trekking", "Blogging", "Chess");

 

How to set the selection model?

comboBox.getSelectionModel().selectFirst();

 

How to make a ComboBox editable?

comboBox.setEditable(true);

 

How to set visible row count of items in ComboBox?

comboBox.setVisibleRowCount(3);

 

Find the below working application.

 

ComboBoxDemo.java 

package com.sample.app.widgets;

import javafx.application.Application;
import javafx.beans.binding.ObjectBinding;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.geometry.Insets;
import javafx.scene.Scene;
import javafx.scene.control.ComboBox;
import javafx.scene.control.Label;
import javafx.scene.effect.DropShadow;
import javafx.scene.layout.HBox;
import javafx.scene.layout.VBox;
import javafx.scene.paint.Color;
import javafx.scene.text.Font;
import javafx.scene.text.FontPosture;
import javafx.stage.Stage;

public class ComboBoxDemo extends Application {

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

	}

	@Override
	public void start(Stage primaryStage) throws Exception {

		DropShadow dropShadow = new DropShadow();
		dropShadow.setOffsetX(5);
		dropShadow.setOffsetY(5);
		dropShadow.setColor(Color.GRAY);

		ObservableList<Object> observableList = FXCollections.observableArrayList("Cricket", "Trekking", "Blogging",
				"Chess");

		HBox hBox1 = new HBox();
		Label label1 = new Label("Please select your hobby");
		label1.setFont(Font.font("Verdana", FontPosture.REGULAR, 30));
		hBox1.getChildren().add(label1);
		hBox1.setPadding(new Insets(20, 20, 20, 20));

		Label selectedHobbies = new Label("");
		selectedHobbies.setFont(Font.font("Verdana", FontPosture.REGULAR, 30));
		selectedHobbies.setTextFill(Color.BLUE);
		selectedHobbies.setWrapText(true);
		selectedHobbies.setEffect(dropShadow);

		ComboBox<String> comboBox = new ComboBox<>();
		comboBox.getItems().addAll("Cricket", "Trekking", "Blogging", "Chess");
		comboBox.getSelectionModel().selectFirst();
		comboBox.setEditable(true);
		comboBox.setVisibleRowCount(3);

		ObjectBinding<String> labelBinding = new ObjectBinding<String>() {

			{
				super.bind(comboBox.valueProperty());
			}

			@Override
			protected String computeValue() {
				String newValue = comboBox.getValue();

				if (newValue != null && !comboBox.getItems().contains(newValue)) {
					comboBox.getItems().add(newValue);
				}

				if (newValue != null) {
					return "Your hobby is : " + newValue;
				}
				
				return "Please choose tour hobby";

			}

		};

		selectedHobbies.textProperty().bind(labelBinding);

		HBox hBox2 = new HBox();
		hBox2.setSpacing(10);
		hBox2.setPadding(new Insets(20, 20, 20, 20));
		hBox2.getChildren().addAll(comboBox);

		HBox hBox3 = new HBox();
		hBox3.setSpacing(10);
		hBox3.setPadding(new Insets(20, 20, 20, 20));
		hBox3.getChildren().addAll(selectedHobbies);

		VBox vBox = new VBox();
		vBox.getChildren().addAll(hBox1, hBox2, hBox3);
		vBox.setEffect(dropShadow);
		vBox.setStyle("-fx-background-color:white");

		Scene scene = new Scene(vBox, 500, 500, Color.WHITE);

		primaryStage.setTitle("ComboBox Demo");
		primaryStage.setScene(scene);
		primaryStage.show();
	}

}

 

Output

 


 Select the hobby from the drop down.


You can even add new hobbies to combo box.


 


Previous                                                    Next                                                    Home

JavaFX: ChoiceBox

ChoiceBox class defines a choice box control. Using choice box control, you can define list of predefined choices from which user may select.

 

Can a user select the item something other than the predefined list?

Yes, it is possible for the developer to specify the selected item to be something other than what is available in the predefined list.

 

ChoiceBox class provides following constructors to define an instance of ChoiceBox.

 

public ChoiceBox()

Create a new ChoiceBox which has an empty list of items.

 

public ChoiceBox(ObservableList<T> items)

Create a new ChoiceBox with the given set of items. Since it is observable, the content of this list may change over time and the ChoiceBox will be updated accordingly.

 

Find the below working application.

 

ChoiceBoxDemo.java 

package com.sample.app.widgets;

import javafx.application.Application;
import javafx.beans.value.ObservableValue;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.geometry.Insets;
import javafx.scene.Scene;
import javafx.scene.control.ChoiceBox;
import javafx.scene.control.Label;
import javafx.scene.effect.DropShadow;
import javafx.scene.layout.HBox;
import javafx.scene.layout.VBox;
import javafx.scene.paint.Color;
import javafx.scene.text.Font;
import javafx.scene.text.FontPosture;
import javafx.stage.Stage;

public class ChoiceBoxDemo extends Application {

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

	}

	@Override
	public void start(Stage primaryStage) throws Exception {
		
		DropShadow dropShadow = new DropShadow();
		dropShadow.setOffsetX(5);
		dropShadow.setOffsetY(5);
		dropShadow.setColor(Color.GRAY);

		ObservableList<Object> observableList = FXCollections.observableArrayList("Cricket", "Trekking", "Blogging",
				"Chess");

		HBox hBox1 = new HBox();
		Label label1 = new Label("Please select your hobby");
		label1.setFont(Font.font("Verdana", FontPosture.REGULAR, 30));
		hBox1.getChildren().add(label1);
		hBox1.setPadding(new Insets(20, 20, 20, 20));

		Label selectedHobbies = new Label("");
		selectedHobbies.setFont(Font.font("Verdana", FontPosture.REGULAR, 30));
		selectedHobbies.setTextFill(Color.BLUE);
		selectedHobbies.setWrapText(true);
		selectedHobbies.setEffect(dropShadow);

		ChoiceBox<String> choiceBox = new ChoiceBox<>();
		choiceBox.getItems().addAll("Cricket", "Trekking", "Blogging", "Chess");
		choiceBox.getSelectionModel().selectFirst();

		choiceBox.getSelectionModel().selectedIndexProperty()
				.addListener((ObservableValue<? extends Number> observable, Number oldValue, Number newValue) -> {
					String result = null;
					if ((int) oldValue == -1) {
						result = "Selection changed form none to " + observableList.get((int) newValue);
						selectedHobbies.setText(result);
					} else {
						result = "Selection changed form " + observableList.get((int) oldValue) + " to "
								+ observableList.get((int) newValue);
						selectedHobbies.setText(result);
					}

				});

		HBox hBox2 = new HBox();
		hBox2.setSpacing(10);
		hBox2.setPadding(new Insets(20, 20, 20, 20));
		hBox2.getChildren().addAll(choiceBox);

		HBox hBox3 = new HBox();
		hBox3.setSpacing(10);
		hBox3.setPadding(new Insets(20, 20, 20, 20));
		hBox3.getChildren().addAll(selectedHobbies);

		VBox vBox = new VBox();
		vBox.getChildren().addAll(hBox1, hBox2, hBox3);
		vBox.setEffect(dropShadow);
		vBox.setStyle("-fx-background-color:white");

		Scene scene = new Scene(vBox, 500, 500, Color.WHITE);

		primaryStage.setTitle("Button Demo 1");
		primaryStage.setScene(scene);
		primaryStage.show();
	}

}

 

Output

 


Select your hobby and you can observe the same is reflected in bottom of the window.

 


 

Previous                                                    Next                                                    Home

JavaFX: CheckBox

 

CheckBox is used to define check box control.

 

CheckBox states

CheckBox control has three states.

a.   Checked: Indeterminate property is false and selected property is true.

b.   Unchecked: Indeterminate property is false and selected property is false.

c.    Undefined: Indeterminate property is true. Undefined or indeterminate state of the CheckBox is rendered with a minus or dash sign.

 

CheckBox class provides following  constructors to define CheckBox instance.

 

public CheckBox()

public CheckBox(String text)

'text' specifies a text string for its label.

 

Find the below working application.

 

checkBoxDemo.fxml

<?import javafx.scene.*?>
<?import javafx.scene.shape.*?>
<?import javafx.scene.layout.*?>
<?import javafx.scene.text.*?>
<?import javafx.scene.effect.*?>
<?import javafx.scene.control.*?>

<VBox xmlns:fx="http://javafx.com/fxml" fx:controller="com.sample.app.widgets.controller.CheckBoxController"
    fx:id="vBox1" spacing="20" alignment="center">
    
    <HBox fx:id="lableHBox"> 
        <Label fx:id="title" text="Select the vegetables" wrapText="true"/>
    </HBox>
    
    <HBox fx:id="vegetableChooserHBox">
        <VBox>
            <CheckBox fx:id="broccoli" text="broccoli"/>
            <CheckBox fx:id="corn" text="corn"/>
            <CheckBox fx:id="cucumber" text="cucumber"/>
        </VBox>
        
        <VBox>
            <CheckBox fx:id="lettuce" text="lettuce"/>
            <CheckBox fx:id="pumpkin" text="pumpkin"/>
            <CheckBox fx:id="pumpkin" text="pumpkin"/>
        </VBox>
        
        <VBox>
            <CheckBox fx:id="beetroot" text="beetroot"/>
            <CheckBox fx:id="sprouts" text="sprouts"/>
            <CheckBox fx:id="carrot" text="carrot"/>
        </VBox>
    </HBox>
    
    <HBox fx:id="lableHBox"> 
        <Label fx:id="selectedVegetables" text="" wrapText="true"/>
    </HBox>
    
    
</VBox>

 

CheckBoxController.java

package com.sample.app.widgets.controller;

import java.net.URL;
import java.util.*;

import javafx.fxml.FXML;
import javafx.fxml.Initializable;
import javafx.geometry.Insets;
import javafx.scene.Node;
import javafx.scene.control.Label;
import javafx.scene.control.CheckBox;
import javafx.scene.effect.DropShadow;
import javafx.scene.layout.HBox;
import javafx.scene.layout.VBox;
import javafx.scene.paint.Color;
import javafx.scene.text.Font;
import javafx.scene.text.FontPosture;

public class CheckBoxController implements Initializable {

    @FXML
    private VBox vBox1;

    @FXML
    private HBox vegetableChooserHBox;

    @FXML
    private Label selectedVegetables;

    @FXML
    private Label title;

    @Override
    public void initialize(URL location, ResourceBundle resources) {

        DropShadow dropShadow = new DropShadow();
        dropShadow.setOffsetX(5);
        dropShadow.setOffsetY(5);
        dropShadow.setColor(Color.GRAY);

        vBox1.setEffect(dropShadow);
        vBox1.setStyle("-fx-background-color:lightyellow");

        vegetableChooserHBox.setSpacing(10);
        vegetableChooserHBox.setPadding(new Insets(20, 20, 20, 80));

        Font font = Font.font("Verdana", FontPosture.REGULAR, 25);

        Iterator<Node> nodes = vegetableChooserHBox.getChildren().iterator();
        vegetableChooserHBox.setSpacing(10);
        List<CheckBox> checkBoxes = new ArrayList<>();

        while (nodes.hasNext()) {
            VBox vBox = (VBox) nodes.next();
            vBox.setSpacing(10);

            Iterator<Node> vBoxNodes = vBox.getChildren().iterator();

            while (vBoxNodes.hasNext()) {
                Node node = vBoxNodes.next();
                if (node instanceof CheckBox) {
                    CheckBox checkBox = (CheckBox) node;
                    checkBoxes.add(checkBox);

                    checkBox.setFont(font);

                    checkBox.setOnAction((event) -> {
                        StringJoiner stringJoiner = new StringJoiner(",");

                        for (CheckBox checkBoxTemp : checkBoxes) {
                            if (checkBoxTemp.isSelected()) {
                                stringJoiner.add(checkBoxTemp.getText());
                            }
                        }

                        String info = "Selected items are : " + stringJoiner.toString();
                        selectedVegetables.setText(info);

                    });

                }
            }

        }

        title.setFont(Font.font("Verdana", FontPosture.REGULAR, 50));
        title.setPadding(new Insets(20, 20, 20, 20));

        selectedVegetables.setFont(Font.font("Verdana", FontPosture.ITALIC, 25));
        selectedVegetables.setTextFill(Color.BLUE);
        selectedVegetables.setPadding(new Insets(20, 20, 20, 20));

    }
}

 

CheckBoxDemo.java

package com.sample.app.widgets;

import javafx.application.Application;
import javafx.fxml.FXMLLoader;
import javafx.scene.Parent;
import javafx.scene.Scene;
import javafx.scene.paint.Color;
import javafx.stage.Stage;

public class CheckBoxDemo extends Application {

    private static final String FXML_FILE = "/checkBoxDemo.fxml";
    private static final String STAGE_TITLE = "CheckBox Demo";

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

    }

    @Override
    public void start(Stage primaryStage) throws Exception {

        Parent root = (Parent) FXMLLoader.load(this.getClass().getResource(FXML_FILE));

        Scene scene = new Scene(root, 700, 600, Color.WHITE);

        primaryStage.setTitle(STAGE_TITLE);
        primaryStage.setScene(scene);
        primaryStage.show();

    }

}

 

Output

 



 
Select vegetables, you can see the selected items information in below of the window.

 


 

Previous                                                    Next                                                    Home

JavaFX: Properties

JavaFX Property wraps a field value and its observable. So whoever want to listen to the property change, they can register to the observable. Registered listeners will get notified when a property gets updated.

 

Let’s see it with an example.

 

Employee.java

package com.sample.app.model;

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

public class Employee {

    private StringProperty firstName = new SimpleStringProperty();

    public final String getFirstName() {
        return firstName.get();
    }

    public final void setFirstName(String firstName) {
        this.firstName.set(firstName);
    }

    public StringProperty firstNameProperty() {
        return firstName;
    }

}

 

As you see above definition, Employee class has firstName property.

 

Property naming conventions

The getFirstName() method is a standard getter that returns the current value of the firstName property. By convention, this method is declared as final. Note that the return type for this method is String, not StringProperty.

 

The setFirstName(String firstName) method (also final) is a standard setter that allows a caller to set the property's value. The setter method is optional. Its parameter is also of type String.

 

Finally, the firstNameProperty() method defines the property getter. This is a new convention in which the method name contains the name of the property (firstName, in this case), followed by the word "Property." The return type is the same as the property itself (StringProperty, in this example).

 

How to listen on employee firstName property change?

Add change listener.

 

emp.firstNameProperty().addListener(new ChangeListener<String>() {

 

    @Override

    public void changed(ObservableValue<? extends String> observable, String oldValue, String newValue) {

        System.out.println("Employee firstName changed from " + oldValue + " -> " + newValue);

    }

 

});

 

Find the below working application.

 

PropertyDemo.java

package com.sample.app;

import com.sample.app.model.Employee;

import javafx.beans.value.ChangeListener;
import javafx.beans.value.ObservableValue;

public class PropertyDemo {

    public static void main(String args[]) {
        Employee emp = new Employee();

        emp.firstNameProperty().addListener(new ChangeListener<String>() {

            @Override
            public void changed(ObservableValue<? extends String> observable, String oldValue, String newValue) {
                System.out.println("Employee firstName changed from " + oldValue + " -> " + newValue);
            }

        });

        emp.setFirstName("Krishna");
        emp.setFirstName("Ram");
        emp.setFirstName("Gopi");

    }

}

 

Output

Employee firstName changed from null -> Krishna

Employee firstName changed from Krishna -> Ram

Employee firstName changed from Ram -> Gopi

 

 

Previous                                                    Next                                                    Home