Friday, 15 June 2018

JavaFX: Customize ListCell

By extending the ListCell class, you can customize the listcells.

For example, below snippet defines 'ListColorCell' class that paints the listcell with given color.

         private static class ListColorCell extends ListCell<String> {
                  @Override
                  public void updateItem(String item, boolean empty) {

                           if (item == null) {
                                    return;
                           }

                           super.updateItem(item, empty);
                           Rectangle rect = new Rectangle(400, 20);
                           rect.setFill(Color.web(item));
                           setGraphic(rect);
                  }
         }

The content of the cell is represented by setGraphic method.

Find the below working application.

ListViewApp.java

package com.sample.demos;

import javafx.application.Application;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.scene.Scene;
import javafx.scene.control.ListCell;
import javafx.scene.control.ListView;
import javafx.scene.layout.VBox;
import javafx.scene.paint.Color;
import javafx.scene.shape.Rectangle;
import javafx.stage.Stage;

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

 private static class ListColorCell extends ListCell<String> {
  @Override
  public void updateItem(String item, boolean empty) {

   if (item == null) {
    return;
   }

   super.updateItem(item, empty);
   Rectangle rect = new Rectangle(400, 20);
   rect.setFill(Color.web(item));
   setGraphic(rect);
  }
 }

 @Override
 public void start(Stage primaryStage) {

  final ListView<String> listView = new ListView<>(colors);
  listView.setCellFactory((ListView<String> l) -> new ListColorCell());

  colors.addAll("tomato", "chocolate", "salmon", "gold", "powderblue", "coral", "darkorchid", "fuchsia",
    "darkgoldenrod", "lightsalmon", "black", "rosybrown", "blue", "papayawhip", "blueviolet",
    "darkturquoise", "brown");

  VBox vBox = new VBox(listView);

  primaryStage.setScene(new Scene(vBox, 400, 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