Sunday, June 2, 2013

JavaFX ComboBox for custom object

The post "Simple example of JavaFX ComboBox" with elements of String. This post demonstrate how to implement ComboBox for custom object, we have to override toString() method of the custom class to display text on the box, and also call setCellFactory() to supply Callback to display text on the drop-down ListView.

JavaFX ComboBox for custom object
JavaFX ComboBox for custom object

package javafxcombobox;

import javafx.application.Application;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.event.ActionEvent;
import javafx.event.EventHandler;
import javafx.geometry.Insets;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.control.ComboBox;
import javafx.scene.control.Label;
import javafx.scene.control.ListCell;
import javafx.scene.control.ListView;
import javafx.scene.layout.StackPane;
import javafx.scene.layout.VBox;
import javafx.stage.Stage;
import javafx.util.Callback;

 * @web
public class JavaFXComboBox extends Application {
    class Site{
        String name;
        String webaddr;
        Site(String n, String a){
            name = n;
            webaddr = a;

        public String toString() {
            return name;

    ObservableList<Site> siteList = 
                new Site("Google", ""),
                new Site("MicroSoft", ""),
                new Site("Apple", ""),
                new Site("Java-Buddy", "")

    public void start(Stage primaryStage) {
        final ComboBox comboBox = new ComboBox(siteList);
        comboBox.getSelectionModel().selectFirst(); //select the first element
        comboBox.setCellFactory(new Callback<ListView<Site>,ListCell<Site>>(){

            public ListCell<Site> call(ListView<Site> p) {
                final ListCell<Site> cell = new ListCell<Site>(){

                    protected void updateItem(Site t, boolean bln) {
                        super.updateItem(t, bln);
                        if(t != null){
                            setText( + ":" + t.webaddr);
                return cell;
        final Label label = new Label();
        Button btn = new Button();
        btn.setText("Read comboBox");
        btn.setOnAction(new EventHandler<ActionEvent>() {
            public void handle(ActionEvent event) {
                label.setText("selected: " + comboBox.getValue());

        VBox vBox = new VBox();
        vBox.setPadding(new Insets(5, 5, 5, 5));
        vBox.getChildren().addAll(label, comboBox, btn);
        StackPane root = new StackPane();
        Scene scene = new Scene(root, 300, 250);
        primaryStage.setTitle("Hello World!");

    public static void main(String[] args) {

1 comment: