How to create a choice box using JavaFX?

JavaFXObject Oriented ProgrammingProgramming

A choice box holds a small set of multiple choices and, allows you to select only one of them. This will have two states showing and not showing. When showing, you can see the list of choices in a choice box and while not showing, it displays the current choice. By default, no option is selected in a choice box.

In JavaFX a choice box is represented by the class javafx.scene.control.ChoiceBox<T>. You can create a choice box by instantiating this class.

This class has a property named items, it is of the type ObservableList<T> and it holds the list of choices to display in the choice box. You can retrieve this list using the getItems() method.

After instantiating the ChoiceBox class, you need to get the observable list and add all the required choices to it using the add() or addAll() method.

Example

import javafx.application.Application;
import javafx.collections.ObservableList;
import javafx.scene.Group;
import javafx.scene.Scene;
import javafx.scene.control.ChoiceBox;
import javafx.scene.control.Label;
import javafx.scene.paint.Color;
import javafx.scene.text.Font;
import javafx.scene.text.FontPosture;
import javafx.scene.text.FontWeight;
import javafx.stage.Stage;
public class ChoiceBoxExample extends Application {
   public void start(Stage stage) {
      //Creating a choice box
      ChoiceBox<String> choiceBox = new ChoiceBox<String>();
      choiceBox.setValue("English");
      //Retrieving the observable list
      ObservableList<String> list = choiceBox.getItems();
      //Adding items to the list
      list.add("English");
      list.add("Hindi");
      list.add("Telugu");
      list.add("Tamil");
      //Setting the position of the choice box
      choiceBox.setTranslateX(200);
      choiceBox.setTranslateY(15);
      //Setting the label
      Label label = new Label("Select Display Language:");
      Font font = Font.font("verdana", FontWeight.BOLD, FontPosture.REGULAR, 12);
      label.setFont(font);
      label.setTranslateX(20);
      label.setTranslateY(20);
      //Adding the choice box to the group
      Group root = new Group(choiceBox, label);
      //Setting the stage
      Scene scene = new Scene(root, 595, 170, Color.BEIGE);
      stage.setTitle("Choice Box Example");
      stage.setScene(scene);
      stage.show();
   }
   public static void main(String args[]){
      launch(args);
   }
}

Output

raja
Published on 18-May-2020 09:58:31
Advertisements