JavaFX Tutorial - JavaFX ComboBox








A combo box allows users to choose one of several options. Users can scroll to the drop down list. The combobox can be editable and uneditable.

Creating Combo Boxes

The following code wraps the option list into ObservableList then instantiates the ComboBox class with observable list.

ObservableList<String> options = 
    FXCollections.observableArrayList(
        "1",
        "2",
        "3"
    );
ComboBox comboBox = new ComboBox(options);

We can also create a combo box by using an empty constructor and call its setItems method to set the data.

ComboBox comboBox = new ComboBox(options);
comboBox.setItems(options);

To add more items to the combobox of items with new values.

comboBox.getItems().addAll(
    "4",
    "5",
    "6"
);

setValue method sets the item selected in the combo box. When calling the setValue method, the selected item of the selectionModel property changes to this value even if the value is not in the combo box items list.

getValue method returns the selected value.

To restrict the number of visible rows in the drop down list, use the following code.

comboBox.setVisibleRowCount(3) 




Editable Combo Boxes

setEditable(true) method makes a combo box editable. With the setPromptText method, we can specify the text to appear in the combo box editing area when no selection is performed.

ComboBox myComboBox = new ComboBox();
myComboBox.getItems().addAll(
            "s@example.com",
            "i@example.com",
            "e@example.com",
            "m@example.com"  
);
myComboBox.setPromptText("Email address");
myComboBox.setEditable(true);        
myComboBox.setOnAction((Event ev) -> {
    address =  myComboBox.getSelectionModel().getSelectedItem().toString();    
});
myComboBox.setValue("s@example.com");        

The following code creates a simple editable ComboBox

import javafx.application.Application;
import javafx.scene.Group;
import javafx.scene.Scene;
import javafx.scene.control.ComboBox;
import javafx.stage.Stage;
/*from   w  ww  .  j  a  v  a  2 s  . c o m*/
public class Main extends Application {
  public static void main(String[] args) {
    launch(args);
  }

  @Override
  public void start(Stage stage) {
    Scene scene = new Scene(new Group(), 450, 250);

    ComboBox<String> myComboBox = new ComboBox<String>();
    myComboBox.getItems().addAll("A","B","C","D","E");
    myComboBox.setEditable(true);        
    
    Group root = (Group) scene.getRoot();
    root.getChildren().add(myComboBox);
    stage.setScene(scene);
    stage.show();

  }
}

The code above generates the following result.

null




ComboBox Cell

We can use the cell factory to alter the default behavior or appearance of a combo box.

The following code creates a cell factory and applies it to the combo box.

The cell factory produces ListCell objects. Every cell is associated with a single combo box item.

import javafx.application.Application;
import javafx.scene.Group;
import javafx.scene.Scene;
import javafx.scene.control.ComboBox;
import javafx.scene.control.ListCell;
import javafx.scene.control.ListView;
import javafx.scene.paint.Color;
import javafx.stage.Stage;
import javafx.util.Callback;
// w w w . jav a2  s .c o  m
public class Main extends Application {
  public static void main(String[] args) {
    launch(args);
  }
  @Override
  public void start(Stage stage) {
    Scene scene = new Scene(new Group(), 200, 200);
    ComboBox<String> myComboBox = new ComboBox<String>();
    myComboBox.getItems().addAll("A", "B", "C", "D", "E");
    myComboBox
        .setCellFactory(new Callback<ListView<String>, ListCell<String>>() {
          @Override
          public ListCell<String> call(ListView<String> param) {
            final ListCell<String> cell = new ListCell<String>() {
              {
                super.setPrefWidth(100);
              }

              @Override
              public void updateItem(String item, boolean empty) {
                super.updateItem(item, empty);
                if (item != null) {
                  setText(item);
                  if (item.contains("A")) {
                    setTextFill(Color.RED);
                  } else if (item.contains("B")) {
                    setTextFill(Color.GREEN);
                  } else {
                    setTextFill(Color.BLACK);
                  }
                } else {
                  setText(null);
                }
              }
            };
            return cell;
          }
        });
    Group root = (Group) scene.getRoot();
    root.getChildren().add(myComboBox);
    stage.setScene(scene);
    stage.show();
  }
}

The code above generates the following result.

null

Example

Set value to null to clear the ComboBox

import javafx.application.Application;
import javafx.scene.Group;
import javafx.scene.Scene;
import javafx.scene.control.ComboBox;
import javafx.stage.Stage;
/* w w  w.  j  a  v a  2s  .c  om*/
public class Main extends Application {
  public static void main(String[] args) {
    launch(args);
  }
  @Override
  public void start(Stage stage) {
    Scene scene = new Scene(new Group(), 450, 250);
    ComboBox<String> myComboBox = new ComboBox<String>();
    myComboBox.getItems().addAll("A","B","C","D","E");
    myComboBox.setValue("A");
    System.out.println(myComboBox.getValue());
    
    myComboBox.setValue(null);
    
    Group root = (Group) scene.getRoot();
    root.getChildren().add(myComboBox);
    stage.setScene(scene);
    stage.show();
  }
}

The code above generates the following result.

null

Example 2

Set and get value for ComboBox

