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<Number> { 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<Number> money = ...; 151 * final ListView<Number> listView = new ListView<Number>(money); 152 * listView.setCellFactory(new Callback<ListView<Number>, ListCell<Number>>() { 153 * @Override public ListCell<Number> call(ListView<Number> 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<String> { 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 * @return the data value associated with this cell 397 */ 398 public final ObjectProperty<T> itemProperty() { return item; } 399 400 /** 401 * Sets the item to the given value - should not be called directly as the 402 * item is managed by the virtualized control. 403 * @param value the data value to this item 404 */ 405 public final void setItem(T value) { item.set(value); } 406 407 /** 408 * Returns the data value associated with this Cell. 409 * @return the data value associated with this cell 410 */ 411 public final T getItem() { return item.get(); } 412 413 414 415 // --- empty 416 private ReadOnlyBooleanWrapper empty = new ReadOnlyBooleanWrapper(true) { 417 @Override protected void invalidated() { 418 final boolean active = get(); 419 pseudoClassStateChanged(PSEUDO_CLASS_EMPTY, active); 420 pseudoClassStateChanged(PSEUDO_CLASS_FILLED, !active); 421 } 422 423 @Override 424 public Object getBean() { 425 return Cell.this; 426 } 427 428 @Override 429 public String getName() { 430 return "empty"; 431 } 432 }; 433 434 /** 435 * A property used to represent whether the cell has any contents. 436 * If true, then the Cell contains no data and is not associated with any 437 * data item in the virtualized Control. 438 * 439 * <p>When a cell is empty, it can be styled differently via the 'empty' 440 * CSS pseudo class state. For example, it may not receive any 441 * alternate row highlighting, or it may not receive hover background 442 * fill when hovered. 443 * @return the representation of whether this cell has any contents 444 */ 445 public final ReadOnlyBooleanProperty emptyProperty() { return empty.getReadOnlyProperty(); } 446 447 private void setEmpty(boolean value) { empty.set(value); } 448 449 /** 450 * Returns a boolean representing whether the cell is considered to be empty 451 * or not. 452 * @return true if cell is empty, otherwise false 453 */ 454 public final boolean isEmpty() { return empty.get(); } 455 456 457 458 // --- selected 459 private ReadOnlyBooleanWrapper selected = new ReadOnlyBooleanWrapper() { 460 @Override protected void invalidated() { 461 pseudoClassStateChanged(PSEUDO_CLASS_SELECTED, get()); 462 } 463 464 @Override 465 public Object getBean() { 466 return Cell.this; 467 } 468 469 @Override 470 public String getName() { 471 return "selected"; 472 } 473 }; 474 475 /** 476 * Indicates whether or not this cell has been selected. For example, a 477 * ListView defines zero or more cells as being the "selected" cells. 478 * @return the representation of whether this cell has been selected 479 */ 480 public final ReadOnlyBooleanProperty selectedProperty() { return selected.getReadOnlyProperty(); } 481 482 void setSelected(boolean value) { selected.set(value); } 483 484 /** 485 * Returns whether this cell is currently selected or not. 486 * @return True if the cell is selected, false otherwise. 487 */ 488 public final boolean isSelected() { return selected.get(); } 489 490 491 492 // --- Editing 493 private ReadOnlyBooleanWrapper editing; 494 495 private void setEditing(boolean value) { 496 editingPropertyImpl().set(value); 497 } 498 499 /** 500 * Represents whether the cell is currently in its editing state or not. 501 * @return true if this cell is currently in its editing state, otherwise 502 * false 503 */ 504 public final boolean isEditing() { 505 return editing == null ? false : editing.get(); 506 } 507 508 /** 509 * Property representing whether this cell is currently in its editing state. 510 * @return the representation of whether this cell is currently in its 511 * editing state 512 */ 513 public final ReadOnlyBooleanProperty editingProperty() { 514 return editingPropertyImpl().getReadOnlyProperty(); 515 } 516 517 private ReadOnlyBooleanWrapper editingPropertyImpl() { 518 if (editing == null) { 519 editing = new ReadOnlyBooleanWrapper(this, "editing"); 520 } 521 return editing; 522 } 523 524 525 526 // --- Editable 527 private BooleanProperty editable; 528 529 /** 530 * Allows for certain cells to not be able to be edited. This is useful in 531 * cases where, say, a List has 'header rows' - it does not make sense for 532 * the header rows to be editable, so they should have editable set to 533 * false. 534 * 535 * @param value A boolean representing whether the cell is editable or not. 536 * If true, the cell is editable, and if it is false, the cell can not 537 * be edited. 538 */ 539 public final void setEditable(boolean value) { 540 editableProperty().set(value); 541 } 542 543 /** 544 * Returns whether this cell is allowed to be put into an editing state. 545 * @return true if this cell is allowed to be put into an editing state, 546 * otherwise false 547 */ 548 public final boolean isEditable() { 549 return editable == null ? true : editable.get(); 550 } 551 552 /** 553 * A property representing whether this cell is allowed to be put into an 554 * editing state. By default editable is set to true in Cells (although for 555 * a subclass of Cell to be allowed to enter its editing state, it may have 556 * to satisfy additional criteria. For example, ListCell requires that the 557 * ListView {@link ListView#editableProperty() editable} property is also 558 * true. 559 * @return the representation of whether this cell is allowed to be put into 560 * an editing state 561 */ 562 public final BooleanProperty editableProperty() { 563 if (editable == null) { 564 editable = new SimpleBooleanProperty(this, "editable", true); 565 } 566 return editable; 567 } 568 569 570 571 /*************************************************************************** 572 * * 573 * Public API * 574 * * 575 **************************************************************************/ 576 577 /** 578 * Call this function to transition from a non-editing state into an editing 579 * state, if the cell is editable. If this cell is already in an editing 580 * state, it will stay in it. 581 */ 582 public void startEdit() { 583 if (isEditable() && !isEditing() && !isEmpty()) { 584 setEditing(true); 585 } 586 } 587 588 /** 589 * Call this function to transition from an editing state into a non-editing 590 * state, without saving any user input. 591 */ 592 public void cancelEdit() { 593 if (isEditing()) { 594 setEditing(false); 595 } 596 } 597 598 /** 599 * Call this function when appropriate (based on the user interaction requirements 600 * of your cell editing user interface) to do two things: 601 * 602 * <ol> 603 * <li>Fire the appropriate events back to the backing UI control (e.g. 604 * {@link ListView}). This will begin the process of pushing this edit 605 * back to the relevant data source / property (although it does not 606 * guarantee that this will be successful - that is dependent upon the 607 * specific edit commit handler being used). Refer to the UI control 608 * class javadoc for more detail.</li> 609 * <li>Begin the transition from an editing state into a non-editing state.</li> 610 * </ol> 611 * 612 * <p>In general there is no need to override this method in custom cell 613 * implementations - it should be sufficient to simply call this method 614 * when appropriate (e.g. when the user pressed the Enter key, you may do something 615 * like {@code cell.commitEdit(converter.fromString(textField.getText()));}</p> 616 * 617 * @param newValue The value as input by the end user, which should be 618 * persisted in the relevant way given the data source underpinning the 619 * user interface and the install edit commit handler of the UI control. 620 */ 621 public void commitEdit(T newValue) { 622 if (isEditing()) { 623 setEditing(false); 624 } 625 } 626 627 /** {@inheritDoc} */ 628 @Override protected void layoutChildren() { 629 if (itemDirty) { 630 updateItem(getItem(), isEmpty()); 631 itemDirty = false; 632 } 633 super.layoutChildren(); 634 } 635 636 637 638 /*************************************************************************** 639 * * 640 * Expert API * 641 * * 642 **************************************************************************/ 643 644 /** 645 * The updateItem method should not be called by developers, but it is the 646 * best method for developers to override to allow for them to customise the 647 * visuals of the cell. To clarify, developers should never call this method 648 * in their code (they should leave it up to the UI control, such as the 649 * {@link javafx.scene.control.ListView} control) to call this method. However, 650 * the purpose of having the updateItem method is so that developers, when 651 * specifying custom cell factories (again, like the ListView 652 * {@link javafx.scene.control.ListView#cellFactoryProperty() cell factory}), 653 * the updateItem method can be overridden to allow for complete customisation 654 * of the cell. 655 * 656 * <p>It is <strong>very important</strong> that subclasses 657 * of Cell override the updateItem method properly, as failure to do so will 658 * lead to issues such as blank cells or cells with unexpected content 659 * appearing within them. Here is an example of how to properly override the 660 * updateItem method: 661 * 662 * <pre> 663 * protected void updateItem(T item, boolean empty) { 664 * super.updateItem(item, empty); 665 * 666 * if (empty || item == null) { 667 * setText(null); 668 * setGraphic(null); 669 * } else { 670 * setText(item.toString()); 671 * } 672 * } 673 * </pre> 674 * 675 * <p>Note in this code sample two important points: 676 * <ol> 677 * <li>We call the super.updateItem(T, boolean) method. If this is not 678 * done, the item and empty properties are not correctly set, and you are 679 * likely to end up with graphical issues.</li> 680 * <li>We test for the <code>empty</code> condition, and if true, we 681 * set the text and graphic properties to null. If we do not do this, 682 * it is almost guaranteed that end users will see graphical artifacts 683 * in cells unexpectedly.</li> 684 * </ol> 685 * 686 * @param item The new item for the cell. 687 * @param empty whether or not this cell represents data from the list. If it 688 * is empty, then it does not represent any domain data, but is a cell 689 * being used to render an "empty" row. 690 */ 691 protected void updateItem(T item, boolean empty) { 692 setItem(item); 693 setEmpty(empty); 694 if (empty && isSelected()) { 695 updateSelected(false); 696 } 697 } 698 699 /** 700 * Updates whether this cell is in a selected state or not. 701 * @param selected whether or not to select this cell. 702 */ 703 public void updateSelected(boolean selected) { 704 if (selected && isEmpty()) return; 705 boolean wasSelected = isSelected(); 706 setSelected(selected); 707 708 if (wasSelected != selected) { 709 markCellDirty(); 710 } 711 } 712 713 /** 714 * This method is called by Cell subclasses so that certain CPU-intensive 715 * actions (specifically, calling {@link #updateItem(Object, boolean)}) are 716 * only performed when necessary (that is, they are only performed 717 * when the currently set {@link #itemProperty() item} is considered to be 718 * different than the proposed new item that could be set). 719 * 720 * <p>The default implementation of this method tests against equality, but 721 * developers are able to override this method to perform checks in other ways 722 * that are specific to their domain.</p> 723 * 724 * @param oldItem The currently-set item contained within the cell (i.e. it is 725 * the same as what is available via {@link #getItem()}). 726 * @param newItem The item that will be set in the cell, if this method 727 * returns true. If this method returns false, it may not be 728 * set. 729 * @return Returns true if the new item is considered to be different than 730 * the old item. By default this method tests against equality, but 731 * subclasses may alter the implementation to test appropriate to 732 * their needs. 733 * @since JavaFX 8u40 734 */ 735 protected boolean isItemChanged(T oldItem, T newItem) { 736 return oldItem != null ? !oldItem.equals(newItem) : newItem != null; 737 } 738 739 740 741 /*************************************************************************** 742 * * 743 * Private Implementation * 744 * * 745 **************************************************************************/ 746 747 // itemDirty and markCellDirty introduced as a solution for JDK-8145588. 748 // In the fullness of time, a more fully developed solution can be developed 749 // that offers a public API around this lazy-dirty impl. 750 private boolean itemDirty = false; 751 private final void markCellDirty() { 752 itemDirty = true; 753 requestLayout(); 754 } 755 756 757 /*************************************************************************** 758 * * 759 * Stylesheet Handling * 760 * * 761 **************************************************************************/ 762 763 private static final String DEFAULT_STYLE_CLASS = "cell"; 764 private static final PseudoClass PSEUDO_CLASS_SELECTED = 765 PseudoClass.getPseudoClass("selected"); 766 private static final PseudoClass PSEUDO_CLASS_FOCUSED = 767 PseudoClass.getPseudoClass("focused"); 768 private static final PseudoClass PSEUDO_CLASS_EMPTY = 769 PseudoClass.getPseudoClass("empty"); 770 private static final PseudoClass PSEUDO_CLASS_FILLED = 771 PseudoClass.getPseudoClass("filled"); 772 773 /** 774 * Returns the initial focus traversable state of this control, for use 775 * by the JavaFX CSS engine to correctly set its initial value. This method 776 * is overridden as by default UI controls have focus traversable set to true, 777 * but that is not appropriate for this control. 778 * 779 * @since 9 780 */ 781 @Override protected Boolean getInitialFocusTraversable() { 782 return Boolean.FALSE; 783 } 784 }