Friday 15 June 2018

JavaFX: ListView: Populate listview data using ComboBoxListCell

By using ComboBoxListCell, you can draw a combo box inside the list cell. Whenever user clicks on list cell, you can display list of options using ComboBoxListCell.

Ex
ObservableList<String> countries = FXCollections.observableArrayList();
countries.addAll("India", "Australia", "Bahrain", "Bangladesh", "Cambodia", "Connie", "Chile", "France", "Hong Kong", "Iran");
listView.setCellFactory(ComboBoxListCell.forListView(countries));

Find the below working application.

ListViewApp.java
package com.sample.demos;

import javafx.application.Application;
import javafx.beans.value.ObservableValue;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.scene.Scene;
import javafx.scene.control.Label;
import javafx.scene.control.ListView;
import javafx.scene.control.cell.ComboBoxListCell;
import javafx.scene.layout.HBox;
import javafx.scene.paint.Color;
import javafx.scene.text.Font;
import javafx.stage.Stage;

public class ListViewApp extends Application {
 public static final ObservableList<String> countries = FXCollections.observableArrayList();
 public static final ObservableList<String> dataToBePopulated = FXCollections.observableArrayList();


 @Override
 public void start(Stage primaryStage) {
  Label label = new Label();
  label.setTextFill(Color.RED);
  label.setFont(new Font("Cambria", 20));

  for (int i = 0; i < 5; i++) {
   dataToBePopulated.add("Country " + (i + 1));
  }

  final ListView<String> listView = new ListView<>(dataToBePopulated);
  listView.setMinWidth(300);
  listView.setMinHeight(300);
  listView.setEditable(true);

  countries.addAll("India", "Australia", "Bahrain", "Bangladesh", "Cambodia", "Connie", "Chile", "France",
    "Hong Kong", "Iran");

  listView.setCellFactory(ComboBoxListCell.forListView(countries));

  listView.getSelectionModel().selectedItemProperty()
    .addListener((ObservableValue<? extends String> ov, String old_val, String new_val) -> {
     label.setText("Country changed from " + old_val + " to " + new_val);
    });

  HBox hBox = new HBox();
  hBox.getChildren().addAll(listView, label);
  primaryStage.setScene(new Scene(hBox, 1000, 250));
  primaryStage.setTitle("List View Sample");
  primaryStage.show();
 }
}

TestFX.java
package com.sample.demos;

import javafx.application.Application;

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





Previous                                                 Next                                                 Home

No comments:

Post a Comment