import javafx.application.Application;
import javafx.scene.Group;
import javafx.scene.Scene;
import javafx.scene.control.ComboBox;
import javafx.stage.Stage;
/*from  w w w  . j  av a2s  .  c  o m*/
public class Main extends Application {
  public static void main(String[] args) {
    launch(args);
  }
  @Override
  public void start(Stage stage) {
    Scene scene = new Scene(new Group(), 450, 250);
    ComboBox<String> myComboBox = new ComboBox<String>();
    myComboBox.getItems().addAll("A","B","C","D","E");
    myComboBox.setValue("A");
    System.out.println(myComboBox.getValue());
    
    
    Group root = (Group) scene.getRoot();
    root.getChildren().add(myComboBox);
    stage.setScene(scene);
    stage.show();
  }
}

The code above generates the following result.

null

Example 3

Add change listener to ComboBox valueProperty

import javafx.application.Application;
import javafx.beans.value.ChangeListener;
import javafx.beans.value.ObservableValue;
import javafx.scene.Group;
import javafx.scene.Scene;
import javafx.scene.control.ComboBox;
import javafx.stage.Stage;
/*w w w  .  ja v  a 2 s. c o m*/
public class Main extends Application {
  public static void main(String[] args) {
    launch(args);
  }
  @Override
  public void start(Stage stage) {
    Scene scene = new Scene(new Group(), 450, 250);
    ComboBox<String> myComboBox = new ComboBox<String>();
    myComboBox.getItems().addAll("A","B","C","D","E");
    myComboBox.setValue("A");
    System.out.println(myComboBox.getValue());
    myComboBox.valueProperty().addListener(new ChangeListener<String>() {
      @Override public void changed(ObservableValue ov, String t, String t1) {
        System.out.println(ov);
          System.out.println(t);
          System.out.println(t1);
      }    
  });
    
    Group root = (Group) scene.getRoot();
    root.getChildren().add(myComboBox);
    stage.setScene(scene);
    stage.show();
  }
}

The code above generates the following result.

null

Example 4

import javafx.application.Application;
import javafx.scene.Group;
import javafx.scene.Scene;
import javafx.scene.control.ComboBox;
import javafx.stage.Stage;
/*from  w  ww.j ava 2s  . c  o m*/
public class Main extends Application {
  public static void main(String[] args) {
    launch(args);
  }
  @Override
  public void start(Stage stage) {
    Scene scene = new Scene(new Group(), 450, 250);
    ComboBox<String> myComboBox = new ComboBox<String>();
    myComboBox.getItems().addAll("A","B","C","D","E");
    myComboBox.setEditable(true);
    myComboBox.setPromptText("Email address");
    
    Group root = (Group) scene.getRoot();
    root.getChildren().add(myComboBox);
    stage.setScene(scene);
    stage.show();
  }
}

The code above generates the following result.

null

Example 5

Display Rectangles in a ComboBox

import javafx.application.Application;
import javafx.scene.Group;
import javafx.scene.Scene;
import javafx.scene.control.ComboBox;
import javafx.scene.layout.GridPane;
import javafx.scene.paint.Color;
import javafx.scene.shape.Rectangle;
import javafx.stage.Stage;
//from   w  w w  .ja  v  a 2  s  . c  om
public class Main extends Application {
    public static void main(String[] args) {
        Application.launch(args);
    }
    @Override
    public void start(final Stage primaryStage) {
        Group root = new Group();
        Scene scene = new Scene(root, 400, 300, Color.WHITE);

        GridPane gridpane = new GridPane();

        ComboBox<Rectangle> cmb = new ComboBox<Rectangle>();
        cmb.getItems().addAll(
            new Rectangle(10, 10, Color.RED), 
            new Rectangle(10, 10, Color.GREEN), 
            new Rectangle(10, 10, Color.BLUE));
        
        gridpane.add(cmb, 2, 0);
        
        root.getChildren().add(gridpane);   
        primaryStage.setScene(scene);

        primaryStage.show();
    }

}

The code above generates the following result.

null

Example 6

The following code shows how to display the combobox value with CellFactory.

//Revised from javafx api document
import javafx.application.Application;
import javafx.scene.Group;
import javafx.scene.Scene;
import javafx.scene.control.ComboBox;
import javafx.scene.control.ContentDisplay;
import javafx.scene.control.ListCell;
import javafx.scene.control.ListView;
import javafx.scene.layout.GridPane;
import javafx.scene.paint.Color;
import javafx.scene.shape.Rectangle;
import javafx.stage.Stage;
import javafx.util.Callback;
//w w  w . j av  a2  s .co  m
public class Main extends Application {
  public static void main(String[] args) {
    Application.launch(args);
  }

  @Override
  public void start(final Stage primaryStage) {
    Group root = new Group();
    Scene scene = new Scene(root, 400, 300, Color.WHITE);
    GridPane gridpane = new GridPane();
    ComboBox<Color> cmb = new ComboBox<Color>();
    cmb.getItems().addAll(Color.RED, Color.GREEN, Color.BLUE);
    cmb.setCellFactory(new Callback<ListView<Color>, ListCell<Color>>() {
      @Override
      public ListCell<Color> call(ListView<Color> p) {
        return new ListCell<Color>() {
          private final Rectangle rectangle;
          {
            setContentDisplay(ContentDisplay.GRAPHIC_ONLY);
            rectangle = new Rectangle(10, 10);
          }

          @Override
          protected void updateItem(Color item, boolean empty) {
            super.updateItem(item, empty);

            if (item == null || empty) {
              setGraphic(null);
            } else {
              rectangle.setFill(item);
              setGraphic(rectangle);
            }
          }
        };
      }
    });

    gridpane.add(cmb, 2, 0);

    root.getChildren().add(gridpane);
    primaryStage.setScene(scene);

    primaryStage.show();
  }

}

The code above generates the following result.

null