1 /*
   2  * Copyright (c) 2010, 2016, Oracle and/or its affiliates. All rights reserved.
   3  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
   4  *
   5  * This code is free software; you can redistribute it and/or modify it
   6  * under the terms of the GNU General Public License version 2 only, as
   7  * published by the Free Software Foundation.  Oracle designates this
   8  * particular file as subject to the "Classpath" exception as provided
   9  * by Oracle in the LICENSE file that accompanied this code.
  10  *
  11  * This code is distributed in the hope that it will be useful, but WITHOUT
  12  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
  13  * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
  14  * version 2 for more details (a copy is included in the LICENSE file that
  15  * accompanied this code).
  16  *
  17  * You should have received a copy of the GNU General Public License version
  18  * 2 along with this work; if not, write to the Free Software Foundation,
  19  * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
  20  *
  21  * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
  22  * or visit www.oracle.com if you need additional information or have any
  23  * questions.
  24  */
  25 
  26 package javafx.scene.control;
  27 
  28 import javafx.beans.InvalidationListener;
  29 import javafx.beans.Observable;
  30 import javafx.beans.property.BooleanProperty;
  31 import javafx.beans.property.ObjectProperty;
  32 import javafx.beans.property.SimpleBooleanProperty;
  33 import javafx.beans.property.SimpleObjectProperty;
  34 import javafx.collections.ObservableList;
  35 import javafx.scene.Node;
  36 import javafx.scene.layout.GridPane;
  37 import javafx.scene.layout.HBox;
  38 import javafx.scene.shape.Rectangle;
  39 import javafx.css.PseudoClass;
  40 import javafx.beans.property.ReadOnlyBooleanProperty;
  41 import javafx.beans.property.ReadOnlyBooleanWrapper;
  42 import javafx.beans.value.WritableValue;
  43 import javafx.css.StyleableProperty;
  44 
  45 /**
  46  * The Cell API is used for virtualized controls such as {@link ListView},
  47  * {@link TreeView}, and {@link TableView}.
  48  * A Cell is a {@link Labeled} {@link Control}, and is used to render a single
  49  * "row" inside  a ListView, TreeView or TableView. Cells are also used for each
  50  * individual 'cell' inside a TableView (i.e. each row/column intersection). See
  51  * the JavaDoc for each control separately for more detail.
  52  * <p>
  53  * Every Cell is associated with a single data item (represented by the
  54  * {@link #itemProperty() item} property). The Cell is responsible for
  55  * rendering that item and, where appropriate, for editing the item. An item
  56  * within a Cell may be represented by text or some other control such as a
  57  * {@link CheckBox}, {@link ChoiceBox} or any other {@link Node} such as a
  58  * {@link HBox}, {@link GridPane}, or even a {@link Rectangle}.
  59  * <p>
  60  * Because TreeView, ListView, TableView and other such controls can potentially
  61  * be used for displaying incredibly large amounts of data, it is not feasible
  62  * to create an actual Cell for every single item in the control.
  63  * We represent extremely large data sets using only very few Cells. Each Cell
  64  * is "recycled", or reused. This is what we mean when we say that these controls
  65  * are virtualized.
  66  * <p>
  67  * Since Cell is a Control, it is essentially a "model". Its Skin is responsible
  68  * for defining the look and layout, while the Behavior is responsible for
  69  * handling all input events and using that information to modify the Control
  70  * state. Also, the Cell is styled from CSS just like any other Control.
  71  * However, it is not necessary to implement a Skin for most uses of a Cell.
  72  * This is because a cell factory can be set - this is detailed more shortly.
  73  * <p>
  74  * Because by far the most common use case for cells is to show text to a user,
  75  * this use case is specially optimized for within Cell. This is done by Cell
  76  * extending from {@link Labeled}. This means that subclasses of Cell need only
  77  * set the {@link #textProperty() text} property, rather than create a separate
  78  * {@link Label} and set that within the Cell. However, for situations where
  79  * something more than just plain text is called for, it is possible to place
  80  * any {@link Node} in the Cell {@link #graphicProperty() graphic} property.
  81  * Despite the term, a graphic can be any Node, and will be fully interactive.
  82  * For example, a ListCell might be configured with a {@link Button} as its
  83  * graphic. The Button text could then be bound to the cells
  84  * {@link #itemProperty() item} property. In this way, whenever the item in the
  85  * Cell changes, the Button text is automatically updated.
  86  * <p>
  87  * Cell sets focusTraversable to false.
  88  * </p>
  89  * <p>
  90  * <b>Cell Factories</b>
  91  * <p>
  92  * The default representation of the Cell <code>item</code> is up to the various
  93  * virtualized container's skins to render. For example, the ListView by default
  94  * will convert the item to a String and call {@link #setText(java.lang.String)}
  95  * with this value. If you want to specialize the Cell used for the
  96  * ListView (for example), then you must provide an implementation of the
  97  * {@link ListView#cellFactoryProperty() cellFactory} callback function defined
  98  * on the ListView. Similar API exists on most controls that use Cells (for example,
  99  * {@link TreeView#cellFactoryProperty() TreeView},
 100  * {@link TableView#rowFactoryProperty() TableView},
 101  * {@link TableColumn#cellFactoryProperty() TableColumn} and
 102  * {@link ListView#cellFactoryProperty() ListView}.
 103  * <p>
 104  * The cell factory is called by the platform whenever it determines that a new
 105  * cell needs to be created. For example, perhaps your ListView has 10 million
 106  * items. Creating all 10 million cells would be prohibitively expensive. So
 107  * instead the ListView skin implementation might only create just enough cells
 108  * to fit the visual space. If the ListView is resized to be larger, the system
 109  * will determine that it needs to create some additional cells. In this case
 110  * it will call the cellFactory callback function (if one is provided) to create
 111  * the Cell implementation that should be used. If no cell factory is provided,
 112  * the built-in default implementation will be used.
 113  * <p>
 114  * The implementation of the cell factory is then responsible not just for
 115  * creating a Cell instance, but also configuring that Cell such that it reacts
 116  * to changes in its state. For example, if I were to create
 117  * a custom Cell which formatted Numbers such that they would appear as currency
 118  * types, I might do so like this:
 119  *
 120  * <pre>
 121  * public class MoneyFormatCell extends ListCell&lt;Number&gt; {
 122  *
 123  *     public MoneyFormatCell() {    }
 124  *
 125  *     @Override protected void updateItem(Number item, boolean empty) {
 126  *         // calling super here is very important - don't skip this!
 127  *         super.updateItem(item, empty);
 128  *
 129  *         // format the number as if it were a monetary value using the
 130  *         // formatting relevant to the current locale. This would format
 131  *         // 43.68 as "$43.68", and -23.67 as "-$23.67"
 132  *         setText(item == null ? "" : NumberFormat.getCurrencyInstance().format(item));
 133  *
 134  *         // change the text fill based on whether it is positive (green)
 135  *         // or negative (red). If the cell is selected, the text will
 136  *         // always be white (so that it can be read against the blue
 137  *         // background), and if the value is zero, we'll make it black.
 138  *         if (item != null) {
 139  *             double value = item.doubleValue();
 140  *             setTextFill(isSelected() ? Color.WHITE :
 141  *                 value == 0 ? Color.BLACK :
 142  *                 value < 0 ? Color.RED : Color.GREEN);
 143  *         }
 144  *     }
 145  * }</pre>
 146  *
 147  * This class could then be used inside a ListView as such:
 148  *
 149  * <pre>
 150  * ObservableList&lt;Number&gt; money = ...;
 151  * final ListView&lt;Number&gt; listView = new ListView&lt;Number&gt;(money);
 152  * listView.setCellFactory(new Callback&lt;ListView&lt;Number&gt;, ListCell&lt;Number&gt;&gt;() {
 153  *     @Override public ListCell&lt;Number&gt; call(ListView&lt;Number&gt; list) {
 154  *         return new MoneyFormatCell();
 155  *     }
 156  * });</pre>
 157  *
 158  * In this example an anonymous inner class is created, that simply returns
 159  * instances of MoneyFormatCell whenever it is called. The MoneyFormatCell class
 160  * extends {@link ListCell}, overriding the
 161  * {@link #updateItem(java.lang.Object, boolean) updateItem} method. This method
 162  * is called whenever the item in the cell changes, for example when the user
 163  * scrolls the ListView or the content of the underlying data model changes
 164  * (and the cell is reused to represent some different item in the ListView).
 165  * Because of this, there is no need to manage bindings - simply react to the
 166  * change in items when this method occurs. In the example above, whenever the
 167  * item changes, we update the cell text property, and also modify the text fill
 168  * to ensure that we get the correct visuals. In addition, if the cell is "empty"
 169  * (meaning it is used to fill out space in the ListView but doesn't have any
 170  * data associated with it), then we just use the empty String.
 171  * <p>
 172  * Note that there are additional
 173  * methods prefixed with 'update' that may be of interest, so be
 174  * sure to read the API documentation for Cell, and subclasses of Cell, closely.
 175  * <p>
 176  * Of course, we can also use the binding API rather than overriding the
 177  * 'update' methods. Shown below is a very trivial example of how this could
 178  * be achieved.
 179  *
 180  *
 181  * <pre>
 182  * public class BoundLabelCell extends ListCell&lt;String&gt; {
 183  *
 184  *     public BoundLabelCell() {
 185  *         textProperty().bind(itemProperty());
 186  *     }
 187  * }
 188  * </pre>
 189  *
 190  * <h3>Key Design Goals</h3>
 191  * <ul>
 192  *   <li>Both time and memory efficient for large data sets</li>
 193  *   <li>Easy to build and use libraries for custom cells</li>
 194  *   <li>Easy to customize cell visuals</li>
 195  *   <li>Easy to customize display formatting (12.34 as $12.34 or 1234% etc)</li>
 196  *   <li>Easy to extend for custom visuals</li>
 197  *   <li>Easy to have "panels" of data for the visuals</li>
 198  *   <li>Easy to animate the cell size or other properties</li>
 199  * </ul>
 200  *
 201  * <h3>Key Use Cases</h3>
 202  * Following are a number of key use cases used to drive the Cell API design,
 203  * along with code examples showing how those use cases are satisfied by this
 204  * API. This is by no means to be considered the definitive list of capabilities
 205  * or features supported, but rather, to provide some guidance as to how to use
 206  * the Cell API. The examples below are focused on the ListView, but the same
 207  * philosophy applies to TreeCells or other kinds of cells.
 208  * <p>
 209  * <b>Changing the Cell's Colors</b>
 210  * <p>
 211  * This should be extraordinarily simple in JavaFX. Each Cell can be styled
 212  * directly from CSS. So for example, if you wanted to change the default
 213  * background of every cell in a ListView to be WHITE you could do the
 214  * following CSS:
 215  *
 216  * <pre>
 217  * .list-cell {
 218  *   -fx-padding: 3 3 3 3;
 219  *   -fx-background-color: white;
 220  * }</pre>
 221  *
 222  * If you wanted to set the color of selected ListView cells to be blue, you
 223  * could add this to your CSS file:
 224  *
 225  * <pre>
 226  * .list-cell:selected {
 227  *   -fx-background-color: blue;
 228  * }</pre>
 229  *
 230  * Most Cell implementations extend from {@link IndexedCell} rather than Cell.
 231  * IndexedCell adds two other pseudoclass states: "odd" and "even". Using this
 232  * you can get alternate row striping by doing something like this in your CSS
 233  * file:
 234  *
 235  * <pre>
 236  * .list-cell:odd {
 237  *   -fx-background-color: grey;
 238  * }</pre>
 239  *
 240  * Each of these examples require no code changes. Simply update your CSS
 241  * file to alter the colors. You can also use the "hover" and other
 242  * pseudoclasses in CSS the same as with other controls.
 243  * <p>
 244  * Another approach to the first example above (formatting a list of numbers) would
 245  * be to use style classes. Suppose you had an {@link ObservableList} of Numbers
 246  * to display in a ListView and wanted to color all of the negative values red
 247  * and all positive or 0 values black.
 248  * One way to achieve this is with a custom cellFactory which changes the
 249  * styleClass of the Cell based on whether the value is negative or positive. This
 250  * is as simple as adding code to test if the number in the cell is negative,
 251  * and adding a "negative" styleClass. If the number is not negative, the "negative"
 252  * string should be removed. This approach allows for the colors to be defined
 253  * from CSS, allowing for simple customization. The CSS file would then include
 254  * something like the following:
 255  *
 256  * <pre>
 257  * .list-cell {
 258  *   -fx-text-fill: black;
 259  * }
 260  *
 261  * .list-cell .negative {
 262  *   -fx-text-fill: red;
 263  * }</pre>
 264  *
 265  * <h3>Editing</h3>
 266  * <p>Most virtualized controls that use the Cell architecture (e.g. {@link ListView},
 267  * {@link TreeView}, {@link TableView} and {@link TreeTableView}) all support
 268  * the notion of editing values directly via the cell. You can learn more about
 269  * the control-specific details by going to the 'editing' section in the class
 270  * documentation for the controls linked above. The remainder of this section
 271  * will cover some of the finer details of editing with cells.</p>
 272  *
 273  * <p>The general flow of editing is as follows (note that in these steps the
 274  * {@link ListView} control is used as an example, but similar API exists for
 275  * all controls mentioned above, and the process is exactly the same in general):</p>
 276  *
 277  * <ol>
 278  *     <li>User requests a cell enter editing mode (via keyboard or mouse commands),
 279  *     or the developer requests that a cell enter editing mode (by calling a
 280  *     method such as the ListView {@link ListView#edit(int) edit} method.
 281  *     <strong>Note:</strong> If the user double-clicks or fires an appropriate
 282  *     keyboard command to initiate editing, then they are effectively calling
 283  *     the appropriate edit method on the control (i.e. the entry method for
 284  *     user-initiated and developer-initiated editing is the same).</li>
 285  *     <li>Each cell in the visible region of the control is notified that the
 286  *     current {@link javafx.scene.control.ListView#editingIndexProperty() editing cell}
 287  *     has changed, and checks to see if it is itself. At this point one of three
 288  *     things can happen:
 289  *         <ol>
 290  *             <li>If the editing index is the same index as the cell,
 291  *             {@link #startEdit()} will be called on this cell. Some pointers:
 292  *                 <ol>
 293  *                     <li>It is recommended that subclasses of Cell override the {@link #startEdit()}
 294  *                     method to update the visuals of the cell when enters the editing state. Note
 295  *                     however that it is very important that subclasses that override the
 296  *                     {@link #startEdit()} method continue to call {@code super.startEdit()} so
 297  *                     that parent classes can update additional state that is necessary for
 298  *                     editing to be successful.</li>
 299  *                     <li>Within the {@link #startEdit()} method is an ideal
 300  *                     time to change the visuals of the cell. For example (and
 301  *                     note that this example is more fleshed out in the UI control
 302  *                     javadocs for {@link ListView}, etc), you may set the
 303  *                     {@link #graphicProperty()} of the cell to a
 304  *                     {@link TextField} and set the {@link #textProperty()}
 305  *                     to null. This would allow end users to then type in input
 306  *                     and make changes to your data model.</li>
 307  *                     <li>When the user has completed editing, they will want
 308  *                     to commit or cancel their change. This is your responsibility
 309  *                     to handle (e.g. by having the Enter key
 310  *                     {@link #commitEdit(Object) commit the edit}
 311  *                     and the ESC key {@link #cancelEdit() cancel the edit}).
 312  *                     You do this by attaching the appropriate event listeners
 313  *                     to the nodes you show whilst in the editing state.</li>
 314  *                 </ol>
 315  *             </li>
 316  *             <li>If the editing index is not the same index as the cell, and
 317  *             if the cell is currently in the {@link #isEditing() editing state},
 318  *             {@link #cancelEdit()} will be called on this cell. As with the
 319  *             {@link #startEdit()} method, you should override this method to
 320  *             clean up the visuals of the cell (and most probably return the
 321  *             {@link #graphicProperty()} back to null and set the
 322  *             {@link #textProperty()} to its (possibly new) value. Again,
 323  *             be sure to always call {@code super.cancelEdit()} to make sure all
 324  *             state is correctly updated.</li>
 325  *             <li>If the editing index is not the same index as the cell, and
 326  *             if the cell is not currently in the {@link #isEditing()} editing state},
 327  *             then nothing will happen on this cell.</li>
 328  *         </ol>
 329  *     </li>
 330  * </ol>
 331  *
 332  *
 333  * @param <T> The type of the item contained within the Cell.
 334  *
 335  * @since JavaFX 2.0
 336  */
 337 public class Cell<T> extends Labeled {
 338 
 339     /***************************************************************************
 340      *                                                                         *
 341      * Constructors                                                            *
 342      *                                                                         *
 343      **************************************************************************/
 344 
 345     /**
 346      * Creates a default Cell with the default style class of 'cell'.
 347      */
 348     public Cell() {
 349         setText(null); // default to null text, to match the null item
 350         // focusTraversable is styleable through css. Calling setFocusTraversable
 351         // makes it look to css like the user set the value and css will not
 352         // override. Initializing focusTraversable by calling set on the
 353         // CssMetaData ensures that css will be able to override the value.
 354         ((StyleableProperty<Boolean>)(WritableValue<Boolean>)focusTraversableProperty()).applyStyle(null, Boolean.FALSE);
 355         getStyleClass().addAll(DEFAULT_STYLE_CLASS);
 356 
 357         /**
 358          * Indicates whether or not this cell has focus. For example, a
 359          * ListView defines zero or one cell as being the "focused" cell. This cell
 360          * would have focused set to true.
 361          */
 362         super.focusedProperty().addListener(new InvalidationListener() {
 363             @Override public void invalidated(Observable property) {
 364                 pseudoClassStateChanged(PSEUDO_CLASS_FOCUSED, isFocused()); // TODO is this necessary??
 365 
 366                 // The user has shifted focus, so we should cancel the editing on this cell
 367                 if (!isFocused() && isEditing()) {
 368                     cancelEdit();
 369                 }
 370             }
 371         });
 372 
 373         // initialize default pseudo-class state
 374         pseudoClassStateChanged(PSEUDO_CLASS_EMPTY, true);
 375     }
 376 
 377 
 378 
 379     /***************************************************************************
 380      *                                                                         *
 381      * Properties                                                              *
 382      *                                                                         *
 383      **************************************************************************/
 384 
 385     // --- item
 386     private ObjectProperty<T> item = new SimpleObjectProperty<T>(this, "item");
 387 
 388     /**
 389      * The data value associated with this Cell. This value is set by the
 390      * virtualized Control when the Cell is created or updated. This represents
 391      * the raw data value.
 392     *
 393     * <p>This value should only be set in subclasses of Cell by the virtualised
 394     * user interface controls that know how to properly work with the Cell
 395     * class.
 396      */
 397     public final ObjectProperty<T> itemProperty() { return item; }
 398 
 399     /**
 400      * Sets the item to the given value - should not be called directly as the
 401      * item is managed by the virtualized control.
 402      */
 403     public final void setItem(T value) { item.set(value); }
 404 
 405     /**
 406      * Returns the data value associated with this Cell.
 407      */
 408     public final T getItem() { return item.get(); }
 409 
 410 
 411 
 412     // --- empty
 413     private ReadOnlyBooleanWrapper empty = new ReadOnlyBooleanWrapper(true) {
 414         @Override protected void invalidated() {
 415             final boolean active = get();
 416             pseudoClassStateChanged(PSEUDO_CLASS_EMPTY,   active);
 417             pseudoClassStateChanged(PSEUDO_CLASS_FILLED, !active);
 418         }
 419 
 420         @Override
 421         public Object getBean() {
 422             return Cell.this;
 423         }
 424 
 425         @Override
 426         public String getName() {
 427             return "empty";
 428         }
 429     };
 430 
 431     /**
 432      * A property used to represent whether the cell has any contents.
 433      * If true, then the Cell contains no data and is not associated with any
 434      * data item in the virtualized Control.
 435      *
 436      * <p>When a cell is empty, it can be styled differently via the 'empty'
 437      * CSS pseudo class state. For example, it may not receive any
 438      * alternate row highlighting, or it may not receive hover background
 439      * fill when hovered.
 440      */
 441     public final ReadOnlyBooleanProperty emptyProperty() { return empty.getReadOnlyProperty(); }
 442 
 443     private void setEmpty(boolean value) { empty.set(value); }
 444 
 445     /**
 446      * Returns a boolean representing whether the cell is considered to be empty
 447      * or not.
 448      */
 449     public final boolean isEmpty() { return empty.get(); }
 450 
 451 
 452 
 453     // --- selected
 454     private ReadOnlyBooleanWrapper selected = new ReadOnlyBooleanWrapper() {
 455         @Override protected void invalidated() {
 456             pseudoClassStateChanged(PSEUDO_CLASS_SELECTED, get());
 457         }
 458 
 459         @Override
 460         public Object getBean() {
 461             return Cell.this;
 462         }
 463 
 464         @Override
 465         public String getName() {
 466             return "selected";
 467         }
 468     };
 469 
 470     /**
 471      * Indicates whether or not this cell has been selected. For example, a
 472      * ListView defines zero or more cells as being the "selected" cells.
 473      */
 474     public final ReadOnlyBooleanProperty selectedProperty() { return selected.getReadOnlyProperty(); }
 475 
 476     void setSelected(boolean value) { selected.set(value); }
 477 
 478     /**
 479      * Returns whether this cell is currently selected or not.
 480      * @return True if the cell is selected, false otherwise.
 481      */
 482     public final boolean isSelected() { return selected.get(); }
 483 
 484 
 485 
 486     // --- Editing
 487     private ReadOnlyBooleanWrapper editing;
 488 
 489     private void setEditing(boolean value) {
 490         editingPropertyImpl().set(value);
 491     }
 492 
 493     /**
 494      * Represents whether the cell is currently in its editing state or not.
 495      */
 496     public final boolean isEditing() {
 497         return editing == null ? false : editing.get();
 498     }
 499 
 500     /**
 501      * Property representing whether this cell is currently in its editing state.
 502      */
 503     public final ReadOnlyBooleanProperty editingProperty() {
 504         return editingPropertyImpl().getReadOnlyProperty();
 505     }
 506 
 507     private ReadOnlyBooleanWrapper editingPropertyImpl() {
 508         if (editing == null) {
 509             editing = new ReadOnlyBooleanWrapper(this, "editing");
 510         }
 511         return editing;
 512     }
 513 
 514 
 515 
 516     // --- Editable
 517     private BooleanProperty editable;
 518 
 519     /**
 520      * Allows for certain cells to not be able to be edited. This is useful in
 521      * cases where, say, a List has 'header rows' - it does not make sense for
 522      * the header rows to be editable, so they should have editable set to
 523      * false.
 524      *
 525      * @param value A boolean representing whether the cell is editable or not.
 526      *      If true, the cell is editable, and if it is false, the cell can not
 527      *      be edited.
 528      */
 529     public final void setEditable(boolean value) {
 530         editableProperty().set(value);
 531     }
 532 
 533     /**
 534      * Returns whether this cell is allowed to be put into an editing state.
 535      */
 536     public final boolean isEditable() {
 537         return editable == null ? true : editable.get();
 538     }
 539 
 540     /**
 541      * A property representing whether this cell is allowed to be put into an
 542      * editing state. By default editable is set to true in Cells (although for
 543      * a subclass of Cell to be allowed to enter its editing state, it may have
 544      * to satisfy additional criteria. For example, ListCell requires that the
 545      * ListView {@link ListView#editableProperty() editable} property is also
 546      * true.
 547      */
 548     public final BooleanProperty editableProperty() {
 549         if (editable == null) {
 550             editable = new SimpleBooleanProperty(this, "editable", true);
 551         }
 552         return editable;
 553     }
 554 
 555 
 556 
 557     /***************************************************************************
 558      *                                                                         *
 559      * Public API                                                              *
 560      *                                                                         *
 561      **************************************************************************/
 562 
 563     /**
 564      * Call this function to transition from a non-editing state into an editing
 565      * state, if the cell is editable. If this cell is already in an editing
 566      * state, it will stay in it.
 567      */
 568     public void startEdit() {
 569         if (isEditable() && !isEditing() && !isEmpty()) {
 570             setEditing(true);
 571         }
 572     }
 573 
 574     /**
 575      * Call this function to transition from an editing state into a non-editing
 576      * state, without saving any user input.
 577      */
 578     public void cancelEdit() {
 579         if (isEditing()) {
 580             setEditing(false);
 581         }
 582     }
 583 
 584     /**
 585      * Call this function when appropriate (based on the user interaction requirements
 586      * of your cell editing user interface) to do two things:
 587      *
 588      * <ol>
 589      *     <li>Fire the appropriate events back to the backing UI control (e.g.
 590      *     {@link ListView}). This will begin the process of pushing this edit
 591      *     back to the relevant data source / property (although it does not
 592      *     guarantee that this will be successful - that is dependent upon the
 593      *     specific edit commit handler being used). Refer to the UI control
 594      *     class javadoc for more detail.</li>
 595      *     <li>Begin the transition from an editing state into a non-editing state.</li>
 596      * </ol>
 597      *
 598      * <p>In general there is no need to override this method in custom cell
 599      * implementations - it should be sufficient to simply call this method
 600      * when appropriate (e.g. when the user pressed the Enter key, you may do something
 601      * like {@code cell.commitEdit(converter.fromString(textField.getText()));}</p>
 602      *
 603      * @param newValue The value as input by the end user, which should be
 604      *      persisted in the relevant way given the data source underpinning the
 605      *      user interface and the install edit commit handler of the UI control.
 606      */
 607     public void commitEdit(T newValue) {
 608         if (isEditing()) {
 609             setEditing(false);
 610         }
 611     }
 612 
 613     /** {@inheritDoc} */
 614     @Override protected void layoutChildren() {
 615         if (itemDirty) {
 616             updateItem(getItem(), isEmpty());
 617             itemDirty = false;
 618         }
 619         super.layoutChildren();
 620     }
 621 
 622 
 623 
 624     /***************************************************************************
 625      *                                                                         *
 626      * Expert API                                                              *
 627      *                                                                         *
 628      **************************************************************************/
 629 
 630     /**
 631      * The updateItem method should not be called by developers, but it is the
 632      * best method for developers to override to allow for them to customise the
 633      * visuals of the cell. To clarify, developers should never call this method
 634      * in their code (they should leave it up to the UI control, such as the
 635      * {@link javafx.scene.control.ListView} control) to call this method. However,
 636      * the purpose of having the updateItem method is so that developers, when
 637      * specifying custom cell factories (again, like the ListView
 638      * {@link javafx.scene.control.ListView#cellFactoryProperty() cell factory}),
 639      * the updateItem method can be overridden to allow for complete customisation
 640      * of the cell.
 641      *
 642      * <p>It is <strong>very important</strong> that subclasses
 643      * of Cell override the updateItem method properly, as failure to do so will
 644      * lead to issues such as blank cells or cells with unexpected content
 645      * appearing within them. Here is an example of how to properly override the
 646      * updateItem method:
 647      *
 648      * <pre>
 649      * protected void updateItem(T item, boolean empty) {
 650      *     super.updateItem(item, empty);
 651      *
 652      *     if (empty || item == null) {
 653      *         setText(null);
 654      *         setGraphic(null);
 655      *     } else {
 656      *         setText(item.toString());
 657      *     }
 658      * }
 659      * </pre>
 660      *
 661      * <p>Note in this code sample two important points:
 662      * <ol>
 663      *     <li>We call the super.updateItem(T, boolean) method. If this is not
 664      *     done, the item and empty properties are not correctly set, and you are
 665      *     likely to end up with graphical issues.</li>
 666      *     <li>We test for the <code>empty</code> condition, and if true, we
 667      *     set the text and graphic properties to null. If we do not do this,
 668      *     it is almost guaranteed that end users will see graphical artifacts
 669      *     in cells unexpectedly.</li>
 670      * </ol>
 671      *
 672      * @param item The new item for the cell.
 673      * @param empty whether or not this cell represents data from the list. If it
 674      *        is empty, then it does not represent any domain data, but is a cell
 675      *        being used to render an "empty" row.
 676      * @expert
 677      */
 678     protected void updateItem(T item, boolean empty) {
 679         setItem(item);
 680         setEmpty(empty);
 681         if (empty && isSelected()) {
 682             updateSelected(false);
 683         }
 684     }
 685 
 686     /**
 687      * Updates whether this cell is in a selected state or not.
 688      * @expert
 689      * @param selected whether or not to select this cell.
 690      */
 691     public void updateSelected(boolean selected) {
 692         if (selected && isEmpty()) return;
 693         boolean wasSelected = isSelected();
 694         setSelected(selected);
 695 
 696         if (wasSelected != selected) {
 697             markCellDirty();
 698         }
 699     }
 700 
 701     /**
 702      * This method is called by Cell subclasses so that certain CPU-intensive
 703      * actions (specifically, calling {@link #updateItem(Object, boolean)}) are
 704      * only performed when necessary (that is, they are only performed
 705      * when the currently set {@link #itemProperty() item} is considered to be
 706      * different than the proposed new item that could be set).
 707      *
 708      * <p>The default implementation of this method tests against equality, but
 709      * developers are able to override this method to perform checks in other ways
 710      * that are specific to their domain.</p>
 711      *
 712      * @param oldItem The currently-set item contained within the cell (i.e. it is
 713      *                the same as what is available via {@link #getItem()}).
 714      * @param newItem The item that will be set in the cell, if this method
 715      *                returns true. If this method returns false, it may not be
 716      *                set.
 717      * @return Returns true if the new item is considered to be different than
 718      *         the old item. By default this method tests against equality, but
 719      *         subclasses may alter the implementation to test appropriate to
 720      *         their needs.
 721      * @since JavaFX 8u40
 722      */
 723     protected boolean isItemChanged(T oldItem, T newItem) {
 724         return oldItem != null ? !oldItem.equals(newItem) : newItem != null;
 725     }
 726 
 727 
 728 
 729     /***************************************************************************
 730      *                                                                         *
 731      * Private Implementation                                                  *
 732      *                                                                         *
 733      **************************************************************************/
 734 
 735     // itemDirty and markCellDirty introduced as a solution for JDK-8145588.
 736     // In the fullness of time, a more fully developed solution can be developed
 737     // that offers a public API around this lazy-dirty impl.
 738     private boolean itemDirty = false;
 739     private final void markCellDirty() {
 740         itemDirty = true;
 741         requestLayout();
 742     }
 743 
 744 
 745     /***************************************************************************
 746      *                                                                         *
 747      * Stylesheet Handling                                                     *
 748      *                                                                         *
 749      **************************************************************************/
 750 
 751     private static final String DEFAULT_STYLE_CLASS = "cell";
 752     private static final PseudoClass PSEUDO_CLASS_SELECTED =
 753             PseudoClass.getPseudoClass("selected");
 754     private static final PseudoClass PSEUDO_CLASS_FOCUSED =
 755             PseudoClass.getPseudoClass("focused");
 756     private static final PseudoClass PSEUDO_CLASS_EMPTY =
 757             PseudoClass.getPseudoClass("empty");
 758     private static final PseudoClass PSEUDO_CLASS_FILLED =
 759             PseudoClass.getPseudoClass("filled");
 760 
 761     /**
 762      * Returns the initial focus traversable state of this control, for use
 763      * by the JavaFX CSS engine to correctly set its initial value. This method
 764      * is overridden as by default UI controls have focus traversable set to true,
 765      * but that is not appropriate for this control.
 766      *
 767      * @since 9
 768      */
 769     @Override protected Boolean getInitialFocusTraversable() {
 770         return Boolean.FALSE;
 771     }
 772 }