1 /* 2 * Copyright (c) 1997, 2017, 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 package javax.swing; 26 27 import java.awt.*; 28 import java.awt.event.*; 29 30 import java.util.Vector; 31 import java.util.Locale; 32 import java.util.ArrayList; 33 import java.util.Collections; 34 import java.util.List; 35 36 import java.beans.JavaBean; 37 import java.beans.BeanProperty; 38 import java.beans.PropertyChangeEvent; 39 import java.beans.PropertyChangeListener; 40 import java.beans.Transient; 41 42 import javax.swing.event.*; 43 import javax.accessibility.*; 44 import javax.swing.plaf.*; 45 import javax.swing.text.Position; 46 47 import java.io.ObjectOutputStream; 48 import java.io.IOException; 49 import java.io.Serializable; 50 51 import sun.swing.SwingUtilities2; 52 import sun.swing.SwingUtilities2.Section; 53 import static sun.swing.SwingUtilities2.Section.*; 54 55 /** 56 * A component that displays a list of objects and allows the user to select 57 * one or more items. A separate model, {@code ListModel}, maintains the 58 * contents of the list. 59 * <p> 60 * It's easy to display an array or Vector of objects, using the {@code JList} 61 * constructor that automatically builds a read-only {@code ListModel} instance 62 * for you: 63 * <pre> 64 * {@code 65 * // Create a JList that displays strings from an array 66 * 67 * String[] data = {"one", "two", "three", "four"}; 68 * JList<String> myList = new JList<String>(data); 69 * 70 * // Create a JList that displays the superclasses of JList.class, by 71 * // creating it with a Vector populated with this data 72 * 73 * Vector<Class<?>> superClasses = new Vector<Class<?>>(); 74 * Class<JList> rootClass = javax.swing.JList.class; 75 * for(Class<?> cls = rootClass; cls != null; cls = cls.getSuperclass()) { 76 * superClasses.addElement(cls); 77 * } 78 * JList<Class<?>> myList = new JList<Class<?>>(superClasses); 79 * 80 * // The automatically created model is stored in JList's "model" 81 * // property, which you can retrieve 82 * 83 * ListModel<Class<?>> model = myList.getModel(); 84 * for(int i = 0; i < model.getSize(); i++) { 85 * System.out.println(model.getElementAt(i)); 86 * } 87 * } 88 * </pre> 89 * <p> 90 * A {@code ListModel} can be supplied directly to a {@code JList} by way of a 91 * constructor or the {@code setModel} method. The contents need not be static - 92 * the number of items, and the values of items can change over time. A correct 93 * {@code ListModel} implementation notifies the set of 94 * {@code javax.swing.event.ListDataListener}s that have been added to it, each 95 * time a change occurs. These changes are characterized by a 96 * {@code javax.swing.event.ListDataEvent}, which identifies the range of list 97 * indices that have been modified, added, or removed. {@code JList}'s 98 * {@code ListUI} is responsible for keeping the visual representation up to 99 * date with changes, by listening to the model. 100 * <p> 101 * Simple, dynamic-content, {@code JList} applications can use the 102 * {@code DefaultListModel} class to maintain list elements. This class 103 * implements the {@code ListModel} interface and also provides a 104 * <code>java.util.Vector</code>-like API. Applications that need a more 105 * custom <code>ListModel</code> implementation may instead wish to subclass 106 * {@code AbstractListModel}, which provides basic support for managing and 107 * notifying listeners. For example, a read-only implementation of 108 * {@code AbstractListModel}: 109 * <pre> 110 * {@code 111 * // This list model has about 2^16 elements. Enjoy scrolling. 112 * 113 * ListModel<String> bigData = new AbstractListModel<String>() { 114 * public int getSize() { return Short.MAX_VALUE; } 115 * public String getElementAt(int index) { return "Index " + index; } 116 * }; 117 * } 118 * </pre> 119 * <p> 120 * The selection state of a {@code JList} is managed by another separate 121 * model, an instance of {@code ListSelectionModel}. {@code JList} is 122 * initialized with a selection model on construction, and also contains 123 * methods to query or set this selection model. Additionally, {@code JList} 124 * provides convenient methods for easily managing the selection. These methods, 125 * such as {@code setSelectedIndex} and {@code getSelectedValue}, are cover 126 * methods that take care of the details of interacting with the selection 127 * model. By default, {@code JList}'s selection model is configured to allow any 128 * combination of items to be selected at a time; selection mode 129 * {@code MULTIPLE_INTERVAL_SELECTION}. The selection mode can be changed 130 * on the selection model directly, or via {@code JList}'s cover method. 131 * Responsibility for updating the selection model in response to user gestures 132 * lies with the list's {@code ListUI}. 133 * <p> 134 * A correct {@code ListSelectionModel} implementation notifies the set of 135 * {@code javax.swing.event.ListSelectionListener}s that have been added to it 136 * each time a change to the selection occurs. These changes are characterized 137 * by a {@code javax.swing.event.ListSelectionEvent}, which identifies the range 138 * of the selection change. 139 * <p> 140 * The preferred way to listen for changes in list selection is to add 141 * {@code ListSelectionListener}s directly to the {@code JList}. {@code JList} 142 * then takes care of listening to the selection model and notifying your 143 * listeners of change. 144 * <p> 145 * Responsibility for listening to selection changes in order to keep the list's 146 * visual representation up to date lies with the list's {@code ListUI}. 147 * <p> 148 * <a id="renderer"></a> 149 * Painting of cells in a {@code JList} is handled by a delegate called a 150 * cell renderer, installed on the list as the {@code cellRenderer} property. 151 * The renderer provides a {@code java.awt.Component} that is used 152 * like a "rubber stamp" to paint the cells. Each time a cell needs to be 153 * painted, the list's {@code ListUI} asks the cell renderer for the component, 154 * moves it into place, and has it paint the contents of the cell by way of its 155 * {@code paint} method. A default cell renderer, which uses a {@code JLabel} 156 * component to render, is installed by the lists's {@code ListUI}. You can 157 * substitute your own renderer using code like this: 158 * <pre> 159 * {@code 160 * // Display an icon and a string for each object in the list. 161 * 162 * class MyCellRenderer extends JLabel implements ListCellRenderer<Object> { 163 * static final ImageIcon longIcon = new ImageIcon("long.gif"); 164 * static final ImageIcon shortIcon = new ImageIcon("short.gif"); 165 * 166 * // This is the only method defined by ListCellRenderer. 167 * // We just reconfigure the JLabel each time we're called. 168 * 169 * public Component getListCellRendererComponent( 170 * JList<?> list, // the list 171 * Object value, // value to display 172 * int index, // cell index 173 * boolean isSelected, // is the cell selected 174 * boolean cellHasFocus) // does the cell have focus 175 * { 176 * String s = value.toString(); 177 * setText(s); 178 * setIcon((s.length() > 10) ? longIcon : shortIcon); 179 * if (isSelected) { 180 * setBackground(list.getSelectionBackground()); 181 * setForeground(list.getSelectionForeground()); 182 * } else { 183 * setBackground(list.getBackground()); 184 * setForeground(list.getForeground()); 185 * } 186 * setEnabled(list.isEnabled()); 187 * setFont(list.getFont()); 188 * setOpaque(true); 189 * return this; 190 * } 191 * } 192 * 193 * myList.setCellRenderer(new MyCellRenderer()); 194 * } 195 * </pre> 196 * <p> 197 * Another job for the cell renderer is in helping to determine sizing 198 * information for the list. By default, the list's {@code ListUI} determines 199 * the size of cells by asking the cell renderer for its preferred 200 * size for each list item. This can be expensive for large lists of items. 201 * To avoid these calculations, you can set a {@code fixedCellWidth} and 202 * {@code fixedCellHeight} on the list, or have these values calculated 203 * automatically based on a single prototype value: 204 * <a id="prototype_example"></a> 205 * <pre> 206 * {@code 207 * JList<String> bigDataList = new JList<String>(bigData); 208 * 209 * // We don't want the JList implementation to compute the width 210 * // or height of all of the list cells, so we give it a string 211 * // that's as big as we'll need for any cell. It uses this to 212 * // compute values for the fixedCellWidth and fixedCellHeight 213 * // properties. 214 * 215 * bigDataList.setPrototypeCellValue("Index 1234567890"); 216 * } 217 * </pre> 218 * <p> 219 * {@code JList} doesn't implement scrolling directly. To create a list that 220 * scrolls, make it the viewport view of a {@code JScrollPane}. For example: 221 * <pre> 222 * JScrollPane scrollPane = new JScrollPane(myList); 223 * 224 * // Or in two steps: 225 * JScrollPane scrollPane = new JScrollPane(); 226 * scrollPane.getViewport().setView(myList); 227 * </pre> 228 * <p> 229 * {@code JList} doesn't provide any special handling of double or triple 230 * (or N) mouse clicks, but it's easy to add a {@code MouseListener} if you 231 * wish to take action on these events. Use the {@code locationToIndex} 232 * method to determine what cell was clicked. For example: 233 * <pre> 234 * MouseListener mouseListener = new MouseAdapter() { 235 * public void mouseClicked(MouseEvent e) { 236 * if (e.getClickCount() == 2) { 237 * int index = list.locationToIndex(e.getPoint()); 238 * System.out.println("Double clicked on Item " + index); 239 * } 240 * } 241 * }; 242 * list.addMouseListener(mouseListener); 243 * </pre> 244 * <p> 245 * <strong>Warning:</strong> Swing is not thread safe. For more 246 * information see <a 247 * href="package-summary.html#threading">Swing's Threading 248 * Policy</a>. 249 * <p> 250 * <strong>Warning:</strong> 251 * Serialized objects of this class will not be compatible with 252 * future Swing releases. The current serialization support is 253 * appropriate for short term storage or RMI between applications running 254 * the same version of Swing. As of 1.4, support for long term storage 255 * of all JavaBeans™ 256 * has been added to the <code>java.beans</code> package. 257 * Please see {@link java.beans.XMLEncoder}. 258 * <p> 259 * See <a href="http://docs.oracle.com/javase/tutorial/uiswing/components/list.html">How to Use Lists</a> 260 * in <a href="http://docs.oracle.com/javase/tutorial/"><em>The Java Tutorial</em></a> 261 * for further documentation. 262 * 263 * @see ListModel 264 * @see AbstractListModel 265 * @see DefaultListModel 266 * @see ListSelectionModel 267 * @see DefaultListSelectionModel 268 * @see ListCellRenderer 269 * @see DefaultListCellRenderer 270 * 271 * @param <E> the type of the elements of this list 272 * 273 * @author Hans Muller 274 * @since 1.2 275 */ 276 @JavaBean(defaultProperty = "UI", description = "A component which allows for the selection of one or more objects from a list.") 277 @SwingContainer(false) 278 @SuppressWarnings("serial") // Same-version serialization only 279 public class JList<E> extends JComponent implements Scrollable, Accessible 280 { 281 /** 282 * @see #getUIClassID 283 * @see #readObject 284 */ 285 private static final String uiClassID = "ListUI"; 286 287 /** 288 * Indicates a vertical layout of cells, in a single column; 289 * the default layout. 290 * @see #setLayoutOrientation 291 * @since 1.4 292 */ 293 public static final int VERTICAL = 0; 294 295 /** 296 * Indicates a "newspaper style" layout with cells flowing vertically 297 * then horizontally. 298 * @see #setLayoutOrientation 299 * @since 1.4 300 */ 301 public static final int VERTICAL_WRAP = 1; 302 303 /** 304 * Indicates a "newspaper style" layout with cells flowing horizontally 305 * then vertically. 306 * @see #setLayoutOrientation 307 * @since 1.4 308 */ 309 public static final int HORIZONTAL_WRAP = 2; 310 311 private int fixedCellWidth = -1; 312 private int fixedCellHeight = -1; 313 private int horizontalScrollIncrement = -1; 314 private E prototypeCellValue; 315 private int visibleRowCount = 8; 316 private Color selectionForeground; 317 private Color selectionBackground; 318 private boolean dragEnabled; 319 320 private ListSelectionModel selectionModel; 321 private ListModel<E> dataModel; 322 private ListCellRenderer<? super E> cellRenderer; 323 private ListSelectionListener selectionListener; 324 325 /** 326 * How to lay out the cells; defaults to <code>VERTICAL</code>. 327 */ 328 private int layoutOrientation; 329 330 /** 331 * The drop mode for this component. 332 */ 333 private DropMode dropMode = DropMode.USE_SELECTION; 334 335 /** 336 * The drop location. 337 */ 338 private transient DropLocation dropLocation; 339 340 /** 341 * Flag to indicate UI update is in progress 342 */ 343 private transient boolean updateInProgress; 344 345 /** 346 * A subclass of <code>TransferHandler.DropLocation</code> representing 347 * a drop location for a <code>JList</code>. 348 * 349 * @see #getDropLocation 350 * @since 1.6 351 */ 352 public static final class DropLocation extends TransferHandler.DropLocation { 353 private final int index; 354 private final boolean isInsert; 355 356 private DropLocation(Point p, int index, boolean isInsert) { 357 super(p); 358 this.index = index; 359 this.isInsert = isInsert; 360 } 361 362 /** 363 * Returns the index where dropped data should be placed in the 364 * list. Interpretation of the value depends on the drop mode set on 365 * the associated component. If the drop mode is either 366 * <code>DropMode.USE_SELECTION</code> or <code>DropMode.ON</code>, 367 * the return value is an index of a row in the list. If the drop mode is 368 * <code>DropMode.INSERT</code>, the return value refers to the index 369 * where the data should be inserted. If the drop mode is 370 * <code>DropMode.ON_OR_INSERT</code>, the value of 371 * <code>isInsert()</code> indicates whether the index is an index 372 * of a row, or an insert index. 373 * <p> 374 * <code>-1</code> indicates that the drop occurred over empty space, 375 * and no index could be calculated. 376 * 377 * @return the drop index 378 */ 379 public int getIndex() { 380 return index; 381 } 382 383 /** 384 * Returns whether or not this location represents an insert 385 * location. 386 * 387 * @return whether or not this is an insert location 388 */ 389 public boolean isInsert() { 390 return isInsert; 391 } 392 393 /** 394 * Returns a string representation of this drop location. 395 * This method is intended to be used for debugging purposes, 396 * and the content and format of the returned string may vary 397 * between implementations. 398 * 399 * @return a string representation of this drop location 400 */ 401 public String toString() { 402 return getClass().getName() 403 + "[dropPoint=" + getDropPoint() + "," 404 + "index=" + index + "," 405 + "insert=" + isInsert + "]"; 406 } 407 } 408 409 /** 410 * Constructs a {@code JList} that displays elements from the specified, 411 * {@code non-null}, model. All {@code JList} constructors delegate to 412 * this one. 413 * <p> 414 * This constructor registers the list with the {@code ToolTipManager}, 415 * allowing for tooltips to be provided by the cell renderers. 416 * 417 * @param dataModel the model for the list 418 * @exception IllegalArgumentException if the model is {@code null} 419 */ 420 public JList(ListModel<E> dataModel) 421 { 422 if (dataModel == null) { 423 throw new IllegalArgumentException("dataModel must be non null"); 424 } 425 426 // Register with the ToolTipManager so that tooltips from the 427 // renderer show through. 428 ToolTipManager toolTipManager = ToolTipManager.sharedInstance(); 429 toolTipManager.registerComponent(this); 430 431 layoutOrientation = VERTICAL; 432 433 this.dataModel = dataModel; 434 selectionModel = createSelectionModel(); 435 setAutoscrolls(true); 436 setOpaque(true); 437 updateUI(); 438 } 439 440 441 /** 442 * Constructs a <code>JList</code> that displays the elements in 443 * the specified array. This constructor creates a read-only model 444 * for the given array, and then delegates to the constructor that 445 * takes a {@code ListModel}. 446 * <p> 447 * Attempts to pass a {@code null} value to this method results in 448 * undefined behavior and, most likely, exceptions. The created model 449 * references the given array directly. Attempts to modify the array 450 * after constructing the list results in undefined behavior. 451 * 452 * @param listData the array of Objects to be loaded into the data model, 453 * {@code non-null} 454 */ 455 public JList(final E[] listData) 456 { 457 this ( 458 new AbstractListModel<E>() { 459 public int getSize() { return listData.length; } 460 public E getElementAt(int i) { return listData[i]; } 461 } 462 ); 463 } 464 465 466 /** 467 * Constructs a <code>JList</code> that displays the elements in 468 * the specified <code>Vector</code>. This constructor creates a read-only 469 * model for the given {@code Vector}, and then delegates to the constructor 470 * that takes a {@code ListModel}. 471 * <p> 472 * Attempts to pass a {@code null} value to this method results in 473 * undefined behavior and, most likely, exceptions. The created model 474 * references the given {@code Vector} directly. Attempts to modify the 475 * {@code Vector} after constructing the list results in undefined behavior. 476 * 477 * @param listData the <code>Vector</code> to be loaded into the 478 * data model, {@code non-null} 479 */ 480 public JList(final Vector<? extends E> listData) { 481 this ( 482 new AbstractListModel<E>() { 483 public int getSize() { return listData.size(); } 484 public E getElementAt(int i) { return listData.elementAt(i); } 485 } 486 ); 487 } 488 489 490 /** 491 * Constructs a <code>JList</code> with an empty, read-only, model. 492 */ 493 public JList() { 494 this ( 495 new AbstractListModel<E>() { 496 public int getSize() { return 0; } 497 public E getElementAt(int i) { throw new IndexOutOfBoundsException("No Data Model"); } 498 } 499 ); 500 } 501 502 503 /** 504 * Returns the {@code ListUI}, the look and feel object that 505 * renders this component. 506 * 507 * @return the <code>ListUI</code> object that renders this component 508 */ 509 public ListUI getUI() { 510 return (ListUI)ui; 511 } 512 513 514 /** 515 * Sets the {@code ListUI}, the look and feel object that 516 * renders this component. 517 * 518 * @param ui the <code>ListUI</code> object 519 * @see UIDefaults#getUI 520 */ 521 @BeanProperty(hidden = true, visualUpdate = true, description 522 = "The UI object that implements the Component's LookAndFeel.") 523 public void setUI(ListUI ui) { 524 super.setUI(ui); 525 } 526 527 528 /** 529 * Resets the {@code ListUI} property by setting it to the value provided 530 * by the current look and feel. If the current cell renderer was installed 531 * by the developer (rather than the look and feel itself), this also causes 532 * the cell renderer and its children to be updated, by calling 533 * {@code SwingUtilities.updateComponentTreeUI} on it. 534 * 535 * @see UIManager#getUI 536 * @see SwingUtilities#updateComponentTreeUI 537 */ 538 public void updateUI() { 539 if (!updateInProgress) { 540 updateInProgress = true; 541 try { 542 setUI((ListUI)UIManager.getUI(this)); 543 544 ListCellRenderer<? super E> renderer = getCellRenderer(); 545 if (renderer instanceof Component) { 546 SwingUtilities.updateComponentTreeUI((Component)renderer); 547 } 548 } finally { 549 updateInProgress = false; 550 } 551 } 552 } 553 554 555 /** 556 * Returns {@code "ListUI"}, the <code>UIDefaults</code> key used to look 557 * up the name of the {@code javax.swing.plaf.ListUI} class that defines 558 * the look and feel for this component. 559 * 560 * @return the string "ListUI" 561 * @see JComponent#getUIClassID 562 * @see UIDefaults#getUI 563 */ 564 @BeanProperty(bound = false) 565 public String getUIClassID() { 566 return uiClassID; 567 } 568 569 570 /* -----private----- 571 * This method is called by setPrototypeCellValue and setCellRenderer 572 * to update the fixedCellWidth and fixedCellHeight properties from the 573 * current value of prototypeCellValue (if it's non null). 574 * <p> 575 * This method sets fixedCellWidth and fixedCellHeight but does <b>not</b> 576 * generate PropertyChangeEvents for them. 577 * 578 * @see #setPrototypeCellValue 579 * @see #setCellRenderer 580 */ 581 private void updateFixedCellSize() 582 { 583 ListCellRenderer<? super E> cr = getCellRenderer(); 584 E value = getPrototypeCellValue(); 585 586 if ((cr != null) && (value != null)) { 587 Component c = cr.getListCellRendererComponent(this, value, 0, false, false); 588 589 /* The ListUI implementation will add Component c to its private 590 * CellRendererPane however we can't assume that's already 591 * been done here. So we temporarily set the one "inherited" 592 * property that may affect the renderer components preferred size: 593 * its font. 594 */ 595 Font f = c.getFont(); 596 c.setFont(getFont()); 597 598 Dimension d = c.getPreferredSize(); 599 fixedCellWidth = d.width; 600 fixedCellHeight = d.height; 601 602 c.setFont(f); 603 } 604 } 605 606 607 /** 608 * Returns the "prototypical" cell value -- a value used to calculate a 609 * fixed width and height for cells. This can be {@code null} if there 610 * is no such value. 611 * 612 * @return the value of the {@code prototypeCellValue} property 613 * @see #setPrototypeCellValue 614 */ 615 public E getPrototypeCellValue() { 616 return prototypeCellValue; 617 } 618 619 /** 620 * Sets the {@code prototypeCellValue} property, and then (if the new value 621 * is {@code non-null}), computes the {@code fixedCellWidth} and 622 * {@code fixedCellHeight} properties by requesting the cell renderer 623 * component for the given value (and index 0) from the cell renderer, and 624 * using that component's preferred size. 625 * <p> 626 * This method is useful when the list is too long to allow the 627 * {@code ListUI} to compute the width/height of each cell, and there is a 628 * single cell value that is known to occupy as much space as any of the 629 * others, a so-called prototype. 630 * <p> 631 * While all three of the {@code prototypeCellValue}, 632 * {@code fixedCellHeight}, and {@code fixedCellWidth} properties may be 633 * modified by this method, {@code PropertyChangeEvent} notifications are 634 * only sent when the {@code prototypeCellValue} property changes. 635 * <p> 636 * To see an example which sets this property, see the 637 * <a href="#prototype_example">class description</a> above. 638 * <p> 639 * The default value of this property is <code>null</code>. 640 * <p> 641 * This is a JavaBeans bound property. 642 * 643 * @param prototypeCellValue the value on which to base 644 * <code>fixedCellWidth</code> and 645 * <code>fixedCellHeight</code> 646 * @see #getPrototypeCellValue 647 * @see #setFixedCellWidth 648 * @see #setFixedCellHeight 649 * @see JComponent#addPropertyChangeListener 650 */ 651 @BeanProperty(visualUpdate = true, description 652 = "The cell prototype value, used to compute cell width and height.") 653 public void setPrototypeCellValue(E prototypeCellValue) { 654 E oldValue = this.prototypeCellValue; 655 this.prototypeCellValue = prototypeCellValue; 656 657 /* If the prototypeCellValue has changed and is non-null, 658 * then recompute fixedCellWidth and fixedCellHeight. 659 */ 660 661 if ((prototypeCellValue != null) && !prototypeCellValue.equals(oldValue)) { 662 updateFixedCellSize(); 663 } 664 665 firePropertyChange("prototypeCellValue", oldValue, prototypeCellValue); 666 } 667 668 669 /** 670 * Returns the value of the {@code fixedCellWidth} property. 671 * 672 * @return the fixed cell width 673 * @see #setFixedCellWidth 674 */ 675 public int getFixedCellWidth() { 676 return fixedCellWidth; 677 } 678 679 /** 680 * Sets a fixed value to be used for the width of every cell in the list. 681 * If {@code width} is -1, cell widths are computed in the {@code ListUI} 682 * by applying <code>getPreferredSize</code> to the cell renderer component 683 * for each list element. 684 * <p> 685 * The default value of this property is {@code -1}. 686 * <p> 687 * This is a JavaBeans bound property. 688 * 689 * @param width the width to be used for all cells in the list 690 * @see #setPrototypeCellValue 691 * @see #setFixedCellWidth 692 * @see JComponent#addPropertyChangeListener 693 */ 694 @BeanProperty(visualUpdate = true, description 695 = "Defines a fixed cell width when greater than zero.") 696 public void setFixedCellWidth(int width) { 697 int oldValue = fixedCellWidth; 698 fixedCellWidth = width; 699 firePropertyChange("fixedCellWidth", oldValue, fixedCellWidth); 700 } 701 702 703 /** 704 * Returns the value of the {@code fixedCellHeight} property. 705 * 706 * @return the fixed cell height 707 * @see #setFixedCellHeight 708 */ 709 public int getFixedCellHeight() { 710 return fixedCellHeight; 711 } 712 713 /** 714 * Sets a fixed value to be used for the height of every cell in the list. 715 * If {@code height} is -1, cell heights are computed in the {@code ListUI} 716 * by applying <code>getPreferredSize</code> to the cell renderer component 717 * for each list element. 718 * <p> 719 * The default value of this property is {@code -1}. 720 * <p> 721 * This is a JavaBeans bound property. 722 * 723 * @param height the height to be used for all cells in the list 724 * @see #setPrototypeCellValue 725 * @see #setFixedCellWidth 726 * @see JComponent#addPropertyChangeListener 727 */ 728 @BeanProperty(visualUpdate = true, description 729 = "Defines a fixed cell height when greater than zero.") 730 public void setFixedCellHeight(int height) { 731 int oldValue = fixedCellHeight; 732 fixedCellHeight = height; 733 firePropertyChange("fixedCellHeight", oldValue, fixedCellHeight); 734 } 735 736 737 /** 738 * Returns the object responsible for painting list items. 739 * 740 * @return the value of the {@code cellRenderer} property 741 * @see #setCellRenderer 742 */ 743 @Transient 744 public ListCellRenderer<? super E> getCellRenderer() { 745 return cellRenderer; 746 } 747 748 /** 749 * Sets the delegate that is used to paint each cell in the list. 750 * The job of a cell renderer is discussed in detail in the 751 * <a href="#renderer">class level documentation</a>. 752 * <p> 753 * If the {@code prototypeCellValue} property is {@code non-null}, 754 * setting the cell renderer also causes the {@code fixedCellWidth} and 755 * {@code fixedCellHeight} properties to be re-calculated. Only one 756 * <code>PropertyChangeEvent</code> is generated however - 757 * for the <code>cellRenderer</code> property. 758 * <p> 759 * The default value of this property is provided by the {@code ListUI} 760 * delegate, i.e. by the look and feel implementation. 761 * <p> 762 * This is a JavaBeans bound property. 763 * 764 * @param cellRenderer the <code>ListCellRenderer</code> 765 * that paints list cells 766 * @see #getCellRenderer 767 */ 768 @BeanProperty(visualUpdate = true, description 769 = "The component used to draw the cells.") 770 public void setCellRenderer(ListCellRenderer<? super E> cellRenderer) { 771 ListCellRenderer<? super E> oldValue = this.cellRenderer; 772 this.cellRenderer = cellRenderer; 773 774 /* If the cellRenderer has changed and prototypeCellValue 775 * was set, then recompute fixedCellWidth and fixedCellHeight. 776 */ 777 if ((cellRenderer != null) && !cellRenderer.equals(oldValue)) { 778 updateFixedCellSize(); 779 } 780 781 firePropertyChange("cellRenderer", oldValue, cellRenderer); 782 } 783 784 785 /** 786 * Returns the color used to draw the foreground of selected items. 787 * {@code DefaultListCellRenderer} uses this color to draw the foreground 788 * of items in the selected state, as do the renderers installed by most 789 * {@code ListUI} implementations. 790 * 791 * @return the color to draw the foreground of selected items 792 * @see #setSelectionForeground 793 * @see DefaultListCellRenderer 794 */ 795 public Color getSelectionForeground() { 796 return selectionForeground; 797 } 798 799 800 /** 801 * Sets the color used to draw the foreground of selected items, which 802 * cell renderers can use to render text and graphics. 803 * {@code DefaultListCellRenderer} uses this color to draw the foreground 804 * of items in the selected state, as do the renderers installed by most 805 * {@code ListUI} implementations. 806 * <p> 807 * The default value of this property is defined by the look and feel 808 * implementation. 809 * <p> 810 * This is a JavaBeans bound property. 811 * 812 * @param selectionForeground the {@code Color} to use in the foreground 813 * for selected list items 814 * @see #getSelectionForeground 815 * @see #setSelectionBackground 816 * @see #setForeground 817 * @see #setBackground 818 * @see #setFont 819 * @see DefaultListCellRenderer 820 */ 821 @BeanProperty(visualUpdate = true, description 822 = "The foreground color of selected cells.") 823 public void setSelectionForeground(Color selectionForeground) { 824 Color oldValue = this.selectionForeground; 825 this.selectionForeground = selectionForeground; 826 firePropertyChange("selectionForeground", oldValue, selectionForeground); 827 } 828 829 830 /** 831 * Returns the color used to draw the background of selected items. 832 * {@code DefaultListCellRenderer} uses this color to draw the background 833 * of items in the selected state, as do the renderers installed by most 834 * {@code ListUI} implementations. 835 * 836 * @return the color to draw the background of selected items 837 * @see #setSelectionBackground 838 * @see DefaultListCellRenderer 839 */ 840 public Color getSelectionBackground() { 841 return selectionBackground; 842 } 843 844 845 /** 846 * Sets the color used to draw the background of selected items, which 847 * cell renderers can use fill selected cells. 848 * {@code DefaultListCellRenderer} uses this color to fill the background 849 * of items in the selected state, as do the renderers installed by most 850 * {@code ListUI} implementations. 851 * <p> 852 * The default value of this property is defined by the look 853 * and feel implementation. 854 * <p> 855 * This is a JavaBeans bound property. 856 * 857 * @param selectionBackground the {@code Color} to use for the 858 * background of selected cells 859 * @see #getSelectionBackground 860 * @see #setSelectionForeground 861 * @see #setForeground 862 * @see #setBackground 863 * @see #setFont 864 * @see DefaultListCellRenderer 865 */ 866 @BeanProperty(visualUpdate = true, description 867 = "The background color of selected cells.") 868 public void setSelectionBackground(Color selectionBackground) { 869 Color oldValue = this.selectionBackground; 870 this.selectionBackground = selectionBackground; 871 firePropertyChange("selectionBackground", oldValue, selectionBackground); 872 } 873 874 875 /** 876 * Returns the value of the {@code visibleRowCount} property. See the 877 * documentation for {@link #setVisibleRowCount} for details on how to 878 * interpret this value. 879 * 880 * @return the value of the {@code visibleRowCount} property. 881 * @see #setVisibleRowCount 882 */ 883 public int getVisibleRowCount() { 884 return visibleRowCount; 885 } 886 887 /** 888 * Sets the {@code visibleRowCount} property, which has different meanings 889 * depending on the layout orientation: For a {@code VERTICAL} layout 890 * orientation, this sets the preferred number of rows to display without 891 * requiring scrolling; for other orientations, it affects the wrapping of 892 * cells. 893 * <p> 894 * In {@code VERTICAL} orientation:<br> 895 * Setting this property affects the return value of the 896 * {@link #getPreferredScrollableViewportSize} method, which is used to 897 * calculate the preferred size of an enclosing viewport. See that method's 898 * documentation for more details. 899 * <p> 900 * In {@code HORIZONTAL_WRAP} and {@code VERTICAL_WRAP} orientations:<br> 901 * This affects how cells are wrapped. See the documentation of 902 * {@link #setLayoutOrientation} for more details. 903 * <p> 904 * The default value of this property is {@code 8}. 905 * <p> 906 * Calling this method with a negative value results in the property 907 * being set to {@code 0}. 908 * <p> 909 * This is a JavaBeans bound property. 910 * 911 * @param visibleRowCount an integer specifying the preferred number of 912 * rows to display without requiring scrolling 913 * @see #getVisibleRowCount 914 * @see #getPreferredScrollableViewportSize 915 * @see #setLayoutOrientation 916 * @see JComponent#getVisibleRect 917 * @see JViewport 918 */ 919 @BeanProperty(visualUpdate = true, description 920 = "The preferred number of rows to display without requiring scrolling") 921 public void setVisibleRowCount(int visibleRowCount) { 922 int oldValue = this.visibleRowCount; 923 this.visibleRowCount = Math.max(0, visibleRowCount); 924 firePropertyChange("visibleRowCount", oldValue, visibleRowCount); 925 } 926 927 928 /** 929 * Returns the layout orientation property for the list: {@code VERTICAL} 930 * if the layout is a single column of cells, {@code VERTICAL_WRAP} if the 931 * layout is "newspaper style" with the content flowing vertically then 932 * horizontally, or {@code HORIZONTAL_WRAP} if the layout is "newspaper 933 * style" with the content flowing horizontally then vertically. 934 * 935 * @return the value of the {@code layoutOrientation} property 936 * @see #setLayoutOrientation 937 * @since 1.4 938 */ 939 public int getLayoutOrientation() { 940 return layoutOrientation; 941 } 942 943 944 /** 945 * Defines the way list cells are layed out. Consider a {@code JList} 946 * with five cells. Cells can be layed out in one of the following ways: 947 * 948 * <pre> 949 * VERTICAL: 0 950 * 1 951 * 2 952 * 3 953 * 4 954 * 955 * HORIZONTAL_WRAP: 0 1 2 956 * 3 4 957 * 958 * VERTICAL_WRAP: 0 3 959 * 1 4 960 * 2 961 * </pre> 962 * <p> 963 * A description of these layouts follows: 964 * 965 * <table class="striped"> 966 * <caption>Describes layouts VERTICAL,HORIZONTAL_WRAP, and VERTICAL_WRAP 967 * </caption> 968 * <thead> 969 * <tr> 970 * <th scope="col">Value 971 * <th scope="col">Description 972 * </thead> 973 * <tbody> 974 * <tr> 975 * <th scope="row">{@code VERTICAL} 976 * <td>Cells are layed out vertically in a single column. 977 * <tr> 978 * <th scope="row">{@code HORIZONTAL_WRAP} 979 * <td>Cells are layed out horizontally, wrapping to a new row as 980 * necessary. If the {@code visibleRowCount} property is less than or 981 * equal to zero, wrapping is determined by the width of the list; 982 * otherwise wrapping is done in such a way as to ensure 983 * {@code visibleRowCount} rows in the list. 984 * <tr> 985 * <th scope="row">{@code VERTICAL_WRAP} 986 * <td>Cells are layed out vertically, wrapping to a new column as 987 * necessary. If the {@code visibleRowCount} property is less than or 988 * equal to zero, wrapping is determined by the height of the list; 989 * otherwise wrapping is done at {@code visibleRowCount} rows. 990 * </tbody> 991 * </table> 992 * 993 * The default value of this property is <code>VERTICAL</code>. 994 * 995 * @param layoutOrientation the new layout orientation, one of: 996 * {@code VERTICAL}, {@code HORIZONTAL_WRAP} or {@code VERTICAL_WRAP} 997 * @see #getLayoutOrientation 998 * @see #setVisibleRowCount 999 * @see #getScrollableTracksViewportHeight 1000 * @see #getScrollableTracksViewportWidth 1001 * @throws IllegalArgumentException if {@code layoutOrientation} isn't one of the 1002 * allowable values 1003 * @since 1.4 1004 */ 1005 @BeanProperty(visualUpdate = true, enumerationValues = { 1006 "JList.VERTICAL", 1007 "JList.HORIZONTAL_WRAP", 1008 "JList.VERTICAL_WRAP"}, description 1009 = "Defines the way list cells are layed out.") 1010 public void setLayoutOrientation(int layoutOrientation) { 1011 int oldValue = this.layoutOrientation; 1012 switch (layoutOrientation) { 1013 case VERTICAL: 1014 case VERTICAL_WRAP: 1015 case HORIZONTAL_WRAP: 1016 this.layoutOrientation = layoutOrientation; 1017 firePropertyChange("layoutOrientation", oldValue, layoutOrientation); 1018 break; 1019 default: 1020 throw new IllegalArgumentException("layoutOrientation must be one of: VERTICAL, HORIZONTAL_WRAP or VERTICAL_WRAP"); 1021 } 1022 } 1023 1024 1025 /** 1026 * Returns the smallest list index that is currently visible. 1027 * In a left-to-right {@code componentOrientation}, the first visible 1028 * cell is found closest to the list's upper-left corner. In right-to-left 1029 * orientation, it is found closest to the upper-right corner. 1030 * If nothing is visible or the list is empty, {@code -1} is returned. 1031 * Note that the returned cell may only be partially visible. 1032 * 1033 * @return the index of the first visible cell 1034 * @see #getLastVisibleIndex 1035 * @see JComponent#getVisibleRect 1036 */ 1037 @BeanProperty(bound = false) 1038 public int getFirstVisibleIndex() { 1039 Rectangle r = getVisibleRect(); 1040 int first; 1041 if (this.getComponentOrientation().isLeftToRight()) { 1042 first = locationToIndex(r.getLocation()); 1043 } else { 1044 first = locationToIndex(new Point((r.x + r.width) - 1, r.y)); 1045 } 1046 if (first != -1) { 1047 Rectangle bounds = getCellBounds(first, first); 1048 if (bounds != null) { 1049 SwingUtilities.computeIntersection(r.x, r.y, r.width, r.height, bounds); 1050 if (bounds.width == 0 || bounds.height == 0) { 1051 first = -1; 1052 } 1053 } 1054 } 1055 return first; 1056 } 1057 1058 1059 /** 1060 * Returns the largest list index that is currently visible. 1061 * If nothing is visible or the list is empty, {@code -1} is returned. 1062 * Note that the returned cell may only be partially visible. 1063 * 1064 * @return the index of the last visible cell 1065 * @see #getFirstVisibleIndex 1066 * @see JComponent#getVisibleRect 1067 */ 1068 @BeanProperty(bound = false) 1069 public int getLastVisibleIndex() { 1070 boolean leftToRight = this.getComponentOrientation().isLeftToRight(); 1071 Rectangle r = getVisibleRect(); 1072 Point lastPoint; 1073 if (leftToRight) { 1074 lastPoint = new Point((r.x + r.width) - 1, (r.y + r.height) - 1); 1075 } else { 1076 lastPoint = new Point(r.x, (r.y + r.height) - 1); 1077 } 1078 int location = locationToIndex(lastPoint); 1079 1080 if (location != -1) { 1081 Rectangle bounds = getCellBounds(location, location); 1082 1083 if (bounds != null) { 1084 SwingUtilities.computeIntersection(r.x, r.y, r.width, r.height, bounds); 1085 if (bounds.width == 0 || bounds.height == 0) { 1086 // Try the top left(LTR) or top right(RTL) corner, and 1087 // then go across checking each cell for HORIZONTAL_WRAP. 1088 // Try the lower left corner, and then go across checking 1089 // each cell for other list layout orientation. 1090 boolean isHorizontalWrap = 1091 (getLayoutOrientation() == HORIZONTAL_WRAP); 1092 Point visibleLocation = isHorizontalWrap ? 1093 new Point(lastPoint.x, r.y) : 1094 new Point(r.x, lastPoint.y); 1095 int last; 1096 int visIndex = -1; 1097 int lIndex = location; 1098 location = -1; 1099 1100 do { 1101 last = visIndex; 1102 visIndex = locationToIndex(visibleLocation); 1103 1104 if (visIndex != -1) { 1105 bounds = getCellBounds(visIndex, visIndex); 1106 if (visIndex != lIndex && bounds != null && 1107 bounds.contains(visibleLocation)) { 1108 location = visIndex; 1109 if (isHorizontalWrap) { 1110 visibleLocation.y = bounds.y + bounds.height; 1111 if (visibleLocation.y >= lastPoint.y) { 1112 // Past visible region, bail. 1113 last = visIndex; 1114 } 1115 } 1116 else { 1117 visibleLocation.x = bounds.x + bounds.width; 1118 if (visibleLocation.x >= lastPoint.x) { 1119 // Past visible region, bail. 1120 last = visIndex; 1121 } 1122 } 1123 1124 } 1125 else { 1126 last = visIndex; 1127 } 1128 } 1129 } while (visIndex != -1 && last != visIndex); 1130 } 1131 } 1132 } 1133 return location; 1134 } 1135 1136 1137 /** 1138 * Scrolls the list within an enclosing viewport to make the specified 1139 * cell completely visible. This calls {@code scrollRectToVisible} with 1140 * the bounds of the specified cell. For this method to work, the 1141 * {@code JList} must be within a <code>JViewport</code>. 1142 * <p> 1143 * If the given index is outside the list's range of cells, this method 1144 * results in nothing. 1145 * 1146 * @param index the index of the cell to make visible 1147 * @see JComponent#scrollRectToVisible 1148 * @see #getVisibleRect 1149 */ 1150 public void ensureIndexIsVisible(int index) { 1151 Rectangle cellBounds = getCellBounds(index, index); 1152 if (cellBounds != null) { 1153 scrollRectToVisible(cellBounds); 1154 } 1155 } 1156 1157 /** 1158 * Turns on or off automatic drag handling. In order to enable automatic 1159 * drag handling, this property should be set to {@code true}, and the 1160 * list's {@code TransferHandler} needs to be {@code non-null}. 1161 * The default value of the {@code dragEnabled} property is {@code false}. 1162 * <p> 1163 * The job of honoring this property, and recognizing a user drag gesture, 1164 * lies with the look and feel implementation, and in particular, the list's 1165 * {@code ListUI}. When automatic drag handling is enabled, most look and 1166 * feels (including those that subclass {@code BasicLookAndFeel}) begin a 1167 * drag and drop operation whenever the user presses the mouse button over 1168 * an item and then moves the mouse a few pixels. Setting this property to 1169 * {@code true} can therefore have a subtle effect on how selections behave. 1170 * <p> 1171 * If a look and feel is used that ignores this property, you can still 1172 * begin a drag and drop operation by calling {@code exportAsDrag} on the 1173 * list's {@code TransferHandler}. 1174 * 1175 * @param b whether or not to enable automatic drag handling 1176 * @exception HeadlessException if 1177 * <code>b</code> is <code>true</code> and 1178 * <code>GraphicsEnvironment.isHeadless()</code> 1179 * returns <code>true</code> 1180 * @see java.awt.GraphicsEnvironment#isHeadless 1181 * @see #getDragEnabled 1182 * @see #setTransferHandler 1183 * @see TransferHandler 1184 * @since 1.4 1185 */ 1186 @BeanProperty(bound = false, description 1187 = "determines whether automatic drag handling is enabled") 1188 public void setDragEnabled(boolean b) { 1189 if (b && GraphicsEnvironment.isHeadless()) { 1190 throw new HeadlessException(); 1191 } 1192 dragEnabled = b; 1193 } 1194 1195 /** 1196 * Returns whether or not automatic drag handling is enabled. 1197 * 1198 * @return the value of the {@code dragEnabled} property 1199 * @see #setDragEnabled 1200 * @since 1.4 1201 */ 1202 public boolean getDragEnabled() { 1203 return dragEnabled; 1204 } 1205 1206 /** 1207 * Sets the drop mode for this component. For backward compatibility, 1208 * the default for this property is <code>DropMode.USE_SELECTION</code>. 1209 * Usage of one of the other modes is recommended, however, for an 1210 * improved user experience. <code>DropMode.ON</code>, for instance, 1211 * offers similar behavior of showing items as selected, but does so without 1212 * affecting the actual selection in the list. 1213 * <p> 1214 * <code>JList</code> supports the following drop modes: 1215 * <ul> 1216 * <li><code>DropMode.USE_SELECTION</code></li> 1217 * <li><code>DropMode.ON</code></li> 1218 * <li><code>DropMode.INSERT</code></li> 1219 * <li><code>DropMode.ON_OR_INSERT</code></li> 1220 * </ul> 1221 * The drop mode is only meaningful if this component has a 1222 * <code>TransferHandler</code> that accepts drops. 1223 * 1224 * @param dropMode the drop mode to use 1225 * @throws IllegalArgumentException if the drop mode is unsupported 1226 * or <code>null</code> 1227 * @see #getDropMode 1228 * @see #getDropLocation 1229 * @see #setTransferHandler 1230 * @see TransferHandler 1231 * @since 1.6 1232 */ 1233 public final void setDropMode(DropMode dropMode) { 1234 if (dropMode != null) { 1235 switch (dropMode) { 1236 case USE_SELECTION: 1237 case ON: 1238 case INSERT: 1239 case ON_OR_INSERT: 1240 this.dropMode = dropMode; 1241 return; 1242 } 1243 } 1244 1245 throw new IllegalArgumentException(dropMode + ": Unsupported drop mode for list"); 1246 } 1247 1248 /** 1249 * Returns the drop mode for this component. 1250 * 1251 * @return the drop mode for this component 1252 * @see #setDropMode 1253 * @since 1.6 1254 */ 1255 public final DropMode getDropMode() { 1256 return dropMode; 1257 } 1258 1259 /** 1260 * Calculates a drop location in this component, representing where a 1261 * drop at the given point should insert data. 1262 * 1263 * @param p the point to calculate a drop location for 1264 * @return the drop location, or <code>null</code> 1265 */ 1266 DropLocation dropLocationForPoint(Point p) { 1267 DropLocation location = null; 1268 Rectangle rect = null; 1269 1270 int index = locationToIndex(p); 1271 if (index != -1) { 1272 rect = getCellBounds(index, index); 1273 } 1274 1275 switch(dropMode) { 1276 case USE_SELECTION: 1277 case ON: 1278 location = new DropLocation(p, 1279 (rect != null && rect.contains(p)) ? index : -1, 1280 false); 1281 1282 break; 1283 case INSERT: 1284 if (index == -1) { 1285 location = new DropLocation(p, getModel().getSize(), true); 1286 break; 1287 } 1288 1289 if (layoutOrientation == HORIZONTAL_WRAP) { 1290 boolean ltr = getComponentOrientation().isLeftToRight(); 1291 1292 if (SwingUtilities2.liesInHorizontal(rect, p, ltr, false) == TRAILING) { 1293 index++; 1294 // special case for below all cells 1295 } else if (index == getModel().getSize() - 1 && p.y >= rect.y + rect.height) { 1296 index++; 1297 } 1298 } else { 1299 if (SwingUtilities2.liesInVertical(rect, p, false) == TRAILING) { 1300 index++; 1301 } 1302 } 1303 1304 location = new DropLocation(p, index, true); 1305 1306 break; 1307 case ON_OR_INSERT: 1308 if (index == -1) { 1309 location = new DropLocation(p, getModel().getSize(), true); 1310 break; 1311 } 1312 1313 boolean between = false; 1314 1315 if (layoutOrientation == HORIZONTAL_WRAP) { 1316 boolean ltr = getComponentOrientation().isLeftToRight(); 1317 1318 Section section = SwingUtilities2.liesInHorizontal(rect, p, ltr, true); 1319 if (section == TRAILING) { 1320 index++; 1321 between = true; 1322 // special case for below all cells 1323 } else if (index == getModel().getSize() - 1 && p.y >= rect.y + rect.height) { 1324 index++; 1325 between = true; 1326 } else if (section == LEADING) { 1327 between = true; 1328 } 1329 } else { 1330 Section section = SwingUtilities2.liesInVertical(rect, p, true); 1331 if (section == LEADING) { 1332 between = true; 1333 } else if (section == TRAILING) { 1334 index++; 1335 between = true; 1336 } 1337 } 1338 1339 location = new DropLocation(p, index, between); 1340 1341 break; 1342 default: 1343 assert false : "Unexpected drop mode"; 1344 } 1345 1346 return location; 1347 } 1348 1349 /** 1350 * Called to set or clear the drop location during a DnD operation. 1351 * In some cases, the component may need to use it's internal selection 1352 * temporarily to indicate the drop location. To help facilitate this, 1353 * this method returns and accepts as a parameter a state object. 1354 * This state object can be used to store, and later restore, the selection 1355 * state. Whatever this method returns will be passed back to it in 1356 * future calls, as the state parameter. If it wants the DnD system to 1357 * continue storing the same state, it must pass it back every time. 1358 * Here's how this is used: 1359 * <p> 1360 * Let's say that on the first call to this method the component decides 1361 * to save some state (because it is about to use the selection to show 1362 * a drop index). It can return a state object to the caller encapsulating 1363 * any saved selection state. On a second call, let's say the drop location 1364 * is being changed to something else. The component doesn't need to 1365 * restore anything yet, so it simply passes back the same state object 1366 * to have the DnD system continue storing it. Finally, let's say this 1367 * method is messaged with <code>null</code>. This means DnD 1368 * is finished with this component for now, meaning it should restore 1369 * state. At this point, it can use the state parameter to restore 1370 * said state, and of course return <code>null</code> since there's 1371 * no longer anything to store. 1372 * 1373 * @param location the drop location (as calculated by 1374 * <code>dropLocationForPoint</code>) or <code>null</code> 1375 * if there's no longer a valid drop location 1376 * @param state the state object saved earlier for this component, 1377 * or <code>null</code> 1378 * @param forDrop whether or not the method is being called because an 1379 * actual drop occurred 1380 * @return any saved state for this component, or <code>null</code> if none 1381 */ 1382 Object setDropLocation(TransferHandler.DropLocation location, 1383 Object state, 1384 boolean forDrop) { 1385 1386 Object retVal = null; 1387 DropLocation listLocation = (DropLocation)location; 1388 1389 if (dropMode == DropMode.USE_SELECTION) { 1390 if (listLocation == null) { 1391 if (!forDrop && state != null) { 1392 setSelectedIndices(((int[][])state)[0]); 1393 1394 int anchor = ((int[][])state)[1][0]; 1395 int lead = ((int[][])state)[1][1]; 1396 1397 SwingUtilities2.setLeadAnchorWithoutSelection( 1398 getSelectionModel(), lead, anchor); 1399 } 1400 } else { 1401 if (dropLocation == null) { 1402 int[] inds = getSelectedIndices(); 1403 retVal = new int[][] {inds, {getAnchorSelectionIndex(), 1404 getLeadSelectionIndex()}}; 1405 } else { 1406 retVal = state; 1407 } 1408 1409 int index = listLocation.getIndex(); 1410 if (index == -1) { 1411 clearSelection(); 1412 getSelectionModel().setAnchorSelectionIndex(-1); 1413 getSelectionModel().setLeadSelectionIndex(-1); 1414 } else { 1415 setSelectionInterval(index, index); 1416 } 1417 } 1418 } 1419 1420 DropLocation old = dropLocation; 1421 dropLocation = listLocation; 1422 firePropertyChange("dropLocation", old, dropLocation); 1423 1424 return retVal; 1425 } 1426 1427 /** 1428 * Returns the location that this component should visually indicate 1429 * as the drop location during a DnD operation over the component, 1430 * or {@code null} if no location is to currently be shown. 1431 * <p> 1432 * This method is not meant for querying the drop location 1433 * from a {@code TransferHandler}, as the drop location is only 1434 * set after the {@code TransferHandler}'s <code>canImport</code> 1435 * has returned and has allowed for the location to be shown. 1436 * <p> 1437 * When this property changes, a property change event with 1438 * name "dropLocation" is fired by the component. 1439 * <p> 1440 * By default, responsibility for listening for changes to this property 1441 * and indicating the drop location visually lies with the list's 1442 * {@code ListUI}, which may paint it directly and/or install a cell 1443 * renderer to do so. Developers wishing to implement custom drop location 1444 * painting and/or replace the default cell renderer, may need to honor 1445 * this property. 1446 * 1447 * @return the drop location 1448 * @see #setDropMode 1449 * @see TransferHandler#canImport(TransferHandler.TransferSupport) 1450 * @since 1.6 1451 */ 1452 @BeanProperty(bound = false) 1453 public final DropLocation getDropLocation() { 1454 return dropLocation; 1455 } 1456 1457 /** 1458 * Returns the next list element whose {@code toString} value 1459 * starts with the given prefix. 1460 * 1461 * @param prefix the string to test for a match 1462 * @param startIndex the index for starting the search 1463 * @param bias the search direction, either 1464 * Position.Bias.Forward or Position.Bias.Backward. 1465 * @return the index of the next list element that 1466 * starts with the prefix; otherwise {@code -1} 1467 * @exception IllegalArgumentException if prefix is {@code null} 1468 * or startIndex is out of bounds 1469 * @since 1.4 1470 */ 1471 public int getNextMatch(String prefix, int startIndex, Position.Bias bias) { 1472 ListModel<E> model = getModel(); 1473 int max = model.getSize(); 1474 if (prefix == null) { 1475 throw new IllegalArgumentException(); 1476 } 1477 if (startIndex < 0 || startIndex >= max) { 1478 throw new IllegalArgumentException(); 1479 } 1480 prefix = prefix.toUpperCase(); 1481 1482 // start search from the next element after the selected element 1483 int increment = (bias == Position.Bias.Forward) ? 1 : -1; 1484 int index = startIndex; 1485 do { 1486 E element = model.getElementAt(index); 1487 1488 if (element != null) { 1489 String string; 1490 1491 if (element instanceof String) { 1492 string = ((String)element).toUpperCase(); 1493 } 1494 else { 1495 string = element.toString(); 1496 if (string != null) { 1497 string = string.toUpperCase(); 1498 } 1499 } 1500 1501 if (string != null && string.startsWith(prefix)) { 1502 return index; 1503 } 1504 } 1505 index = (index + increment + max) % max; 1506 } while (index != startIndex); 1507 return -1; 1508 } 1509 1510 /** 1511 * Returns the tooltip text to be used for the given event. This overrides 1512 * {@code JComponent}'s {@code getToolTipText} to first check the cell 1513 * renderer component for the cell over which the event occurred, returning 1514 * its tooltip text, if any. This implementation allows you to specify 1515 * tooltip text on the cell level, by using {@code setToolTipText} on your 1516 * cell renderer component. 1517 * <p> 1518 * <strong>Note:</strong> For <code>JList</code> to properly display the 1519 * tooltips of its renderers in this manner, <code>JList</code> must be a 1520 * registered component with the <code>ToolTipManager</code>. This registration 1521 * is done automatically in the constructor. However, if at a later point 1522 * <code>JList</code> is unregistered, by way of a call to 1523 * {@code setToolTipText(null)}, tips from the renderers will no longer display. 1524 * 1525 * @param event the {@code MouseEvent} to fetch the tooltip text for 1526 * @see JComponent#setToolTipText 1527 * @see JComponent#getToolTipText 1528 */ 1529 @SuppressWarnings("deprecation") 1530 public String getToolTipText(MouseEvent event) { 1531 if(event != null) { 1532 Point p = event.getPoint(); 1533 int index = locationToIndex(p); 1534 ListCellRenderer<? super E> r = getCellRenderer(); 1535 Rectangle cellBounds; 1536 1537 if (index != -1 && r != null && (cellBounds = 1538 getCellBounds(index, index)) != null && 1539 cellBounds.contains(p.x, p.y)) { 1540 ListSelectionModel lsm = getSelectionModel(); 1541 Component rComponent = r.getListCellRendererComponent( 1542 this, getModel().getElementAt(index), index, 1543 lsm.isSelectedIndex(index), 1544 (hasFocus() && (lsm.getLeadSelectionIndex() == 1545 index))); 1546 1547 if(rComponent instanceof JComponent) { 1548 MouseEvent newEvent; 1549 1550 p.translate(-cellBounds.x, -cellBounds.y); 1551 newEvent = new MouseEvent(rComponent, event.getID(), 1552 event.getWhen(), 1553 event.getModifiers(), 1554 p.x, p.y, 1555 event.getXOnScreen(), 1556 event.getYOnScreen(), 1557 event.getClickCount(), 1558 event.isPopupTrigger(), 1559 MouseEvent.NOBUTTON); 1560 1561 String tip = ((JComponent)rComponent).getToolTipText( 1562 newEvent); 1563 1564 if (tip != null) { 1565 return tip; 1566 } 1567 } 1568 } 1569 } 1570 return super.getToolTipText(); 1571 } 1572 1573 /** 1574 * --- ListUI Delegations --- 1575 */ 1576 1577 1578 /** 1579 * Returns the cell index closest to the given location in the list's 1580 * coordinate system. To determine if the cell actually contains the 1581 * specified location, compare the point against the cell's bounds, 1582 * as provided by {@code getCellBounds}. This method returns {@code -1} 1583 * if the model is empty 1584 * <p> 1585 * This is a cover method that delegates to the method of the same name 1586 * in the list's {@code ListUI}. It returns {@code -1} if the list has 1587 * no {@code ListUI}. 1588 * 1589 * @param location the coordinates of the point 1590 * @return the cell index closest to the given location, or {@code -1} 1591 */ 1592 public int locationToIndex(Point location) { 1593 ListUI ui = getUI(); 1594 return (ui != null) ? ui.locationToIndex(this, location) : -1; 1595 } 1596 1597 1598 /** 1599 * Returns the origin of the specified item in the list's coordinate 1600 * system. This method returns {@code null} if the index isn't valid. 1601 * <p> 1602 * This is a cover method that delegates to the method of the same name 1603 * in the list's {@code ListUI}. It returns {@code null} if the list has 1604 * no {@code ListUI}. 1605 * 1606 * @param index the cell index 1607 * @return the origin of the cell, or {@code null} 1608 */ 1609 public Point indexToLocation(int index) { 1610 ListUI ui = getUI(); 1611 return (ui != null) ? ui.indexToLocation(this, index) : null; 1612 } 1613 1614 1615 /** 1616 * Returns the bounding rectangle, in the list's coordinate system, 1617 * for the range of cells specified by the two indices. 1618 * These indices can be supplied in any order. 1619 * <p> 1620 * If the smaller index is outside the list's range of cells, this method 1621 * returns {@code null}. If the smaller index is valid, but the larger 1622 * index is outside the list's range, the bounds of just the first index 1623 * is returned. Otherwise, the bounds of the valid range is returned. 1624 * <p> 1625 * This is a cover method that delegates to the method of the same name 1626 * in the list's {@code ListUI}. It returns {@code null} if the list has 1627 * no {@code ListUI}. 1628 * 1629 * @param index0 the first index in the range 1630 * @param index1 the second index in the range 1631 * @return the bounding rectangle for the range of cells, or {@code null} 1632 */ 1633 public Rectangle getCellBounds(int index0, int index1) { 1634 ListUI ui = getUI(); 1635 return (ui != null) ? ui.getCellBounds(this, index0, index1) : null; 1636 } 1637 1638 1639 /** 1640 * --- ListModel Support --- 1641 */ 1642 1643 1644 /** 1645 * Returns the data model that holds the list of items displayed 1646 * by the <code>JList</code> component. 1647 * 1648 * @return the <code>ListModel</code> that provides the displayed 1649 * list of items 1650 * @see #setModel 1651 */ 1652 public ListModel<E> getModel() { 1653 return dataModel; 1654 } 1655 1656 /** 1657 * Sets the model that represents the contents or "value" of the 1658 * list, notifies property change listeners, and then clears the 1659 * list's selection. 1660 * <p> 1661 * This is a JavaBeans bound property. 1662 * 1663 * @param model the <code>ListModel</code> that provides the 1664 * list of items for display 1665 * @exception IllegalArgumentException if <code>model</code> is 1666 * <code>null</code> 1667 * @see #getModel 1668 * @see #clearSelection 1669 */ 1670 @BeanProperty(visualUpdate = true, description 1671 = "The object that contains the data to be drawn by this JList.") 1672 public void setModel(ListModel<E> model) { 1673 if (model == null) { 1674 throw new IllegalArgumentException("model must be non null"); 1675 } 1676 ListModel<E> oldValue = dataModel; 1677 dataModel = model; 1678 firePropertyChange("model", oldValue, dataModel); 1679 clearSelection(); 1680 } 1681 1682 1683 /** 1684 * Constructs a read-only <code>ListModel</code> from an array of items, 1685 * and calls {@code setModel} with this model. 1686 * <p> 1687 * Attempts to pass a {@code null} value to this method results in 1688 * undefined behavior and, most likely, exceptions. The created model 1689 * references the given array directly. Attempts to modify the array 1690 * after invoking this method results in undefined behavior. 1691 * 1692 * @param listData an array of {@code E} containing the items to 1693 * display in the list 1694 * @see #setModel 1695 */ 1696 public void setListData(final E[] listData) { 1697 setModel ( 1698 new AbstractListModel<E>() { 1699 public int getSize() { return listData.length; } 1700 public E getElementAt(int i) { return listData[i]; } 1701 } 1702 ); 1703 } 1704 1705 1706 /** 1707 * Constructs a read-only <code>ListModel</code> from a <code>Vector</code> 1708 * and calls {@code setModel} with this model. 1709 * <p> 1710 * Attempts to pass a {@code null} value to this method results in 1711 * undefined behavior and, most likely, exceptions. The created model 1712 * references the given {@code Vector} directly. Attempts to modify the 1713 * {@code Vector} after invoking this method results in undefined behavior. 1714 * 1715 * @param listData a <code>Vector</code> containing the items to 1716 * display in the list 1717 * @see #setModel 1718 */ 1719 public void setListData(final Vector<? extends E> listData) { 1720 setModel ( 1721 new AbstractListModel<E>() { 1722 public int getSize() { return listData.size(); } 1723 public E getElementAt(int i) { return listData.elementAt(i); } 1724 } 1725 ); 1726 } 1727 1728 1729 /** 1730 * --- ListSelectionModel delegations and extensions --- 1731 */ 1732 1733 1734 /** 1735 * Returns an instance of {@code DefaultListSelectionModel}; called 1736 * during construction to initialize the list's selection model 1737 * property. 1738 * 1739 * @return a {@code DefaultListSelecitonModel}, used to initialize 1740 * the list's selection model property during construction 1741 * @see #setSelectionModel 1742 * @see DefaultListSelectionModel 1743 */ 1744 protected ListSelectionModel createSelectionModel() { 1745 return new DefaultListSelectionModel(); 1746 } 1747 1748 1749 /** 1750 * Returns the current selection model. The selection model maintains the 1751 * selection state of the list. See the class level documentation for more 1752 * details. 1753 * 1754 * @return the <code>ListSelectionModel</code> that maintains the 1755 * list's selections 1756 * 1757 * @see #setSelectionModel 1758 * @see ListSelectionModel 1759 */ 1760 public ListSelectionModel getSelectionModel() { 1761 return selectionModel; 1762 } 1763 1764 1765 /** 1766 * Notifies {@code ListSelectionListener}s added directly to the list 1767 * of selection changes made to the selection model. {@code JList} 1768 * listens for changes made to the selection in the selection model, 1769 * and forwards notification to listeners added to the list directly, 1770 * by calling this method. 1771 * <p> 1772 * This method constructs a {@code ListSelectionEvent} with this list 1773 * as the source, and the specified arguments, and sends it to the 1774 * registered {@code ListSelectionListeners}. 1775 * 1776 * @param firstIndex the first index in the range, {@code <= lastIndex} 1777 * @param lastIndex the last index in the range, {@code >= firstIndex} 1778 * @param isAdjusting whether or not this is one in a series of 1779 * multiple events, where changes are still being made 1780 * 1781 * @see #addListSelectionListener 1782 * @see #removeListSelectionListener 1783 * @see javax.swing.event.ListSelectionEvent 1784 * @see EventListenerList 1785 */ 1786 protected void fireSelectionValueChanged(int firstIndex, int lastIndex, 1787 boolean isAdjusting) 1788 { 1789 Object[] listeners = listenerList.getListenerList(); 1790 ListSelectionEvent e = null; 1791 1792 for (int i = listeners.length - 2; i >= 0; i -= 2) { 1793 if (listeners[i] == ListSelectionListener.class) { 1794 if (e == null) { 1795 e = new ListSelectionEvent(this, firstIndex, lastIndex, 1796 isAdjusting); 1797 } 1798 ((ListSelectionListener)listeners[i+1]).valueChanged(e); 1799 } 1800 } 1801 } 1802 1803 1804 /* A ListSelectionListener that forwards ListSelectionEvents from 1805 * the selectionModel to the JList ListSelectionListeners. The 1806 * forwarded events only differ from the originals in that their 1807 * source is the JList instead of the selectionModel itself. 1808 */ 1809 private class ListSelectionHandler implements ListSelectionListener, Serializable 1810 { 1811 public void valueChanged(ListSelectionEvent e) { 1812 fireSelectionValueChanged(e.getFirstIndex(), 1813 e.getLastIndex(), 1814 e.getValueIsAdjusting()); 1815 } 1816 } 1817 1818 1819 /** 1820 * Adds a listener to the list, to be notified each time a change to the 1821 * selection occurs; the preferred way of listening for selection state 1822 * changes. {@code JList} takes care of listening for selection state 1823 * changes in the selection model, and notifies the given listener of 1824 * each change. {@code ListSelectionEvent}s sent to the listener have a 1825 * {@code source} property set to this list. 1826 * 1827 * @param listener the {@code ListSelectionListener} to add 1828 * @see #getSelectionModel 1829 * @see #getListSelectionListeners 1830 */ 1831 public void addListSelectionListener(ListSelectionListener listener) 1832 { 1833 if (selectionListener == null) { 1834 selectionListener = new ListSelectionHandler(); 1835 getSelectionModel().addListSelectionListener(selectionListener); 1836 } 1837 1838 listenerList.add(ListSelectionListener.class, listener); 1839 } 1840 1841 1842 /** 1843 * Removes a selection listener from the list. 1844 * 1845 * @param listener the {@code ListSelectionListener} to remove 1846 * @see #addListSelectionListener 1847 * @see #getSelectionModel 1848 */ 1849 public void removeListSelectionListener(ListSelectionListener listener) { 1850 listenerList.remove(ListSelectionListener.class, listener); 1851 } 1852 1853 1854 /** 1855 * Returns an array of all the {@code ListSelectionListener}s added 1856 * to this {@code JList} by way of {@code addListSelectionListener}. 1857 * 1858 * @return all of the {@code ListSelectionListener}s on this list, or 1859 * an empty array if no listeners have been added 1860 * @see #addListSelectionListener 1861 * @since 1.4 1862 */ 1863 @BeanProperty(bound = false) 1864 public ListSelectionListener[] getListSelectionListeners() { 1865 return listenerList.getListeners(ListSelectionListener.class); 1866 } 1867 1868 1869 /** 1870 * Sets the <code>selectionModel</code> for the list to a 1871 * non-<code>null</code> <code>ListSelectionModel</code> 1872 * implementation. The selection model handles the task of making single 1873 * selections, selections of contiguous ranges, and non-contiguous 1874 * selections. 1875 * <p> 1876 * This is a JavaBeans bound property. 1877 * 1878 * @param selectionModel the <code>ListSelectionModel</code> that 1879 * implements the selections 1880 * @exception IllegalArgumentException if <code>selectionModel</code> 1881 * is <code>null</code> 1882 * @see #getSelectionModel 1883 */ 1884 @BeanProperty(description 1885 = "The selection model, recording which cells are selected.") 1886 public void setSelectionModel(ListSelectionModel selectionModel) { 1887 if (selectionModel == null) { 1888 throw new IllegalArgumentException("selectionModel must be non null"); 1889 } 1890 1891 /* Remove the forwarding ListSelectionListener from the old 1892 * selectionModel, and add it to the new one, if necessary. 1893 */ 1894 if (selectionListener != null) { 1895 this.selectionModel.removeListSelectionListener(selectionListener); 1896 selectionModel.addListSelectionListener(selectionListener); 1897 } 1898 1899 ListSelectionModel oldValue = this.selectionModel; 1900 this.selectionModel = selectionModel; 1901 firePropertyChange("selectionModel", oldValue, selectionModel); 1902 } 1903 1904 1905 /** 1906 * Sets the selection mode for the list. This is a cover method that sets 1907 * the selection mode directly on the selection model. 1908 * <p> 1909 * The following list describes the accepted selection modes: 1910 * <ul> 1911 * <li>{@code ListSelectionModel.SINGLE_SELECTION} - 1912 * Only one list index can be selected at a time. In this mode, 1913 * {@code setSelectionInterval} and {@code addSelectionInterval} are 1914 * equivalent, both replacing the current selection with the index 1915 * represented by the second argument (the "lead"). 1916 * <li>{@code ListSelectionModel.SINGLE_INTERVAL_SELECTION} - 1917 * Only one contiguous interval can be selected at a time. 1918 * In this mode, {@code addSelectionInterval} behaves like 1919 * {@code setSelectionInterval} (replacing the current selection}, 1920 * unless the given interval is immediately adjacent to or overlaps 1921 * the existing selection, and can be used to grow the selection. 1922 * <li>{@code ListSelectionModel.MULTIPLE_INTERVAL_SELECTION} - 1923 * In this mode, there's no restriction on what can be selected. 1924 * This mode is the default. 1925 * </ul> 1926 * 1927 * @param selectionMode the selection mode 1928 * @see #getSelectionMode 1929 * @throws IllegalArgumentException if the selection mode isn't 1930 * one of those allowed 1931 */ 1932 @BeanProperty(bound = false, enumerationValues = { 1933 "ListSelectionModel.SINGLE_SELECTION", 1934 "ListSelectionModel.SINGLE_INTERVAL_SELECTION", 1935 "ListSelectionModel.MULTIPLE_INTERVAL_SELECTION"}, description 1936 = "The selection mode.") 1937 public void setSelectionMode(int selectionMode) { 1938 getSelectionModel().setSelectionMode(selectionMode); 1939 } 1940 1941 /** 1942 * Returns the current selection mode for the list. This is a cover 1943 * method that delegates to the method of the same name on the 1944 * list's selection model. 1945 * 1946 * @return the current selection mode 1947 * @see #setSelectionMode 1948 */ 1949 public int getSelectionMode() { 1950 return getSelectionModel().getSelectionMode(); 1951 } 1952 1953 1954 /** 1955 * Returns the anchor selection index. This is a cover method that 1956 * delegates to the method of the same name on the list's selection model. 1957 * 1958 * @return the anchor selection index 1959 * @see ListSelectionModel#getAnchorSelectionIndex 1960 */ 1961 @BeanProperty(bound = false) 1962 public int getAnchorSelectionIndex() { 1963 return getSelectionModel().getAnchorSelectionIndex(); 1964 } 1965 1966 1967 /** 1968 * Returns the lead selection index. This is a cover method that 1969 * delegates to the method of the same name on the list's selection model. 1970 * 1971 * @return the lead selection index 1972 * @see ListSelectionModel#getLeadSelectionIndex 1973 */ 1974 @BeanProperty(bound = false, description 1975 = "The lead selection index.") 1976 public int getLeadSelectionIndex() { 1977 return getSelectionModel().getLeadSelectionIndex(); 1978 } 1979 1980 1981 /** 1982 * Returns the smallest selected cell index, or {@code -1} if the selection 1983 * is empty. This is a cover method that delegates to the method of the same 1984 * name on the list's selection model. 1985 * 1986 * @return the smallest selected cell index, or {@code -1} 1987 * @see ListSelectionModel#getMinSelectionIndex 1988 */ 1989 @BeanProperty(bound = false) 1990 public int getMinSelectionIndex() { 1991 return getSelectionModel().getMinSelectionIndex(); 1992 } 1993 1994 1995 /** 1996 * Returns the largest selected cell index, or {@code -1} if the selection 1997 * is empty. This is a cover method that delegates to the method of the same 1998 * name on the list's selection model. 1999 * 2000 * @return the largest selected cell index 2001 * @see ListSelectionModel#getMaxSelectionIndex 2002 */ 2003 @BeanProperty(bound = false) 2004 public int getMaxSelectionIndex() { 2005 return getSelectionModel().getMaxSelectionIndex(); 2006 } 2007 2008 2009 /** 2010 * Returns {@code true} if the specified index is selected, 2011 * else {@code false}. This is a cover method that delegates to the method 2012 * of the same name on the list's selection model. 2013 * 2014 * @param index index to be queried for selection state 2015 * @return {@code true} if the specified index is selected, 2016 * else {@code false} 2017 * @see ListSelectionModel#isSelectedIndex 2018 * @see #setSelectedIndex 2019 */ 2020 public boolean isSelectedIndex(int index) { 2021 return getSelectionModel().isSelectedIndex(index); 2022 } 2023 2024 2025 /** 2026 * Returns {@code true} if nothing is selected, else {@code false}. 2027 * This is a cover method that delegates to the method of the same 2028 * name on the list's selection model. 2029 * 2030 * @return {@code true} if nothing is selected, else {@code false} 2031 * @see ListSelectionModel#isSelectionEmpty 2032 * @see #clearSelection 2033 */ 2034 @BeanProperty(bound = false) 2035 public boolean isSelectionEmpty() { 2036 return getSelectionModel().isSelectionEmpty(); 2037 } 2038 2039 2040 /** 2041 * Clears the selection; after calling this method, {@code isSelectionEmpty} 2042 * will return {@code true}. This is a cover method that delegates to the 2043 * method of the same name on the list's selection model. 2044 * 2045 * @see ListSelectionModel#clearSelection 2046 * @see #isSelectionEmpty 2047 */ 2048 public void clearSelection() { 2049 getSelectionModel().clearSelection(); 2050 } 2051 2052 2053 /** 2054 * Selects the specified interval. Both {@code anchor} and {@code lead} 2055 * indices are included. {@code anchor} doesn't have to be less than or 2056 * equal to {@code lead}. This is a cover method that delegates to the 2057 * method of the same name on the list's selection model. 2058 * <p> 2059 * Refer to the documentation of the selection model class being used 2060 * for details on how values less than {@code 0} are handled. 2061 * 2062 * @param anchor the first index to select 2063 * @param lead the last index to select 2064 * @see ListSelectionModel#setSelectionInterval 2065 * @see DefaultListSelectionModel#setSelectionInterval 2066 * @see #createSelectionModel 2067 * @see #addSelectionInterval 2068 * @see #removeSelectionInterval 2069 */ 2070 public void setSelectionInterval(int anchor, int lead) { 2071 getSelectionModel().setSelectionInterval(anchor, lead); 2072 } 2073 2074 2075 /** 2076 * Sets the selection to be the union of the specified interval with current 2077 * selection. Both the {@code anchor} and {@code lead} indices are 2078 * included. {@code anchor} doesn't have to be less than or 2079 * equal to {@code lead}. This is a cover method that delegates to the 2080 * method of the same name on the list's selection model. 2081 * <p> 2082 * Refer to the documentation of the selection model class being used 2083 * for details on how values less than {@code 0} are handled. 2084 * 2085 * @param anchor the first index to add to the selection 2086 * @param lead the last index to add to the selection 2087 * @see ListSelectionModel#addSelectionInterval 2088 * @see DefaultListSelectionModel#addSelectionInterval 2089 * @see #createSelectionModel 2090 * @see #setSelectionInterval 2091 * @see #removeSelectionInterval 2092 */ 2093 public void addSelectionInterval(int anchor, int lead) { 2094 getSelectionModel().addSelectionInterval(anchor, lead); 2095 } 2096 2097 2098 /** 2099 * Sets the selection to be the set difference of the specified interval 2100 * and the current selection. Both the {@code index0} and {@code index1} 2101 * indices are removed. {@code index0} doesn't have to be less than or 2102 * equal to {@code index1}. This is a cover method that delegates to the 2103 * method of the same name on the list's selection model. 2104 * <p> 2105 * Refer to the documentation of the selection model class being used 2106 * for details on how values less than {@code 0} are handled. 2107 * 2108 * @param index0 the first index to remove from the selection 2109 * @param index1 the last index to remove from the selection 2110 * @see ListSelectionModel#removeSelectionInterval 2111 * @see DefaultListSelectionModel#removeSelectionInterval 2112 * @see #createSelectionModel 2113 * @see #setSelectionInterval 2114 * @see #addSelectionInterval 2115 */ 2116 public void removeSelectionInterval(int index0, int index1) { 2117 getSelectionModel().removeSelectionInterval(index0, index1); 2118 } 2119 2120 2121 /** 2122 * Sets the selection model's {@code valueIsAdjusting} property. When 2123 * {@code true}, upcoming changes to selection should be considered part 2124 * of a single change. This property is used internally and developers 2125 * typically need not call this method. For example, when the model is being 2126 * updated in response to a user drag, the value of the property is set 2127 * to {@code true} when the drag is initiated and set to {@code false} 2128 * when the drag is finished. This allows listeners to update only 2129 * when a change has been finalized, rather than handling all of the 2130 * intermediate values. 2131 * <p> 2132 * You may want to use this directly if making a series of changes 2133 * that should be considered part of a single change. 2134 * <p> 2135 * This is a cover method that delegates to the method of the same name on 2136 * the list's selection model. See the documentation for 2137 * {@link javax.swing.ListSelectionModel#setValueIsAdjusting} for 2138 * more details. 2139 * 2140 * @param b the new value for the property 2141 * @see ListSelectionModel#setValueIsAdjusting 2142 * @see javax.swing.event.ListSelectionEvent#getValueIsAdjusting 2143 * @see #getValueIsAdjusting 2144 */ 2145 public void setValueIsAdjusting(boolean b) { 2146 getSelectionModel().setValueIsAdjusting(b); 2147 } 2148 2149 2150 /** 2151 * Returns the value of the selection model's {@code isAdjusting} property. 2152 * <p> 2153 * This is a cover method that delegates to the method of the same name on 2154 * the list's selection model. 2155 * 2156 * @return the value of the selection model's {@code isAdjusting} property. 2157 * 2158 * @see #setValueIsAdjusting 2159 * @see ListSelectionModel#getValueIsAdjusting 2160 */ 2161 public boolean getValueIsAdjusting() { 2162 return getSelectionModel().getValueIsAdjusting(); 2163 } 2164 2165 2166 /** 2167 * Returns an array of all of the selected indices, in increasing 2168 * order. 2169 * 2170 * @return all of the selected indices, in increasing order, 2171 * or an empty array if nothing is selected 2172 * @see #removeSelectionInterval 2173 * @see #addListSelectionListener 2174 */ 2175 @Transient 2176 public int[] getSelectedIndices() { 2177 ListSelectionModel sm = getSelectionModel(); 2178 int iMin = sm.getMinSelectionIndex(); 2179 int iMax = sm.getMaxSelectionIndex(); 2180 2181 if ((iMin < 0) || (iMax < 0)) { 2182 return new int[0]; 2183 } 2184 2185 int[] rvTmp = new int[1+ (iMax - iMin)]; 2186 int n = 0; 2187 for(int i = iMin; i <= iMax; i++) { 2188 if (sm.isSelectedIndex(i)) { 2189 rvTmp[n++] = i; 2190 } 2191 } 2192 int[] rv = new int[n]; 2193 System.arraycopy(rvTmp, 0, rv, 0, n); 2194 return rv; 2195 } 2196 2197 2198 /** 2199 * Selects a single cell. Does nothing if the given index is greater 2200 * than or equal to the model size. This is a convenience method that uses 2201 * {@code setSelectionInterval} on the selection model. Refer to the 2202 * documentation for the selection model class being used for details on 2203 * how values less than {@code 0} are handled. 2204 * 2205 * @param index the index of the cell to select 2206 * @see ListSelectionModel#setSelectionInterval 2207 * @see #isSelectedIndex 2208 * @see #addListSelectionListener 2209 */ 2210 @BeanProperty(bound = false, description 2211 = "The index of the selected cell.") 2212 public void setSelectedIndex(int index) { 2213 if (index >= getModel().getSize()) { 2214 return; 2215 } 2216 getSelectionModel().setSelectionInterval(index, index); 2217 } 2218 2219 2220 /** 2221 * Changes the selection to be the set of indices specified by the given 2222 * array. Indices greater than or equal to the model size are ignored. 2223 * This is a convenience method that clears the selection and then uses 2224 * {@code addSelectionInterval} on the selection model to add the indices. 2225 * Refer to the documentation of the selection model class being used for 2226 * details on how values less than {@code 0} are handled. 2227 * 2228 * @param indices an array of the indices of the cells to select, 2229 * {@code non-null} 2230 * @see ListSelectionModel#addSelectionInterval 2231 * @see #isSelectedIndex 2232 * @see #addListSelectionListener 2233 * @throws NullPointerException if the given array is {@code null} 2234 */ 2235 public void setSelectedIndices(int[] indices) { 2236 ListSelectionModel sm = getSelectionModel(); 2237 sm.clearSelection(); 2238 int size = getModel().getSize(); 2239 for (int i : indices) { 2240 if (i < size) { 2241 sm.addSelectionInterval(i, i); 2242 } 2243 } 2244 } 2245 2246 2247 /** 2248 * Returns an array of all the selected values, in increasing order based 2249 * on their indices in the list. 2250 * 2251 * @return the selected values, or an empty array if nothing is selected 2252 * @see #isSelectedIndex 2253 * @see #getModel 2254 * @see #addListSelectionListener 2255 * 2256 * @deprecated As of JDK 1.7, replaced by {@link #getSelectedValuesList()} 2257 */ 2258 @Deprecated 2259 @BeanProperty(bound = false) 2260 public Object[] getSelectedValues() { 2261 ListSelectionModel sm = getSelectionModel(); 2262 ListModel<E> dm = getModel(); 2263 2264 int iMin = sm.getMinSelectionIndex(); 2265 int iMax = sm.getMaxSelectionIndex(); 2266 2267 if ((iMin < 0) || (iMax < 0)) { 2268 return new Object[0]; 2269 } 2270 2271 Object[] rvTmp = new Object[1+ (iMax - iMin)]; 2272 int n = 0; 2273 for(int i = iMin; i <= iMax; i++) { 2274 if (sm.isSelectedIndex(i)) { 2275 rvTmp[n++] = dm.getElementAt(i); 2276 } 2277 } 2278 Object[] rv = new Object[n]; 2279 System.arraycopy(rvTmp, 0, rv, 0, n); 2280 return rv; 2281 } 2282 2283 /** 2284 * Returns a list of all the selected items, in increasing order based 2285 * on their indices in the list. 2286 * 2287 * @return the selected items, or an empty list if nothing is selected 2288 * @see #isSelectedIndex 2289 * @see #getModel 2290 * @see #addListSelectionListener 2291 * 2292 * @since 1.7 2293 */ 2294 @BeanProperty(bound = false) 2295 public List<E> getSelectedValuesList() { 2296 ListSelectionModel sm = getSelectionModel(); 2297 ListModel<E> dm = getModel(); 2298 2299 int iMin = sm.getMinSelectionIndex(); 2300 int iMax = sm.getMaxSelectionIndex(); 2301 2302 if ((iMin < 0) || (iMax < 0)) { 2303 return Collections.emptyList(); 2304 } 2305 2306 List<E> selectedItems = new ArrayList<E>(); 2307 for(int i = iMin; i <= iMax; i++) { 2308 if (sm.isSelectedIndex(i)) { 2309 selectedItems.add(dm.getElementAt(i)); 2310 } 2311 } 2312 return selectedItems; 2313 } 2314 2315 2316 /** 2317 * Returns the smallest selected cell index; <i>the selection</i> when only 2318 * a single item is selected in the list. When multiple items are selected, 2319 * it is simply the smallest selected index. Returns {@code -1} if there is 2320 * no selection. 2321 * <p> 2322 * This method is a cover that delegates to {@code getMinSelectionIndex}. 2323 * 2324 * @return the smallest selected cell index 2325 * @see #getMinSelectionIndex 2326 * @see #addListSelectionListener 2327 */ 2328 public int getSelectedIndex() { 2329 return getMinSelectionIndex(); 2330 } 2331 2332 2333 /** 2334 * Returns the value for the smallest selected cell index; 2335 * <i>the selected value</i> when only a single item is selected in the 2336 * list. When multiple items are selected, it is simply the value for the 2337 * smallest selected index. Returns {@code null} if there is no selection. 2338 * <p> 2339 * This is a convenience method that simply returns the model value for 2340 * {@code getMinSelectionIndex}. 2341 * 2342 * @return the first selected value 2343 * @see #getMinSelectionIndex 2344 * @see #getModel 2345 * @see #addListSelectionListener 2346 */ 2347 @BeanProperty(bound = false) 2348 public E getSelectedValue() { 2349 int i = getMinSelectionIndex(); 2350 return (i == -1) ? null : getModel().getElementAt(i); 2351 } 2352 2353 2354 /** 2355 * Selects the specified object from the list. 2356 * 2357 * @param anObject the object to select 2358 * @param shouldScroll {@code true} if the list should scroll to display 2359 * the selected object, if one exists; otherwise {@code false} 2360 */ 2361 public void setSelectedValue(Object anObject,boolean shouldScroll) { 2362 if(anObject == null) 2363 setSelectedIndex(-1); 2364 else if(!anObject.equals(getSelectedValue())) { 2365 int i,c; 2366 ListModel<E> dm = getModel(); 2367 for(i=0,c=dm.getSize();i<c;i++) 2368 if(anObject.equals(dm.getElementAt(i))){ 2369 setSelectedIndex(i); 2370 if(shouldScroll) 2371 ensureIndexIsVisible(i); 2372 repaint(); /** FIX-ME setSelectedIndex does not redraw all the time with the basic l&f**/ 2373 return; 2374 } 2375 setSelectedIndex(-1); 2376 } 2377 repaint(); /** FIX-ME setSelectedIndex does not redraw all the time with the basic l&f**/ 2378 } 2379 2380 2381 2382 /** 2383 * --- The Scrollable Implementation --- 2384 */ 2385 2386 private void checkScrollableParameters(Rectangle visibleRect, int orientation) { 2387 if (visibleRect == null) { 2388 throw new IllegalArgumentException("visibleRect must be non-null"); 2389 } 2390 switch (orientation) { 2391 case SwingConstants.VERTICAL: 2392 case SwingConstants.HORIZONTAL: 2393 break; 2394 default: 2395 throw new IllegalArgumentException("orientation must be one of: VERTICAL, HORIZONTAL"); 2396 } 2397 } 2398 2399 2400 /** 2401 * Computes the size of viewport needed to display {@code visibleRowCount} 2402 * rows. The value returned by this method depends on the layout 2403 * orientation: 2404 * <p> 2405 * <b>{@code VERTICAL}:</b> 2406 * <br> 2407 * This is trivial if both {@code fixedCellWidth} and {@code fixedCellHeight} 2408 * have been set (either explicitly or by specifying a prototype cell value). 2409 * The width is simply the {@code fixedCellWidth} plus the list's horizontal 2410 * insets. The height is the {@code fixedCellHeight} multiplied by the 2411 * {@code visibleRowCount}, plus the list's vertical insets. 2412 * <p> 2413 * If either {@code fixedCellWidth} or {@code fixedCellHeight} haven't been 2414 * specified, heuristics are used. If the model is empty, the width is 2415 * the {@code fixedCellWidth}, if greater than {@code 0}, or a hard-coded 2416 * value of {@code 256}. The height is the {@code fixedCellHeight} multiplied 2417 * by {@code visibleRowCount}, if {@code fixedCellHeight} is greater than 2418 * {@code 0}, otherwise it is a hard-coded value of {@code 16} multiplied by 2419 * {@code visibleRowCount}. 2420 * <p> 2421 * If the model isn't empty, the width is the preferred size's width, 2422 * typically the width of the widest list element. The height is the 2423 * {@code fixedCellHeight} multiplied by the {@code visibleRowCount}, 2424 * plus the list's vertical insets. 2425 * <p> 2426 * <b>{@code VERTICAL_WRAP} or {@code HORIZONTAL_WRAP}:</b> 2427 * <br> 2428 * This method simply returns the value from {@code getPreferredSize}. 2429 * The list's {@code ListUI} is expected to override {@code getPreferredSize} 2430 * to return an appropriate value. 2431 * 2432 * @return a dimension containing the size of the viewport needed 2433 * to display {@code visibleRowCount} rows 2434 * @see #getPreferredScrollableViewportSize 2435 * @see #setPrototypeCellValue 2436 */ 2437 @BeanProperty(bound = false) 2438 public Dimension getPreferredScrollableViewportSize() 2439 { 2440 if (getLayoutOrientation() != VERTICAL) { 2441 return getPreferredSize(); 2442 } 2443 Insets insets = getInsets(); 2444 int dx = insets.left + insets.right; 2445 int dy = insets.top + insets.bottom; 2446 2447 int visibleRowCount = getVisibleRowCount(); 2448 int fixedCellWidth = getFixedCellWidth(); 2449 int fixedCellHeight = getFixedCellHeight(); 2450 2451 if ((fixedCellWidth > 0) && (fixedCellHeight > 0)) { 2452 int width = fixedCellWidth + dx; 2453 int height = (visibleRowCount * fixedCellHeight) + dy; 2454 return new Dimension(width, height); 2455 } 2456 else if (getModel().getSize() > 0) { 2457 int width = getPreferredSize().width; 2458 int height; 2459 Rectangle r = getCellBounds(0, 0); 2460 if (r != null) { 2461 height = (visibleRowCount * r.height) + dy; 2462 } 2463 else { 2464 // Will only happen if UI null, shouldn't matter what we return 2465 height = 1; 2466 } 2467 return new Dimension(width, height); 2468 } 2469 else { 2470 fixedCellWidth = (fixedCellWidth > 0) ? fixedCellWidth : 256; 2471 fixedCellHeight = (fixedCellHeight > 0) ? fixedCellHeight : 16; 2472 return new Dimension(fixedCellWidth, fixedCellHeight * visibleRowCount); 2473 } 2474 } 2475 2476 2477 /** 2478 * Returns the distance to scroll to expose the next or previous 2479 * row (for vertical scrolling) or column (for horizontal scrolling). 2480 * <p> 2481 * For horizontal scrolling, if the layout orientation is {@code VERTICAL}, 2482 * then the list's font size is returned (or {@code 1} if the font is 2483 * {@code null}). 2484 * 2485 * @param visibleRect the view area visible within the viewport 2486 * @param orientation {@code SwingConstants.HORIZONTAL} or 2487 * {@code SwingConstants.VERTICAL} 2488 * @param direction less or equal to zero to scroll up/back, 2489 * greater than zero for down/forward 2490 * @return the "unit" increment for scrolling in the specified direction; 2491 * always positive 2492 * @see #getScrollableBlockIncrement 2493 * @see Scrollable#getScrollableUnitIncrement 2494 * @throws IllegalArgumentException if {@code visibleRect} is {@code null}, or 2495 * {@code orientation} isn't one of {@code SwingConstants.VERTICAL} or 2496 * {@code SwingConstants.HORIZONTAL} 2497 */ 2498 public int getScrollableUnitIncrement(Rectangle visibleRect, int orientation, int direction) 2499 { 2500 checkScrollableParameters(visibleRect, orientation); 2501 2502 if (orientation == SwingConstants.VERTICAL) { 2503 int row = locationToIndex(visibleRect.getLocation()); 2504 2505 if (row == -1) { 2506 return 0; 2507 } 2508 else { 2509 /* Scroll Down */ 2510 if (direction > 0) { 2511 Rectangle r = getCellBounds(row, row); 2512 return (r == null) ? 0 : r.height - (visibleRect.y - r.y); 2513 } 2514 /* Scroll Up */ 2515 else { 2516 Rectangle r = getCellBounds(row, row); 2517 2518 /* The first row is completely visible and it's row 0. 2519 * We're done. 2520 */ 2521 if ((r.y == visibleRect.y) && (row == 0)) { 2522 return 0; 2523 } 2524 /* The first row is completely visible, return the 2525 * height of the previous row or 0 if the first row 2526 * is the top row of the list. 2527 */ 2528 else if (r.y == visibleRect.y) { 2529 Point loc = r.getLocation(); 2530 loc.y--; 2531 int prevIndex = locationToIndex(loc); 2532 Rectangle prevR = getCellBounds(prevIndex, prevIndex); 2533 2534 if (prevR == null || prevR.y >= r.y) { 2535 return 0; 2536 } 2537 return prevR.height; 2538 } 2539 /* The first row is partially visible, return the 2540 * height of hidden part. 2541 */ 2542 else { 2543 return visibleRect.y - r.y; 2544 } 2545 } 2546 } 2547 } else if (orientation == SwingConstants.HORIZONTAL && 2548 getLayoutOrientation() != JList.VERTICAL) { 2549 boolean leftToRight = getComponentOrientation().isLeftToRight(); 2550 int index; 2551 Point leadingPoint; 2552 2553 if (leftToRight) { 2554 leadingPoint = visibleRect.getLocation(); 2555 } 2556 else { 2557 leadingPoint = new Point(visibleRect.x + visibleRect.width -1, 2558 visibleRect.y); 2559 } 2560 index = locationToIndex(leadingPoint); 2561 2562 if (index != -1) { 2563 Rectangle cellBounds = getCellBounds(index, index); 2564 if (cellBounds != null && cellBounds.contains(leadingPoint)) { 2565 int leadingVisibleEdge; 2566 int leadingCellEdge; 2567 2568 if (leftToRight) { 2569 leadingVisibleEdge = visibleRect.x; 2570 leadingCellEdge = cellBounds.x; 2571 } 2572 else { 2573 leadingVisibleEdge = visibleRect.x + visibleRect.width; 2574 leadingCellEdge = cellBounds.x + cellBounds.width; 2575 } 2576 2577 if (leadingCellEdge != leadingVisibleEdge) { 2578 if (direction < 0) { 2579 // Show remainder of leading cell 2580 return Math.abs(leadingVisibleEdge - leadingCellEdge); 2581 2582 } 2583 else if (leftToRight) { 2584 // Hide rest of leading cell 2585 return leadingCellEdge + cellBounds.width - leadingVisibleEdge; 2586 } 2587 else { 2588 // Hide rest of leading cell 2589 return leadingVisibleEdge - cellBounds.x; 2590 } 2591 } 2592 // ASSUME: All cells are the same width 2593 return cellBounds.width; 2594 } 2595 } 2596 } 2597 Font f = getFont(); 2598 return (f != null) ? f.getSize() : 1; 2599 } 2600 2601 2602 /** 2603 * Returns the distance to scroll to expose the next or previous block. 2604 * <p> 2605 * For vertical scrolling, the following rules are used: 2606 * <ul> 2607 * <li>if scrolling down, returns the distance to scroll so that the last 2608 * visible element becomes the first completely visible element 2609 * <li>if scrolling up, returns the distance to scroll so that the first 2610 * visible element becomes the last completely visible element 2611 * <li>returns {@code visibleRect.height} if the list is empty 2612 * </ul> 2613 * <p> 2614 * For horizontal scrolling, when the layout orientation is either 2615 * {@code VERTICAL_WRAP} or {@code HORIZONTAL_WRAP}: 2616 * <ul> 2617 * <li>if scrolling right, returns the distance to scroll so that the 2618 * last visible element becomes 2619 * the first completely visible element 2620 * <li>if scrolling left, returns the distance to scroll so that the first 2621 * visible element becomes the last completely visible element 2622 * <li>returns {@code visibleRect.width} if the list is empty 2623 * </ul> 2624 * <p> 2625 * For horizontal scrolling and {@code VERTICAL} orientation, 2626 * returns {@code visibleRect.width}. 2627 * <p> 2628 * Note that the value of {@code visibleRect} must be the equal to 2629 * {@code this.getVisibleRect()}. 2630 * 2631 * @param visibleRect the view area visible within the viewport 2632 * @param orientation {@code SwingConstants.HORIZONTAL} or 2633 * {@code SwingConstants.VERTICAL} 2634 * @param direction less or equal to zero to scroll up/back, 2635 * greater than zero for down/forward 2636 * @return the "block" increment for scrolling in the specified direction; 2637 * always positive 2638 * @see #getScrollableUnitIncrement 2639 * @see Scrollable#getScrollableBlockIncrement 2640 * @throws IllegalArgumentException if {@code visibleRect} is {@code null}, or 2641 * {@code orientation} isn't one of {@code SwingConstants.VERTICAL} or 2642 * {@code SwingConstants.HORIZONTAL} 2643 */ 2644 public int getScrollableBlockIncrement(Rectangle visibleRect, int orientation, int direction) { 2645 checkScrollableParameters(visibleRect, orientation); 2646 if (orientation == SwingConstants.VERTICAL) { 2647 int inc = visibleRect.height; 2648 /* Scroll Down */ 2649 if (direction > 0) { 2650 // last cell is the lowest left cell 2651 int last = locationToIndex(new Point(visibleRect.x, visibleRect.y+visibleRect.height-1)); 2652 if (last != -1) { 2653 Rectangle lastRect = getCellBounds(last,last); 2654 if (lastRect != null) { 2655 inc = lastRect.y - visibleRect.y; 2656 if ( (inc == 0) && (last < getModel().getSize()-1) ) { 2657 inc = lastRect.height; 2658 } 2659 } 2660 } 2661 } 2662 /* Scroll Up */ 2663 else { 2664 int newFirst = locationToIndex(new Point(visibleRect.x, visibleRect.y-visibleRect.height)); 2665 int first = getFirstVisibleIndex(); 2666 if (newFirst != -1) { 2667 if (first == -1) { 2668 first = locationToIndex(visibleRect.getLocation()); 2669 } 2670 Rectangle newFirstRect = getCellBounds(newFirst,newFirst); 2671 Rectangle firstRect = getCellBounds(first,first); 2672 if ((newFirstRect != null) && (firstRect!=null)) { 2673 while ( (newFirstRect.y + visibleRect.height < 2674 firstRect.y + firstRect.height) && 2675 (newFirstRect.y < firstRect.y) ) { 2676 newFirst++; 2677 newFirstRect = getCellBounds(newFirst,newFirst); 2678 } 2679 inc = visibleRect.y - newFirstRect.y; 2680 if ( (inc <= 0) && (newFirstRect.y > 0)) { 2681 newFirst--; 2682 newFirstRect = getCellBounds(newFirst,newFirst); 2683 if (newFirstRect != null) { 2684 inc = visibleRect.y - newFirstRect.y; 2685 } 2686 } 2687 } 2688 } 2689 } 2690 return inc; 2691 } 2692 else if (orientation == SwingConstants.HORIZONTAL && 2693 getLayoutOrientation() != JList.VERTICAL) { 2694 boolean leftToRight = getComponentOrientation().isLeftToRight(); 2695 int inc = visibleRect.width; 2696 /* Scroll Right (in ltr mode) or Scroll Left (in rtl mode) */ 2697 if (direction > 0) { 2698 // position is upper right if ltr, or upper left otherwise 2699 int x = visibleRect.x + (leftToRight ? (visibleRect.width - 1) : 0); 2700 int last = locationToIndex(new Point(x, visibleRect.y)); 2701 2702 if (last != -1) { 2703 Rectangle lastRect = getCellBounds(last,last); 2704 if (lastRect != null) { 2705 if (leftToRight) { 2706 inc = lastRect.x - visibleRect.x; 2707 } else { 2708 inc = visibleRect.x + visibleRect.width 2709 - (lastRect.x + lastRect.width); 2710 } 2711 if (inc < 0) { 2712 inc += lastRect.width; 2713 } else if ( (inc == 0) && (last < getModel().getSize()-1) ) { 2714 inc = lastRect.width; 2715 } 2716 } 2717 } 2718 } 2719 /* Scroll Left (in ltr mode) or Scroll Right (in rtl mode) */ 2720 else { 2721 // position is upper left corner of the visibleRect shifted 2722 // left by the visibleRect.width if ltr, or upper right shifted 2723 // right by the visibleRect.width otherwise 2724 int x = visibleRect.x + (leftToRight 2725 ? -visibleRect.width 2726 : visibleRect.width - 1 + visibleRect.width); 2727 int first = locationToIndex(new Point(x, visibleRect.y)); 2728 2729 if (first != -1) { 2730 Rectangle firstRect = getCellBounds(first,first); 2731 if (firstRect != null) { 2732 // the right of the first cell 2733 int firstRight = firstRect.x + firstRect.width; 2734 2735 if (leftToRight) { 2736 if ((firstRect.x < visibleRect.x - visibleRect.width) 2737 && (firstRight < visibleRect.x)) { 2738 inc = visibleRect.x - firstRight; 2739 } else { 2740 inc = visibleRect.x - firstRect.x; 2741 } 2742 } else { 2743 int visibleRight = visibleRect.x + visibleRect.width; 2744 2745 if ((firstRight > visibleRight + visibleRect.width) 2746 && (firstRect.x > visibleRight)) { 2747 inc = firstRect.x - visibleRight; 2748 } else { 2749 inc = firstRight - visibleRight; 2750 } 2751 } 2752 } 2753 } 2754 } 2755 return inc; 2756 } 2757 return visibleRect.width; 2758 } 2759 2760 2761 /** 2762 * Returns {@code true} if this {@code JList} is displayed in a 2763 * {@code JViewport} and the viewport is wider than the list's 2764 * preferred width, or if the layout orientation is {@code HORIZONTAL_WRAP} 2765 * and {@code visibleRowCount <= 0}; otherwise returns {@code false}. 2766 * <p> 2767 * If {@code false}, then don't track the viewport's width. This allows 2768 * horizontal scrolling if the {@code JViewport} is itself embedded in a 2769 * {@code JScrollPane}. 2770 * 2771 * @return whether or not an enclosing viewport should force the list's 2772 * width to match its own 2773 * @see Scrollable#getScrollableTracksViewportWidth 2774 */ 2775 @BeanProperty(bound = false) 2776 public boolean getScrollableTracksViewportWidth() { 2777 if (getLayoutOrientation() == HORIZONTAL_WRAP && 2778 getVisibleRowCount() <= 0) { 2779 return true; 2780 } 2781 Container parent = SwingUtilities.getUnwrappedParent(this); 2782 if (parent instanceof JViewport) { 2783 return parent.getWidth() > getPreferredSize().width; 2784 } 2785 return false; 2786 } 2787 2788 /** 2789 * Returns {@code true} if this {@code JList} is displayed in a 2790 * {@code JViewport} and the viewport is taller than the list's 2791 * preferred height, or if the layout orientation is {@code VERTICAL_WRAP} 2792 * and {@code visibleRowCount <= 0}; otherwise returns {@code false}. 2793 * <p> 2794 * If {@code false}, then don't track the viewport's height. This allows 2795 * vertical scrolling if the {@code JViewport} is itself embedded in a 2796 * {@code JScrollPane}. 2797 * 2798 * @return whether or not an enclosing viewport should force the list's 2799 * height to match its own 2800 * @see Scrollable#getScrollableTracksViewportHeight 2801 */ 2802 @BeanProperty(bound = false) 2803 public boolean getScrollableTracksViewportHeight() { 2804 if (getLayoutOrientation() == VERTICAL_WRAP && 2805 getVisibleRowCount() <= 0) { 2806 return true; 2807 } 2808 Container parent = SwingUtilities.getUnwrappedParent(this); 2809 if (parent instanceof JViewport) { 2810 return parent.getHeight() > getPreferredSize().height; 2811 } 2812 return false; 2813 } 2814 2815 2816 /* 2817 * See {@code readObject} and {@code writeObject} in {@code JComponent} 2818 * for more information about serialization in Swing. 2819 */ 2820 private void writeObject(ObjectOutputStream s) throws IOException { 2821 s.defaultWriteObject(); 2822 if (getUIClassID().equals(uiClassID)) { 2823 byte count = JComponent.getWriteObjCounter(this); 2824 JComponent.setWriteObjCounter(this, --count); 2825 if (count == 0 && ui != null) { 2826 ui.installUI(this); 2827 } 2828 } 2829 } 2830 2831 2832 /** 2833 * Returns a {@code String} representation of this {@code JList}. 2834 * This method is intended to be used only for debugging purposes, 2835 * and the content and format of the returned {@code String} may vary 2836 * between implementations. The returned {@code String} may be empty, 2837 * but may not be {@code null}. 2838 * 2839 * @return a {@code String} representation of this {@code JList}. 2840 */ 2841 protected String paramString() { 2842 String selectionForegroundString = (selectionForeground != null ? 2843 selectionForeground.toString() : 2844 ""); 2845 String selectionBackgroundString = (selectionBackground != null ? 2846 selectionBackground.toString() : 2847 ""); 2848 2849 return super.paramString() + 2850 ",fixedCellHeight=" + fixedCellHeight + 2851 ",fixedCellWidth=" + fixedCellWidth + 2852 ",horizontalScrollIncrement=" + horizontalScrollIncrement + 2853 ",selectionBackground=" + selectionBackgroundString + 2854 ",selectionForeground=" + selectionForegroundString + 2855 ",visibleRowCount=" + visibleRowCount + 2856 ",layoutOrientation=" + layoutOrientation; 2857 } 2858 2859 2860 /** 2861 * --- Accessibility Support --- 2862 */ 2863 2864 /** 2865 * Gets the {@code AccessibleContext} associated with this {@code JList}. 2866 * For {@code JList}, the {@code AccessibleContext} takes the form of an 2867 * {@code AccessibleJList}. 2868 * <p> 2869 * A new {@code AccessibleJList} instance is created if necessary. 2870 * 2871 * @return an {@code AccessibleJList} that serves as the 2872 * {@code AccessibleContext} of this {@code JList} 2873 */ 2874 @BeanProperty(bound = false) 2875 public AccessibleContext getAccessibleContext() { 2876 if (accessibleContext == null) { 2877 accessibleContext = new AccessibleJList(); 2878 } 2879 return accessibleContext; 2880 } 2881 2882 /** 2883 * This class implements accessibility support for the 2884 * {@code JList} class. It provides an implementation of the 2885 * Java Accessibility API appropriate to list user-interface 2886 * elements. 2887 * <p> 2888 * <strong>Warning:</strong> 2889 * Serialized objects of this class will not be compatible with 2890 * future Swing releases. The current serialization support is 2891 * appropriate for short term storage or RMI between applications running 2892 * the same version of Swing. As of 1.4, support for long term storage 2893 * of all JavaBeans™ 2894 * has been added to the <code>java.beans</code> package. 2895 * Please see {@link java.beans.XMLEncoder}. 2896 */ 2897 @SuppressWarnings("serial") // Same-version serialization only 2898 protected class AccessibleJList extends AccessibleJComponent 2899 implements AccessibleSelection, PropertyChangeListener, 2900 ListSelectionListener, ListDataListener { 2901 2902 int leadSelectionIndex; 2903 2904 /** 2905 * Constructs an {@code AccessibleJList}. 2906 */ 2907 public AccessibleJList() { 2908 super(); 2909 JList.this.addPropertyChangeListener(this); 2910 JList.this.getSelectionModel().addListSelectionListener(this); 2911 JList.this.getModel().addListDataListener(this); 2912 leadSelectionIndex = JList.this.getLeadSelectionIndex(); 2913 } 2914 2915 /** 2916 * Property Change Listener change method. Used to track changes 2917 * to the DataModel and ListSelectionModel, in order to re-set 2918 * listeners to those for reporting changes there via the Accessibility 2919 * PropertyChange mechanism. 2920 * 2921 * @param e PropertyChangeEvent 2922 */ 2923 public void propertyChange(PropertyChangeEvent e) { 2924 String name = e.getPropertyName(); 2925 Object oldValue = e.getOldValue(); 2926 Object newValue = e.getNewValue(); 2927 2928 // re-set listData listeners 2929 if (name.compareTo("model") == 0) { 2930 2931 if (oldValue != null && oldValue instanceof ListModel) { 2932 ((ListModel) oldValue).removeListDataListener(this); 2933 } 2934 if (newValue != null && newValue instanceof ListModel) { 2935 ((ListModel) newValue).addListDataListener(this); 2936 } 2937 2938 // re-set listSelectionModel listeners 2939 } else if (name.compareTo("selectionModel") == 0) { 2940 2941 if (oldValue != null && oldValue instanceof ListSelectionModel) { 2942 ((ListSelectionModel) oldValue).removeListSelectionListener(this); 2943 } 2944 if (newValue != null && newValue instanceof ListSelectionModel) { 2945 ((ListSelectionModel) newValue).addListSelectionListener(this); 2946 } 2947 2948 firePropertyChange( 2949 AccessibleContext.ACCESSIBLE_SELECTION_PROPERTY, 2950 Boolean.valueOf(false), Boolean.valueOf(true)); 2951 } 2952 } 2953 2954 /** 2955 * List Selection Listener value change method. Used to fire 2956 * the property change 2957 * 2958 * @param e ListSelectionEvent 2959 * 2960 */ 2961 public void valueChanged(ListSelectionEvent e) { 2962 int oldLeadSelectionIndex = leadSelectionIndex; 2963 leadSelectionIndex = JList.this.getLeadSelectionIndex(); 2964 if (oldLeadSelectionIndex != leadSelectionIndex) { 2965 Accessible oldLS, newLS; 2966 oldLS = (oldLeadSelectionIndex >= 0) 2967 ? getAccessibleChild(oldLeadSelectionIndex) 2968 : null; 2969 newLS = (leadSelectionIndex >= 0) 2970 ? getAccessibleChild(leadSelectionIndex) 2971 : null; 2972 firePropertyChange(AccessibleContext.ACCESSIBLE_ACTIVE_DESCENDANT_PROPERTY, 2973 oldLS, newLS); 2974 } 2975 2976 firePropertyChange(AccessibleContext.ACCESSIBLE_VISIBLE_DATA_PROPERTY, 2977 Boolean.valueOf(false), Boolean.valueOf(true)); 2978 firePropertyChange(AccessibleContext.ACCESSIBLE_SELECTION_PROPERTY, 2979 Boolean.valueOf(false), Boolean.valueOf(true)); 2980 2981 // Process the State changes for Multiselectable 2982 AccessibleStateSet s = getAccessibleStateSet(); 2983 ListSelectionModel lsm = JList.this.getSelectionModel(); 2984 if (lsm.getSelectionMode() != ListSelectionModel.SINGLE_SELECTION) { 2985 if (!s.contains(AccessibleState.MULTISELECTABLE)) { 2986 s.add(AccessibleState.MULTISELECTABLE); 2987 firePropertyChange(AccessibleContext.ACCESSIBLE_STATE_PROPERTY, 2988 null, AccessibleState.MULTISELECTABLE); 2989 } 2990 } else { 2991 if (s.contains(AccessibleState.MULTISELECTABLE)) { 2992 s.remove(AccessibleState.MULTISELECTABLE); 2993 firePropertyChange(AccessibleContext.ACCESSIBLE_STATE_PROPERTY, 2994 AccessibleState.MULTISELECTABLE, null); 2995 } 2996 } 2997 } 2998 2999 /** 3000 * List Data Listener interval added method. Used to fire the visible data property change 3001 * 3002 * @param e ListDataEvent 3003 * 3004 */ 3005 public void intervalAdded(ListDataEvent e) { 3006 firePropertyChange(AccessibleContext.ACCESSIBLE_VISIBLE_DATA_PROPERTY, 3007 Boolean.valueOf(false), Boolean.valueOf(true)); 3008 } 3009 3010 /** 3011 * List Data Listener interval removed method. Used to fire the visible data property change 3012 * 3013 * @param e ListDataEvent 3014 * 3015 */ 3016 public void intervalRemoved(ListDataEvent e) { 3017 firePropertyChange(AccessibleContext.ACCESSIBLE_VISIBLE_DATA_PROPERTY, 3018 Boolean.valueOf(false), Boolean.valueOf(true)); 3019 } 3020 3021 /** 3022 * List Data Listener contents changed method. Used to fire the visible data property change 3023 * 3024 * @param e ListDataEvent 3025 * 3026 */ 3027 public void contentsChanged(ListDataEvent e) { 3028 firePropertyChange(AccessibleContext.ACCESSIBLE_VISIBLE_DATA_PROPERTY, 3029 Boolean.valueOf(false), Boolean.valueOf(true)); 3030 } 3031 3032 // AccessibleContext methods 3033 3034 /** 3035 * Get the state set of this object. 3036 * 3037 * @return an instance of AccessibleState containing the current state 3038 * of the object 3039 * @see AccessibleState 3040 */ 3041 public AccessibleStateSet getAccessibleStateSet() { 3042 AccessibleStateSet states = super.getAccessibleStateSet(); 3043 if (selectionModel.getSelectionMode() != 3044 ListSelectionModel.SINGLE_SELECTION) { 3045 states.add(AccessibleState.MULTISELECTABLE); 3046 } 3047 return states; 3048 } 3049 3050 /** 3051 * Get the role of this object. 3052 * 3053 * @return an instance of AccessibleRole describing the role of the 3054 * object 3055 * @see AccessibleRole 3056 */ 3057 public AccessibleRole getAccessibleRole() { 3058 return AccessibleRole.LIST; 3059 } 3060 3061 /** 3062 * Returns the <code>Accessible</code> child contained at 3063 * the local coordinate <code>Point</code>, if one exists. 3064 * Otherwise returns <code>null</code>. 3065 * 3066 * @return the <code>Accessible</code> at the specified 3067 * location, if it exists 3068 */ 3069 public Accessible getAccessibleAt(Point p) { 3070 int i = locationToIndex(p); 3071 if (i >= 0) { 3072 return new AccessibleJListChild(JList.this, i); 3073 } else { 3074 return null; 3075 } 3076 } 3077 3078 /** 3079 * Returns the number of accessible children in the object. If all 3080 * of the children of this object implement Accessible, than this 3081 * method should return the number of children of this object. 3082 * 3083 * @return the number of accessible children in the object. 3084 */ 3085 public int getAccessibleChildrenCount() { 3086 return getModel().getSize(); 3087 } 3088 3089 /** 3090 * Return the nth Accessible child of the object. 3091 * 3092 * @param i zero-based index of child 3093 * @return the nth Accessible child of the object 3094 */ 3095 public Accessible getAccessibleChild(int i) { 3096 if (i >= getModel().getSize()) { 3097 return null; 3098 } else { 3099 return new AccessibleJListChild(JList.this, i); 3100 } 3101 } 3102 3103 /** 3104 * Get the AccessibleSelection associated with this object. In the 3105 * implementation of the Java Accessibility API for this class, 3106 * return this object, which is responsible for implementing the 3107 * AccessibleSelection interface on behalf of itself. 3108 * 3109 * @return this object 3110 */ 3111 public AccessibleSelection getAccessibleSelection() { 3112 return this; 3113 } 3114 3115 3116 // AccessibleSelection methods 3117 3118 /** 3119 * Returns the number of items currently selected. 3120 * If no items are selected, the return value will be 0. 3121 * 3122 * @return the number of items currently selected. 3123 */ 3124 public int getAccessibleSelectionCount() { 3125 return JList.this.getSelectedIndices().length; 3126 } 3127 3128 /** 3129 * Returns an Accessible representing the specified selected item 3130 * in the object. If there isn't a selection, or there are 3131 * fewer items selected than the integer passed in, the return 3132 * value will be <code>null</code>. 3133 * 3134 * @param i the zero-based index of selected items 3135 * @return an Accessible containing the selected item 3136 */ 3137 public Accessible getAccessibleSelection(int i) { 3138 int len = getAccessibleSelectionCount(); 3139 if (i < 0 || i >= len) { 3140 return null; 3141 } else { 3142 return getAccessibleChild(JList.this.getSelectedIndices()[i]); 3143 } 3144 } 3145 3146 /** 3147 * Returns true if the current child of this object is selected. 3148 * 3149 * @param i the zero-based index of the child in this Accessible 3150 * object. 3151 * @see AccessibleContext#getAccessibleChild 3152 */ 3153 public boolean isAccessibleChildSelected(int i) { 3154 return isSelectedIndex(i); 3155 } 3156 3157 /** 3158 * Adds the specified selected item in the object to the object's 3159 * selection. If the object supports multiple selections, 3160 * the specified item is added to any existing selection, otherwise 3161 * it replaces any existing selection in the object. If the 3162 * specified item is already selected, this method has no effect. 3163 * 3164 * @param i the zero-based index of selectable items 3165 */ 3166 public void addAccessibleSelection(int i) { 3167 JList.this.addSelectionInterval(i, i); 3168 } 3169 3170 /** 3171 * Removes the specified selected item in the object from the object's 3172 * selection. If the specified item isn't currently selected, this 3173 * method has no effect. 3174 * 3175 * @param i the zero-based index of selectable items 3176 */ 3177 public void removeAccessibleSelection(int i) { 3178 JList.this.removeSelectionInterval(i, i); 3179 } 3180 3181 /** 3182 * Clears the selection in the object, so that nothing in the 3183 * object is selected. 3184 */ 3185 public void clearAccessibleSelection() { 3186 JList.this.clearSelection(); 3187 } 3188 3189 /** 3190 * Causes every selected item in the object to be selected 3191 * if the object supports multiple selections. 3192 */ 3193 public void selectAllAccessibleSelection() { 3194 JList.this.addSelectionInterval(0, getAccessibleChildrenCount() -1); 3195 } 3196 3197 /** 3198 * This class implements accessibility support appropriate 3199 * for list children. 3200 */ 3201 protected class AccessibleJListChild extends AccessibleContext 3202 implements Accessible, AccessibleComponent, AccessibleAction { 3203 private JList<E> parent = null; 3204 int indexInParent; 3205 private Component component = null; 3206 private AccessibleContext accessibleContext = null; 3207 private ListModel<E> listModel; 3208 private ListCellRenderer<? super E> cellRenderer = null; 3209 3210 /** 3211 * Constructs an {@code AccessibleJListChild}. 3212 * @param parent the parent 3213 * @param indexInParent the index in the parent 3214 */ 3215 public AccessibleJListChild(JList<E> parent, int indexInParent) { 3216 this.parent = parent; 3217 this.setAccessibleParent(parent); 3218 this.indexInParent = indexInParent; 3219 if (parent != null) { 3220 listModel = parent.getModel(); 3221 cellRenderer = parent.getCellRenderer(); 3222 } 3223 } 3224 3225 private Component getCurrentComponent() { 3226 return getComponentAtIndex(indexInParent); 3227 } 3228 3229 AccessibleContext getCurrentAccessibleContext() { 3230 Component c = getComponentAtIndex(indexInParent); 3231 if (c instanceof Accessible) { 3232 return c.getAccessibleContext(); 3233 } else { 3234 return null; 3235 } 3236 } 3237 3238 private Component getComponentAtIndex(int index) { 3239 if (index < 0 || index >= listModel.getSize()) { 3240 return null; 3241 } 3242 if ((parent != null) 3243 && (listModel != null) 3244 && cellRenderer != null) { 3245 E value = listModel.getElementAt(index); 3246 boolean isSelected = parent.isSelectedIndex(index); 3247 boolean isFocussed = parent.isFocusOwner() 3248 && (index == parent.getLeadSelectionIndex()); 3249 return cellRenderer.getListCellRendererComponent( 3250 parent, 3251 value, 3252 index, 3253 isSelected, 3254 isFocussed); 3255 } else { 3256 return null; 3257 } 3258 } 3259 3260 3261 // Accessible Methods 3262 /** 3263 * Get the AccessibleContext for this object. In the 3264 * implementation of the Java Accessibility API for this class, 3265 * returns this object, which is its own AccessibleContext. 3266 * 3267 * @return this object 3268 */ 3269 public AccessibleContext getAccessibleContext() { 3270 return this; 3271 } 3272 3273 3274 // AccessibleContext methods 3275 3276 public String getAccessibleName() { 3277 AccessibleContext ac = getCurrentAccessibleContext(); 3278 if (ac != null) { 3279 return ac.getAccessibleName(); 3280 } else { 3281 return null; 3282 } 3283 } 3284 3285 public void setAccessibleName(String s) { 3286 AccessibleContext ac = getCurrentAccessibleContext(); 3287 if (ac != null) { 3288 ac.setAccessibleName(s); 3289 } 3290 } 3291 3292 public String getAccessibleDescription() { 3293 AccessibleContext ac = getCurrentAccessibleContext(); 3294 if (ac != null) { 3295 return ac.getAccessibleDescription(); 3296 } else { 3297 return null; 3298 } 3299 } 3300 3301 public void setAccessibleDescription(String s) { 3302 AccessibleContext ac = getCurrentAccessibleContext(); 3303 if (ac != null) { 3304 ac.setAccessibleDescription(s); 3305 } 3306 } 3307 3308 public AccessibleRole getAccessibleRole() { 3309 AccessibleContext ac = getCurrentAccessibleContext(); 3310 if (ac != null) { 3311 return ac.getAccessibleRole(); 3312 } else { 3313 return null; 3314 } 3315 } 3316 3317 public AccessibleStateSet getAccessibleStateSet() { 3318 AccessibleContext ac = getCurrentAccessibleContext(); 3319 AccessibleStateSet s; 3320 if (ac != null) { 3321 s = ac.getAccessibleStateSet(); 3322 } else { 3323 s = new AccessibleStateSet(); 3324 } 3325 3326 s.add(AccessibleState.SELECTABLE); 3327 if (parent.isFocusOwner() 3328 && (indexInParent == parent.getLeadSelectionIndex())) { 3329 s.add(AccessibleState.ACTIVE); 3330 } 3331 if (parent.isSelectedIndex(indexInParent)) { 3332 s.add(AccessibleState.SELECTED); 3333 } 3334 if (this.isShowing()) { 3335 s.add(AccessibleState.SHOWING); 3336 } else if (s.contains(AccessibleState.SHOWING)) { 3337 s.remove(AccessibleState.SHOWING); 3338 } 3339 if (this.isVisible()) { 3340 s.add(AccessibleState.VISIBLE); 3341 } else if (s.contains(AccessibleState.VISIBLE)) { 3342 s.remove(AccessibleState.VISIBLE); 3343 } 3344 s.add(AccessibleState.TRANSIENT); // cell-rendered 3345 return s; 3346 } 3347 3348 public int getAccessibleIndexInParent() { 3349 return indexInParent; 3350 } 3351 3352 public int getAccessibleChildrenCount() { 3353 AccessibleContext ac = getCurrentAccessibleContext(); 3354 if (ac != null) { 3355 return ac.getAccessibleChildrenCount(); 3356 } else { 3357 return 0; 3358 } 3359 } 3360 3361 public Accessible getAccessibleChild(int i) { 3362 AccessibleContext ac = getCurrentAccessibleContext(); 3363 if (ac != null) { 3364 Accessible accessibleChild = ac.getAccessibleChild(i); 3365 ac.setAccessibleParent(this); 3366 return accessibleChild; 3367 } else { 3368 return null; 3369 } 3370 } 3371 3372 public Locale getLocale() { 3373 AccessibleContext ac = getCurrentAccessibleContext(); 3374 if (ac != null) { 3375 return ac.getLocale(); 3376 } else { 3377 return null; 3378 } 3379 } 3380 3381 public void addPropertyChangeListener(PropertyChangeListener l) { 3382 AccessibleContext ac = getCurrentAccessibleContext(); 3383 if (ac != null) { 3384 ac.addPropertyChangeListener(l); 3385 } 3386 } 3387 3388 public void removePropertyChangeListener(PropertyChangeListener l) { 3389 AccessibleContext ac = getCurrentAccessibleContext(); 3390 if (ac != null) { 3391 ac.removePropertyChangeListener(l); 3392 } 3393 } 3394 3395 /** 3396 * Get the AccessibleComponent associated with this object. In the 3397 * implementation of the Java Accessibility API for this class, 3398 * return this object, which is responsible for implementing the 3399 * AccessibleComponent interface on behalf of itself. 3400 * 3401 * @return this object 3402 */ 3403 public AccessibleComponent getAccessibleComponent() { 3404 return this; // to override getBounds() 3405 } 3406 3407 public AccessibleSelection getAccessibleSelection() { 3408 AccessibleContext ac = getCurrentAccessibleContext(); 3409 return ac != null ? ac.getAccessibleSelection() : null; 3410 } 3411 3412 public AccessibleText getAccessibleText() { 3413 AccessibleContext ac = getCurrentAccessibleContext(); 3414 return ac != null ? ac.getAccessibleText() : null; 3415 } 3416 3417 public AccessibleValue getAccessibleValue() { 3418 AccessibleContext ac = getCurrentAccessibleContext(); 3419 return ac != null ? ac.getAccessibleValue() : null; 3420 } 3421 3422 3423 // AccessibleComponent methods 3424 3425 public Color getBackground() { 3426 AccessibleContext ac = getCurrentAccessibleContext(); 3427 if (ac instanceof AccessibleComponent) { 3428 return ((AccessibleComponent) ac).getBackground(); 3429 } else { 3430 Component c = getCurrentComponent(); 3431 if (c != null) { 3432 return c.getBackground(); 3433 } else { 3434 return null; 3435 } 3436 } 3437 } 3438 3439 public void setBackground(Color c) { 3440 AccessibleContext ac = getCurrentAccessibleContext(); 3441 if (ac instanceof AccessibleComponent) { 3442 ((AccessibleComponent) ac).setBackground(c); 3443 } else { 3444 Component cp = getCurrentComponent(); 3445 if (cp != null) { 3446 cp.setBackground(c); 3447 } 3448 } 3449 } 3450 3451 public Color getForeground() { 3452 AccessibleContext ac = getCurrentAccessibleContext(); 3453 if (ac instanceof AccessibleComponent) { 3454 return ((AccessibleComponent) ac).getForeground(); 3455 } else { 3456 Component c = getCurrentComponent(); 3457 if (c != null) { 3458 return c.getForeground(); 3459 } else { 3460 return null; 3461 } 3462 } 3463 } 3464 3465 public void setForeground(Color c) { 3466 AccessibleContext ac = getCurrentAccessibleContext(); 3467 if (ac instanceof AccessibleComponent) { 3468 ((AccessibleComponent) ac).setForeground(c); 3469 } else { 3470 Component cp = getCurrentComponent(); 3471 if (cp != null) { 3472 cp.setForeground(c); 3473 } 3474 } 3475 } 3476 3477 public Cursor getCursor() { 3478 AccessibleContext ac = getCurrentAccessibleContext(); 3479 if (ac instanceof AccessibleComponent) { 3480 return ((AccessibleComponent) ac).getCursor(); 3481 } else { 3482 Component c = getCurrentComponent(); 3483 if (c != null) { 3484 return c.getCursor(); 3485 } else { 3486 Accessible ap = getAccessibleParent(); 3487 if (ap instanceof AccessibleComponent) { 3488 return ((AccessibleComponent) ap).getCursor(); 3489 } else { 3490 return null; 3491 } 3492 } 3493 } 3494 } 3495 3496 public void setCursor(Cursor c) { 3497 AccessibleContext ac = getCurrentAccessibleContext(); 3498 if (ac instanceof AccessibleComponent) { 3499 ((AccessibleComponent) ac).setCursor(c); 3500 } else { 3501 Component cp = getCurrentComponent(); 3502 if (cp != null) { 3503 cp.setCursor(c); 3504 } 3505 } 3506 } 3507 3508 public Font getFont() { 3509 AccessibleContext ac = getCurrentAccessibleContext(); 3510 if (ac instanceof AccessibleComponent) { 3511 return ((AccessibleComponent) ac).getFont(); 3512 } else { 3513 Component c = getCurrentComponent(); 3514 if (c != null) { 3515 return c.getFont(); 3516 } else { 3517 return null; 3518 } 3519 } 3520 } 3521 3522 public void setFont(Font f) { 3523 AccessibleContext ac = getCurrentAccessibleContext(); 3524 if (ac instanceof AccessibleComponent) { 3525 ((AccessibleComponent) ac).setFont(f); 3526 } else { 3527 Component c = getCurrentComponent(); 3528 if (c != null) { 3529 c.setFont(f); 3530 } 3531 } 3532 } 3533 3534 public FontMetrics getFontMetrics(Font f) { 3535 AccessibleContext ac = getCurrentAccessibleContext(); 3536 if (ac instanceof AccessibleComponent) { 3537 return ((AccessibleComponent) ac).getFontMetrics(f); 3538 } else { 3539 Component c = getCurrentComponent(); 3540 if (c != null) { 3541 return c.getFontMetrics(f); 3542 } else { 3543 return null; 3544 } 3545 } 3546 } 3547 3548 public boolean isEnabled() { 3549 AccessibleContext ac = getCurrentAccessibleContext(); 3550 if (ac instanceof AccessibleComponent) { 3551 return ((AccessibleComponent) ac).isEnabled(); 3552 } else { 3553 Component c = getCurrentComponent(); 3554 if (c != null) { 3555 return c.isEnabled(); 3556 } else { 3557 return false; 3558 } 3559 } 3560 } 3561 3562 public void setEnabled(boolean b) { 3563 AccessibleContext ac = getCurrentAccessibleContext(); 3564 if (ac instanceof AccessibleComponent) { 3565 ((AccessibleComponent) ac).setEnabled(b); 3566 } else { 3567 Component c = getCurrentComponent(); 3568 if (c != null) { 3569 c.setEnabled(b); 3570 } 3571 } 3572 } 3573 3574 public boolean isVisible() { 3575 int fi = parent.getFirstVisibleIndex(); 3576 int li = parent.getLastVisibleIndex(); 3577 // The UI incorrectly returns a -1 for the last 3578 // visible index if the list is smaller than the 3579 // viewport size. 3580 if (li == -1) { 3581 li = parent.getModel().getSize() - 1; 3582 } 3583 return ((indexInParent >= fi) 3584 && (indexInParent <= li)); 3585 } 3586 3587 public void setVisible(boolean b) { 3588 } 3589 3590 public boolean isShowing() { 3591 return (parent.isShowing() && isVisible()); 3592 } 3593 3594 public boolean contains(Point p) { 3595 AccessibleContext ac = getCurrentAccessibleContext(); 3596 if (ac instanceof AccessibleComponent) { 3597 Rectangle r = ((AccessibleComponent) ac).getBounds(); 3598 return r.contains(p); 3599 } else { 3600 Component c = getCurrentComponent(); 3601 if (c != null) { 3602 Rectangle r = c.getBounds(); 3603 return r.contains(p); 3604 } else { 3605 return getBounds().contains(p); 3606 } 3607 } 3608 } 3609 3610 public Point getLocationOnScreen() { 3611 if (parent != null) { 3612 Point listLocation; 3613 try { 3614 listLocation = parent.getLocationOnScreen(); 3615 } catch (IllegalComponentStateException e) { 3616 // This can happen if the component isn't visisble 3617 return null; 3618 } 3619 Point componentLocation = parent.indexToLocation(indexInParent); 3620 if (componentLocation != null) { 3621 componentLocation.translate(listLocation.x, listLocation.y); 3622 return componentLocation; 3623 } else { 3624 return null; 3625 } 3626 } else { 3627 return null; 3628 } 3629 } 3630 3631 public Point getLocation() { 3632 if (parent != null) { 3633 return parent.indexToLocation(indexInParent); 3634 } else { 3635 return null; 3636 } 3637 } 3638 3639 public void setLocation(Point p) { 3640 if ((parent != null) && (parent.contains(p))) { 3641 ensureIndexIsVisible(indexInParent); 3642 } 3643 } 3644 3645 public Rectangle getBounds() { 3646 if (parent != null) { 3647 return parent.getCellBounds(indexInParent,indexInParent); 3648 } else { 3649 return null; 3650 } 3651 } 3652 3653 public void setBounds(Rectangle r) { 3654 AccessibleContext ac = getCurrentAccessibleContext(); 3655 if (ac instanceof AccessibleComponent) { 3656 ((AccessibleComponent) ac).setBounds(r); 3657 } 3658 } 3659 3660 public Dimension getSize() { 3661 Rectangle cellBounds = this.getBounds(); 3662 if (cellBounds != null) { 3663 return cellBounds.getSize(); 3664 } else { 3665 return null; 3666 } 3667 } 3668 3669 public void setSize (Dimension d) { 3670 AccessibleContext ac = getCurrentAccessibleContext(); 3671 if (ac instanceof AccessibleComponent) { 3672 ((AccessibleComponent) ac).setSize(d); 3673 } else { 3674 Component c = getCurrentComponent(); 3675 if (c != null) { 3676 c.setSize(d); 3677 } 3678 } 3679 } 3680 3681 public Accessible getAccessibleAt(Point p) { 3682 AccessibleContext ac = getCurrentAccessibleContext(); 3683 if (ac instanceof AccessibleComponent) { 3684 return ((AccessibleComponent) ac).getAccessibleAt(p); 3685 } else { 3686 return null; 3687 } 3688 } 3689 3690 @SuppressWarnings("deprecation") 3691 public boolean isFocusTraversable() { 3692 AccessibleContext ac = getCurrentAccessibleContext(); 3693 if (ac instanceof AccessibleComponent) { 3694 return ((AccessibleComponent) ac).isFocusTraversable(); 3695 } else { 3696 Component c = getCurrentComponent(); 3697 if (c != null) { 3698 return c.isFocusTraversable(); 3699 } else { 3700 return false; 3701 } 3702 } 3703 } 3704 3705 public void requestFocus() { 3706 AccessibleContext ac = getCurrentAccessibleContext(); 3707 if (ac instanceof AccessibleComponent) { 3708 ((AccessibleComponent) ac).requestFocus(); 3709 } else { 3710 Component c = getCurrentComponent(); 3711 if (c != null) { 3712 c.requestFocus(); 3713 } 3714 } 3715 } 3716 3717 public void addFocusListener(FocusListener l) { 3718 AccessibleContext ac = getCurrentAccessibleContext(); 3719 if (ac instanceof AccessibleComponent) { 3720 ((AccessibleComponent) ac).addFocusListener(l); 3721 } else { 3722 Component c = getCurrentComponent(); 3723 if (c != null) { 3724 c.addFocusListener(l); 3725 } 3726 } 3727 } 3728 3729 public void removeFocusListener(FocusListener l) { 3730 AccessibleContext ac = getCurrentAccessibleContext(); 3731 if (ac instanceof AccessibleComponent) { 3732 ((AccessibleComponent) ac).removeFocusListener(l); 3733 } else { 3734 Component c = getCurrentComponent(); 3735 if (c != null) { 3736 c.removeFocusListener(l); 3737 } 3738 } 3739 } 3740 3741 // TIGER - 4733624 3742 /** 3743 * Returns the icon for the element renderer, as the only item 3744 * of an array of <code>AccessibleIcon</code>s or a <code>null</code> array 3745 * if the renderer component contains no icons. 3746 * 3747 * @return an array containing the accessible icon 3748 * or a <code>null</code> array if none 3749 * @since 1.3 3750 */ 3751 public AccessibleIcon [] getAccessibleIcon() { 3752 AccessibleContext ac = getCurrentAccessibleContext(); 3753 if (ac != null) { 3754 return ac.getAccessibleIcon(); 3755 } else { 3756 return null; 3757 } 3758 } 3759 3760 /** 3761 * {@inheritDoc} 3762 * @implSpec Returns the AccessibleAction for this AccessibleJListChild 3763 * as follows: First getListCellRendererComponent of the ListCellRenderer 3764 * for the component at the "index in parent" of this child is called. 3765 * Then its AccessibleContext is fetched and that AccessibleContext's 3766 * AccessibleAction is returned. Note that if an AccessibleAction 3767 * is not found using this process then this object with its implementation 3768 * of the AccessibleAction interface is returned. 3769 * @since 9 3770 */ 3771 @Override 3772 public AccessibleAction getAccessibleAction() { 3773 AccessibleContext ac = getCurrentAccessibleContext(); 3774 if (ac == null) { 3775 return null; 3776 } else { 3777 AccessibleAction aa = ac.getAccessibleAction(); 3778 if (aa != null) { 3779 return aa; 3780 } else { 3781 return this; 3782 } 3783 } 3784 } 3785 3786 /** 3787 * {@inheritDoc} 3788 * @implSpec If i == 0 selects this AccessibleJListChild by calling 3789 * JList.this.setSelectedIndex(indexInParent) and then returns true; 3790 * otherwise returns false. 3791 * @since 9 3792 */ 3793 @Override 3794 public boolean doAccessibleAction(int i) { 3795 if (i == 0) { 3796 JList.this.setSelectedIndex(indexInParent); 3797 return true; 3798 } else { 3799 return false; 3800 } 3801 } 3802 3803 /** 3804 * {@inheritDoc} 3805 * @implSpec If i == 0 returns the action description fetched from 3806 * UIManager.getString("AbstractButton.clickText"); 3807 * otherwise returns null. 3808 * @since 9 3809 */ 3810 @Override 3811 public String getAccessibleActionDescription(int i) { 3812 if (i == 0) { 3813 return UIManager.getString("AbstractButton.clickText"); 3814 } else { 3815 return null; 3816 } 3817 } 3818 3819 /** 3820 * {@inheritDoc} 3821 * @implSpec Returns 1, i.e. there is only one action. 3822 * @since 9 3823 */ 3824 @Override 3825 public int getAccessibleActionCount() { 3826 return 1; 3827 } 3828 3829 } // inner class AccessibleJListChild 3830 3831 } // inner class AccessibleJList 3832 }