JavaFX ComboBox

0

JavaFX ComboBox tutorial:

javaFX ComboBox UI control allows users to select one of several options from a drop-down list.

Constructors:

  • ComboBox()
    Creates a default ComboBox instance with an empty items list.
  • ComboBox(ObservableList items)
    Creates a default ComboBox instance with the provided items list.

Creating ComboBox :

    • creating list for adding to ComboBox AS

ObservableList list1 =
FXCollections.observableArrayList(
"fname",
"lname",
"UID"
);

  • ComboBox cb = new ComboBox(list1);
  • And you can also use cb.getItems().addAll(); to add list items as in example.

Example using combo box:


package javafxtuts;
import javafx.application.Application;
import javafx.scene.Scene;
import javafx.scene.control.ComboBox;
import javafx.scene.layout.FlowPane;
import javafx.stage.Stage;

public class Javafxtuts extends Application {

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

  @Override
  public void start(Stage stage) {
      stage.setTitle("Javafxtuts.com");
      
      ComboBox cb = new ComboBox();
      cb.getItems().addAll("a","s","d","f");
      cb.setValue("a");
      FlowPane root =new FlowPane();
      root.getChildren().add(cb);
        Scene scene = new Scene(root, 250, 300);
        stage.setScene(scene);
        stage.show();
  }
}

Output :

Explanation of combo box example :

  • Creating Combo BOx cb

    ComboBox cb = new ComboBox();
  • To add items to the cb we do AS

    cb.getItems().addAll("a","s","d","f");
  • To set default value of cb we use setValue() method AS

    cb.setValue("a");
Share.

Leave A Reply