1 /* 2 * Copyright (c) 1997, 2016, Oracle and/or its affiliates. All rights reserved. 3 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. 4 * 5 * This code is free software; you can redistribute it and/or modify it 6 * under the terms of the GNU General Public License version 2 only, as 7 * published by the Free Software Foundation. Oracle designates this 8 * particular file as subject to the "Classpath" exception as provided 9 * by Oracle in the LICENSE file that accompanied this code. 10 * 11 * This code is distributed in the hope that it will be useful, but WITHOUT 12 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or 13 * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License 14 * version 2 for more details (a copy is included in the LICENSE file that 15 * accompanied this code). 16 * 17 * You should have received a copy of the GNU General Public License version 18 * 2 along with this work; if not, write to the Free Software Foundation, 19 * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. 20 * 21 * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA 22 * or visit www.oracle.com if you need additional information or have any 23 * questions. 24 */ 25 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 name="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 name="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 border="1" 966 * summary="Describes layouts VERTICAL, HORIZONTAL_WRAP, and VERTICAL_WRAP"> 967 * <tr><th><p style="text-align:left">Value</p></th><th><p style="text-align:left">Description</p></th></tr> 968 * <tr><td><code>VERTICAL</code> 969 * <td>Cells are layed out vertically in a single column. 970 * <tr><td><code>HORIZONTAL_WRAP</code> 971 * <td>Cells are layed out horizontally, wrapping to a new row as 972 * necessary. If the {@code visibleRowCount} property is less than 973 * or equal to zero, wrapping is determined by the width of the 974 * list; otherwise wrapping is done in such a way as to ensure 975 * {@code visibleRowCount} rows in the list. 976 * <tr><td><code>VERTICAL_WRAP</code> 977 * <td>Cells are layed out vertically, wrapping to a new column as 978 * necessary. If the {@code visibleRowCount} property is less than 979 * or equal to zero, wrapping is determined by the height of the 980 * list; otherwise wrapping is done at {@code visibleRowCount} rows. 981 * </table> 982 * <p> 983 * The default value of this property is <code>VERTICAL</code>. 984 * 985 * @param layoutOrientation the new layout orientation, one of: 986 * {@code VERTICAL}, {@code HORIZONTAL_WRAP} or {@code VERTICAL_WRAP} 987 * @see #getLayoutOrientation 988 * @see #setVisibleRowCount 989 * @see #getScrollableTracksViewportHeight 990 * @see #getScrollableTracksViewportWidth 991 * @throws IllegalArgumentException if {@code layoutOrientation} isn't one of the 992 * allowable values 993 * @since 1.4 994 */ 995 @BeanProperty(visualUpdate = true, enumerationValues = { 996 "JList.VERTICAL", 997 "JList.HORIZONTAL_WRAP", 998 "JList.VERTICAL_WRAP"}, description 999 = "Defines the way list cells are layed out.") 1000 public void setLayoutOrientation(int layoutOrientation) { 1001 int oldValue = this.layoutOrientation; 1002 switch (layoutOrientation) { 1003 case VERTICAL: 1004 case VERTICAL_WRAP: 1005 case HORIZONTAL_WRAP: 1006 this.layoutOrientation = layoutOrientation; 1007 firePropertyChange("layoutOrientation", oldValue, layoutOrientation); 1008 break; 1009 default: 1010 throw new IllegalArgumentException("layoutOrientation must be one of: VERTICAL, HORIZONTAL_WRAP or VERTICAL_WRAP"); 1011 } 1012 } 1013 1014 1015 /** 1016 * Returns the smallest list index that is currently visible. 1017 * In a left-to-right {@code componentOrientation}, the first visible 1018 * cell is found closest to the list's upper-left corner. In right-to-left 1019 * orientation, it is found closest to the upper-right corner. 1020 * If nothing is visible or the list is empty, {@code -1} is returned. 1021 * Note that the returned cell may only be partially visible. 1022 * 1023 * @return the index of the first visible cell 1024 * @see #getLastVisibleIndex 1025 * @see JComponent#getVisibleRect 1026 */ 1027 @BeanProperty(bound = false) 1028 public int getFirstVisibleIndex() { 1029 Rectangle r = getVisibleRect(); 1030 int first; 1031 if (this.getComponentOrientation().isLeftToRight()) { 1032 first = locationToIndex(r.getLocation()); 1033 } else { 1034 first = locationToIndex(new Point((r.x + r.width) - 1, r.y)); 1035 } 1036 if (first != -1) { 1037 Rectangle bounds = getCellBounds(first, first); 1038 if (bounds != null) { 1039 SwingUtilities.computeIntersection(r.x, r.y, r.width, r.height, bounds); 1040 if (bounds.width == 0 || bounds.height == 0) { 1041 first = -1; 1042 } 1043 } 1044 } 1045 return first; 1046 } 1047 1048 1049 /** 1050 * Returns the largest list index that is currently visible. 1051 * If nothing is visible or the list is empty, {@code -1} is returned. 1052 * Note that the returned cell may only be partially visible. 1053 * 1054 * @return the index of the last visible cell 1055 * @see #getFirstVisibleIndex 1056 * @see JComponent#getVisibleRect 1057 */ 1058 @BeanProperty(bound = false) 1059 public int getLastVisibleIndex() { 1060 boolean leftToRight = this.getComponentOrientation().isLeftToRight(); 1061 Rectangle r = getVisibleRect(); 1062 Point lastPoint; 1063 if (leftToRight) { 1064 lastPoint = new Point((r.x + r.width) - 1, (r.y + r.height) - 1); 1065 } else { 1066 lastPoint = new Point(r.x, (r.y + r.height) - 1); 1067 } 1068 int location = locationToIndex(lastPoint); 1069 1070 if (location != -1) { 1071 Rectangle bounds = getCellBounds(location, location); 1072 1073 if (bounds != null) { 1074 SwingUtilities.computeIntersection(r.x, r.y, r.width, r.height, bounds); 1075 if (bounds.width == 0 || bounds.height == 0) { 1076 // Try the top left(LTR) or top right(RTL) corner, and 1077 // then go across checking each cell for HORIZONTAL_WRAP. 1078 // Try the lower left corner, and then go across checking 1079 // each cell for other list layout orientation. 1080 boolean isHorizontalWrap = 1081 (getLayoutOrientation() == HORIZONTAL_WRAP); 1082 Point visibleLocation = isHorizontalWrap ? 1083 new Point(lastPoint.x, r.y) : 1084 new Point(r.x, lastPoint.y); 1085 int last; 1086 int visIndex = -1; 1087 int lIndex = location; 1088 location = -1; 1089 1090 do { 1091 last = visIndex; 1092 visIndex = locationToIndex(visibleLocation); 1093 1094 if (visIndex != -1) { 1095 bounds = getCellBounds(visIndex, visIndex); 1096 if (visIndex != lIndex && bounds != null && 1097 bounds.contains(visibleLocation)) { 1098 location = visIndex; 1099 if (isHorizontalWrap) { 1100 visibleLocation.y = bounds.y + bounds.height; 1101 if (visibleLocation.y >= lastPoint.y) { 1102 // Past visible region, bail. 1103 last = visIndex; 1104 } 1105 } 1106 else { 1107 visibleLocation.x = bounds.x + bounds.width; 1108 if (visibleLocation.x >= lastPoint.x) { 1109 // Past visible region, bail. 1110 last = visIndex; 1111 } 1112 } 1113 1114 } 1115 else { 1116 last = visIndex; 1117 } 1118 } 1119 } while (visIndex != -1 && last != visIndex); 1120 } 1121 } 1122 } 1123 return location; 1124 } 1125 1126 1127 /** 1128 * Scrolls the list within an enclosing viewport to make the specified 1129 * cell completely visible. This calls {@code scrollRectToVisible} with 1130 * the bounds of the specified cell. For this method to work, the 1131 * {@code JList} must be within a <code>JViewport</code>. 1132 * <p> 1133 * If the given index is outside the list's range of cells, this method 1134 * results in nothing. 1135 * 1136 * @param index the index of the cell to make visible 1137 * @see JComponent#scrollRectToVisible 1138 * @see #getVisibleRect 1139 */ 1140 public void ensureIndexIsVisible(int index) { 1141 Rectangle cellBounds = getCellBounds(index, index); 1142 if (cellBounds != null) { 1143 scrollRectToVisible(cellBounds); 1144 } 1145 } 1146 1147 /** 1148 * Turns on or off automatic drag handling. In order to enable automatic 1149 * drag handling, this property should be set to {@code true}, and the 1150 * list's {@code TransferHandler} needs to be {@code non-null}. 1151 * The default value of the {@code dragEnabled} property is {@code false}. 1152 * <p> 1153 * The job of honoring this property, and recognizing a user drag gesture, 1154 * lies with the look and feel implementation, and in particular, the list's 1155 * {@code ListUI}. When automatic drag handling is enabled, most look and 1156 * feels (including those that subclass {@code BasicLookAndFeel}) begin a 1157 * drag and drop operation whenever the user presses the mouse button over 1158 * an item and then moves the mouse a few pixels. Setting this property to 1159 * {@code true} can therefore have a subtle effect on how selections behave. 1160 * <p> 1161 * If a look and feel is used that ignores this property, you can still 1162 * begin a drag and drop operation by calling {@code exportAsDrag} on the 1163 * list's {@code TransferHandler}. 1164 * 1165 * @param b whether or not to enable automatic drag handling 1166 * @exception HeadlessException if 1167 * <code>b</code> is <code>true</code> and 1168 * <code>GraphicsEnvironment.isHeadless()</code> 1169 * returns <code>true</code> 1170 * @see java.awt.GraphicsEnvironment#isHeadless 1171 * @see #getDragEnabled 1172 * @see #setTransferHandler 1173 * @see TransferHandler 1174 * @since 1.4 1175 */ 1176 @BeanProperty(bound = false, description 1177 = "determines whether automatic drag handling is enabled") 1178 public void setDragEnabled(boolean b) { 1179 if (b && GraphicsEnvironment.isHeadless()) { 1180 throw new HeadlessException(); 1181 } 1182 dragEnabled = b; 1183 } 1184 1185 /** 1186 * Returns whether or not automatic drag handling is enabled. 1187 * 1188 * @return the value of the {@code dragEnabled} property 1189 * @see #setDragEnabled 1190 * @since 1.4 1191 */ 1192 public boolean getDragEnabled() { 1193 return dragEnabled; 1194 } 1195 1196 /** 1197 * Sets the drop mode for this component. For backward compatibility, 1198 * the default for this property is <code>DropMode.USE_SELECTION</code>. 1199 * Usage of one of the other modes is recommended, however, for an 1200 * improved user experience. <code>DropMode.ON</code>, for instance, 1201 * offers similar behavior of showing items as selected, but does so without 1202 * affecting the actual selection in the list. 1203 * <p> 1204 * <code>JList</code> supports the following drop modes: 1205 * <ul> 1206 * <li><code>DropMode.USE_SELECTION</code></li> 1207 * <li><code>DropMode.ON</code></li> 1208 * <li><code>DropMode.INSERT</code></li> 1209 * <li><code>DropMode.ON_OR_INSERT</code></li> 1210 * </ul> 1211 * The drop mode is only meaningful if this component has a 1212 * <code>TransferHandler</code> that accepts drops. 1213 * 1214 * @param dropMode the drop mode to use 1215 * @throws IllegalArgumentException if the drop mode is unsupported 1216 * or <code>null</code> 1217 * @see #getDropMode 1218 * @see #getDropLocation 1219 * @see #setTransferHandler 1220 * @see TransferHandler 1221 * @since 1.6 1222 */ 1223 public final void setDropMode(DropMode dropMode) { 1224 if (dropMode != null) { 1225 switch (dropMode) { 1226 case USE_SELECTION: 1227 case ON: 1228 case INSERT: 1229 case ON_OR_INSERT: 1230 this.dropMode = dropMode; 1231 return; 1232 } 1233 } 1234 1235 throw new IllegalArgumentException(dropMode + ": Unsupported drop mode for list"); 1236 } 1237 1238 /** 1239 * Returns the drop mode for this component. 1240 * 1241 * @return the drop mode for this component 1242 * @see #setDropMode 1243 * @since 1.6 1244 */ 1245 public final DropMode getDropMode() { 1246 return dropMode; 1247 } 1248 1249 /** 1250 * Calculates a drop location in this component, representing where a 1251 * drop at the given point should insert data. 1252 * 1253 * @param p the point to calculate a drop location for 1254 * @return the drop location, or <code>null</code> 1255 */ 1256 DropLocation dropLocationForPoint(Point p) { 1257 DropLocation location = null; 1258 Rectangle rect = null; 1259 1260 int index = locationToIndex(p); 1261 if (index != -1) { 1262 rect = getCellBounds(index, index); 1263 } 1264 1265 switch(dropMode) { 1266 case USE_SELECTION: 1267 case ON: 1268 location = new DropLocation(p, 1269 (rect != null && rect.contains(p)) ? index : -1, 1270 false); 1271 1272 break; 1273 case INSERT: 1274 if (index == -1) { 1275 location = new DropLocation(p, getModel().getSize(), true); 1276 break; 1277 } 1278 1279 if (layoutOrientation == HORIZONTAL_WRAP) { 1280 boolean ltr = getComponentOrientation().isLeftToRight(); 1281 1282 if (SwingUtilities2.liesInHorizontal(rect, p, ltr, false) == TRAILING) { 1283 index++; 1284 // special case for below all cells 1285 } else if (index == getModel().getSize() - 1 && p.y >= rect.y + rect.height) { 1286 index++; 1287 } 1288 } else { 1289 if (SwingUtilities2.liesInVertical(rect, p, false) == TRAILING) { 1290 index++; 1291 } 1292 } 1293 1294 location = new DropLocation(p, index, true); 1295 1296 break; 1297 case ON_OR_INSERT: 1298 if (index == -1) { 1299 location = new DropLocation(p, getModel().getSize(), true); 1300 break; 1301 } 1302 1303 boolean between = false; 1304 1305 if (layoutOrientation == HORIZONTAL_WRAP) { 1306 boolean ltr = getComponentOrientation().isLeftToRight(); 1307 1308 Section section = SwingUtilities2.liesInHorizontal(rect, p, ltr, true); 1309 if (section == TRAILING) { 1310 index++; 1311 between = true; 1312 // special case for below all cells 1313 } else if (index == getModel().getSize() - 1 && p.y >= rect.y + rect.height) { 1314 index++; 1315 between = true; 1316 } else if (section == LEADING) { 1317 between = true; 1318 } 1319 } else { 1320 Section section = SwingUtilities2.liesInVertical(rect, p, true); 1321 if (section == LEADING) { 1322 between = true; 1323 } else if (section == TRAILING) { 1324 index++; 1325 between = true; 1326 } 1327 } 1328 1329 location = new DropLocation(p, index, between); 1330 1331 break; 1332 default: 1333 assert false : "Unexpected drop mode"; 1334 } 1335 1336 return location; 1337 } 1338 1339 /** 1340 * Called to set or clear the drop location during a DnD operation. 1341 * In some cases, the component may need to use it's internal selection 1342 * temporarily to indicate the drop location. To help facilitate this, 1343 * this method returns and accepts as a parameter a state object. 1344 * This state object can be used to store, and later restore, the selection 1345 * state. Whatever this method returns will be passed back to it in 1346 * future calls, as the state parameter. If it wants the DnD system to 1347 * continue storing the same state, it must pass it back every time. 1348 * Here's how this is used: 1349 * <p> 1350 * Let's say that on the first call to this method the component decides 1351 * to save some state (because it is about to use the selection to show 1352 * a drop index). It can return a state object to the caller encapsulating 1353 * any saved selection state. On a second call, let's say the drop location 1354 * is being changed to something else. The component doesn't need to 1355 * restore anything yet, so it simply passes back the same state object 1356 * to have the DnD system continue storing it. Finally, let's say this 1357 * method is messaged with <code>null</code>. This means DnD 1358 * is finished with this component for now, meaning it should restore 1359 * state. At this point, it can use the state parameter to restore 1360 * said state, and of course return <code>null</code> since there's 1361 * no longer anything to store. 1362 * 1363 * @param location the drop location (as calculated by 1364 * <code>dropLocationForPoint</code>) or <code>null</code> 1365 * if there's no longer a valid drop location 1366 * @param state the state object saved earlier for this component, 1367 * or <code>null</code> 1368 * @param forDrop whether or not the method is being called because an 1369 * actual drop occurred 1370 * @return any saved state for this component, or <code>null</code> if none 1371 */ 1372 Object setDropLocation(TransferHandler.DropLocation location, 1373 Object state, 1374 boolean forDrop) { 1375 1376 Object retVal = null; 1377 DropLocation listLocation = (DropLocation)location; 1378 1379 if (dropMode == DropMode.USE_SELECTION) { 1380 if (listLocation == null) { 1381 if (!forDrop && state != null) { 1382 setSelectedIndices(((int[][])state)[0]); 1383 1384 int anchor = ((int[][])state)[1][0]; 1385 int lead = ((int[][])state)[1][1]; 1386 1387 SwingUtilities2.setLeadAnchorWithoutSelection( 1388 getSelectionModel(), lead, anchor); 1389 } 1390 } else { 1391 if (dropLocation == null) { 1392 int[] inds = getSelectedIndices(); 1393 retVal = new int[][] {inds, {getAnchorSelectionIndex(), 1394 getLeadSelectionIndex()}}; 1395 } else { 1396 retVal = state; 1397 } 1398 1399 int index = listLocation.getIndex(); 1400 if (index == -1) { 1401 clearSelection(); 1402 getSelectionModel().setAnchorSelectionIndex(-1); 1403 getSelectionModel().setLeadSelectionIndex(-1); 1404 } else { 1405 setSelectionInterval(index, index); 1406 } 1407 } 1408 } 1409 1410 DropLocation old = dropLocation; 1411 dropLocation = listLocation; 1412 firePropertyChange("dropLocation", old, dropLocation); 1413 1414 return retVal; 1415 } 1416 1417 /** 1418 * Returns the location that this component should visually indicate 1419 * as the drop location during a DnD operation over the component, 1420 * or {@code null} if no location is to currently be shown. 1421 * <p> 1422 * This method is not meant for querying the drop location 1423 * from a {@code TransferHandler}, as the drop location is only 1424 * set after the {@code TransferHandler}'s <code>canImport</code> 1425 * has returned and has allowed for the location to be shown. 1426 * <p> 1427 * When this property changes, a property change event with 1428 * name "dropLocation" is fired by the component. 1429 * <p> 1430 * By default, responsibility for listening for changes to this property 1431 * and indicating the drop location visually lies with the list's 1432 * {@code ListUI}, which may paint it directly and/or install a cell 1433 * renderer to do so. Developers wishing to implement custom drop location 1434 * painting and/or replace the default cell renderer, may need to honor 1435 * this property. 1436 * 1437 * @return the drop location 1438 * @see #setDropMode 1439 * @see TransferHandler#canImport(TransferHandler.TransferSupport) 1440 * @since 1.6 1441 */ 1442 @BeanProperty(bound = false) 1443 public final DropLocation getDropLocation() { 1444 return dropLocation; 1445 } 1446 1447 /** 1448 * Returns the next list element whose {@code toString} value 1449 * starts with the given prefix. 1450 * 1451 * @param prefix the string to test for a match 1452 * @param startIndex the index for starting the search 1453 * @param bias the search direction, either 1454 * Position.Bias.Forward or Position.Bias.Backward. 1455 * @return the index of the next list element that 1456 * starts with the prefix; otherwise {@code -1} 1457 * @exception IllegalArgumentException if prefix is {@code null} 1458 * or startIndex is out of bounds 1459 * @since 1.4 1460 */ 1461 public int getNextMatch(String prefix, int startIndex, Position.Bias bias) { 1462 ListModel<E> model = getModel(); 1463 int max = model.getSize(); 1464 if (prefix == null) { 1465 throw new IllegalArgumentException(); 1466 } 1467 if (startIndex < 0 || startIndex >= max) { 1468 throw new IllegalArgumentException(); 1469 } 1470 prefix = prefix.toUpperCase(); 1471 1472 // start search from the next element after the selected element 1473 int increment = (bias == Position.Bias.Forward) ? 1 : -1; 1474 int index = startIndex; 1475 do { 1476 E element = model.getElementAt(index); 1477 1478 if (element != null) { 1479 String string; 1480 1481 if (element instanceof String) { 1482 string = ((String)element).toUpperCase(); 1483 } 1484 else { 1485 string = element.toString(); 1486 if (string != null) { 1487 string = string.toUpperCase(); 1488 } 1489 } 1490 1491 if (string != null && string.startsWith(prefix)) { 1492 return index; 1493 } 1494 } 1495 index = (index + increment + max) % max; 1496 } while (index != startIndex); 1497 return -1; 1498 } 1499 1500 /** 1501 * Returns the tooltip text to be used for the given event. This overrides 1502 * {@code JComponent}'s {@code getToolTipText} to first check the cell 1503 * renderer component for the cell over which the event occurred, returning 1504 * its tooltip text, if any. This implementation allows you to specify 1505 * tooltip text on the cell level, by using {@code setToolTipText} on your 1506 * cell renderer component. 1507 * <p> 1508 * <strong>Note:</strong> For <code>JList</code> to properly display the 1509 * tooltips of its renderers in this manner, <code>JList</code> must be a 1510 * registered component with the <code>ToolTipManager</code>. This registration 1511 * is done automatically in the constructor. However, if at a later point 1512 * <code>JList</code> is unregistered, by way of a call to 1513 * {@code setToolTipText(null)}, tips from the renderers will no longer display. 1514 * 1515 * @param event the {@code MouseEvent} to fetch the tooltip text for 1516 * @see JComponent#setToolTipText 1517 * @see JComponent#getToolTipText 1518 */ 1519 public String getToolTipText(MouseEvent event) { 1520 if(event != null) { 1521 Point p = event.getPoint(); 1522 int index = locationToIndex(p); 1523 ListCellRenderer<? super E> r = getCellRenderer(); 1524 Rectangle cellBounds; 1525 1526 if (index != -1 && r != null && (cellBounds = 1527 getCellBounds(index, index)) != null && 1528 cellBounds.contains(p.x, p.y)) { 1529 ListSelectionModel lsm = getSelectionModel(); 1530 Component rComponent = r.getListCellRendererComponent( 1531 this, getModel().getElementAt(index), index, 1532 lsm.isSelectedIndex(index), 1533 (hasFocus() && (lsm.getLeadSelectionIndex() == 1534 index))); 1535 1536 if(rComponent instanceof JComponent) { 1537 MouseEvent newEvent; 1538 1539 p.translate(-cellBounds.x, -cellBounds.y); 1540 newEvent = new MouseEvent(rComponent, event.getID(), 1541 event.getWhen(), 1542 event.getModifiers(), 1543 p.x, p.y, 1544 event.getXOnScreen(), 1545 event.getYOnScreen(), 1546 event.getClickCount(), 1547 event.isPopupTrigger(), 1548 MouseEvent.NOBUTTON); 1549 1550 String tip = ((JComponent)rComponent).getToolTipText( 1551 newEvent); 1552 1553 if (tip != null) { 1554 return tip; 1555 } 1556 } 1557 } 1558 } 1559 return super.getToolTipText(); 1560 } 1561 1562 /** 1563 * --- ListUI Delegations --- 1564 */ 1565 1566 1567 /** 1568 * Returns the cell index closest to the given location in the list's 1569 * coordinate system. To determine if the cell actually contains the 1570 * specified location, compare the point against the cell's bounds, 1571 * as provided by {@code getCellBounds}. This method returns {@code -1} 1572 * if the model is empty 1573 * <p> 1574 * This is a cover method that delegates to the method of the same name 1575 * in the list's {@code ListUI}. It returns {@code -1} if the list has 1576 * no {@code ListUI}. 1577 * 1578 * @param location the coordinates of the point 1579 * @return the cell index closest to the given location, or {@code -1} 1580 */ 1581 public int locationToIndex(Point location) { 1582 ListUI ui = getUI(); 1583 return (ui != null) ? ui.locationToIndex(this, location) : -1; 1584 } 1585 1586 1587 /** 1588 * Returns the origin of the specified item in the list's coordinate 1589 * system. This method returns {@code null} if the index isn't valid. 1590 * <p> 1591 * This is a cover method that delegates to the method of the same name 1592 * in the list's {@code ListUI}. It returns {@code null} if the list has 1593 * no {@code ListUI}. 1594 * 1595 * @param index the cell index 1596 * @return the origin of the cell, or {@code null} 1597 */ 1598 public Point indexToLocation(int index) { 1599 ListUI ui = getUI(); 1600 return (ui != null) ? ui.indexToLocation(this, index) : null; 1601 } 1602 1603 1604 /** 1605 * Returns the bounding rectangle, in the list's coordinate system, 1606 * for the range of cells specified by the two indices. 1607 * These indices can be supplied in any order. 1608 * <p> 1609 * If the smaller index is outside the list's range of cells, this method 1610 * returns {@code null}. If the smaller index is valid, but the larger 1611 * index is outside the list's range, the bounds of just the first index 1612 * is returned. Otherwise, the bounds of the valid range is returned. 1613 * <p> 1614 * This is a cover method that delegates to the method of the same name 1615 * in the list's {@code ListUI}. It returns {@code null} if the list has 1616 * no {@code ListUI}. 1617 * 1618 * @param index0 the first index in the range 1619 * @param index1 the second index in the range 1620 * @return the bounding rectangle for the range of cells, or {@code null} 1621 */ 1622 public Rectangle getCellBounds(int index0, int index1) { 1623 ListUI ui = getUI(); 1624 return (ui != null) ? ui.getCellBounds(this, index0, index1) : null; 1625 } 1626 1627 1628 /** 1629 * --- ListModel Support --- 1630 */ 1631 1632 1633 /** 1634 * Returns the data model that holds the list of items displayed 1635 * by the <code>JList</code> component. 1636 * 1637 * @return the <code>ListModel</code> that provides the displayed 1638 * list of items 1639 * @see #setModel 1640 */ 1641 public ListModel<E> getModel() { 1642 return dataModel; 1643 } 1644 1645 /** 1646 * Sets the model that represents the contents or "value" of the 1647 * list, notifies property change listeners, and then clears the 1648 * list's selection. 1649 * <p> 1650 * This is a JavaBeans bound property. 1651 * 1652 * @param model the <code>ListModel</code> that provides the 1653 * list of items for display 1654 * @exception IllegalArgumentException if <code>model</code> is 1655 * <code>null</code> 1656 * @see #getModel 1657 * @see #clearSelection 1658 */ 1659 @BeanProperty(visualUpdate = true, description 1660 = "The object that contains the data to be drawn by this JList.") 1661 public void setModel(ListModel<E> model) { 1662 if (model == null) { 1663 throw new IllegalArgumentException("model must be non null"); 1664 } 1665 ListModel<E> oldValue = dataModel; 1666 dataModel = model; 1667 firePropertyChange("model", oldValue, dataModel); 1668 clearSelection(); 1669 } 1670 1671 1672 /** 1673 * Constructs a read-only <code>ListModel</code> from an array of items, 1674 * and calls {@code setModel} with this model. 1675 * <p> 1676 * Attempts to pass a {@code null} value to this method results in 1677 * undefined behavior and, most likely, exceptions. The created model 1678 * references the given array directly. Attempts to modify the array 1679 * after invoking this method results in undefined behavior. 1680 * 1681 * @param listData an array of {@code E} containing the items to 1682 * display in the list 1683 * @see #setModel 1684 */ 1685 public void setListData(final E[] listData) { 1686 setModel ( 1687 new AbstractListModel<E>() { 1688 public int getSize() { return listData.length; } 1689 public E getElementAt(int i) { return listData[i]; } 1690 } 1691 ); 1692 } 1693 1694 1695 /** 1696 * Constructs a read-only <code>ListModel</code> from a <code>Vector</code> 1697 * and calls {@code setModel} with this model. 1698 * <p> 1699 * Attempts to pass a {@code null} value to this method results in 1700 * undefined behavior and, most likely, exceptions. The created model 1701 * references the given {@code Vector} directly. Attempts to modify the 1702 * {@code Vector} after invoking this method results in undefined behavior. 1703 * 1704 * @param listData a <code>Vector</code> containing the items to 1705 * display in the list 1706 * @see #setModel 1707 */ 1708 public void setListData(final Vector<? extends E> listData) { 1709 setModel ( 1710 new AbstractListModel<E>() { 1711 public int getSize() { return listData.size(); } 1712 public E getElementAt(int i) { return listData.elementAt(i); } 1713 } 1714 ); 1715 } 1716 1717 1718 /** 1719 * --- ListSelectionModel delegations and extensions --- 1720 */ 1721 1722 1723 /** 1724 * Returns an instance of {@code DefaultListSelectionModel}; called 1725 * during construction to initialize the list's selection model 1726 * property. 1727 * 1728 * @return a {@code DefaultListSelecitonModel}, used to initialize 1729 * the list's selection model property during construction 1730 * @see #setSelectionModel 1731 * @see DefaultListSelectionModel 1732 */ 1733 protected ListSelectionModel createSelectionModel() { 1734 return new DefaultListSelectionModel(); 1735 } 1736 1737 1738 /** 1739 * Returns the current selection model. The selection model maintains the 1740 * selection state of the list. See the class level documentation for more 1741 * details. 1742 * 1743 * @return the <code>ListSelectionModel</code> that maintains the 1744 * list's selections 1745 * 1746 * @see #setSelectionModel 1747 * @see ListSelectionModel 1748 */ 1749 public ListSelectionModel getSelectionModel() { 1750 return selectionModel; 1751 } 1752 1753 1754 /** 1755 * Notifies {@code ListSelectionListener}s added directly to the list 1756 * of selection changes made to the selection model. {@code JList} 1757 * listens for changes made to the selection in the selection model, 1758 * and forwards notification to listeners added to the list directly, 1759 * by calling this method. 1760 * <p> 1761 * This method constructs a {@code ListSelectionEvent} with this list 1762 * as the source, and the specified arguments, and sends it to the 1763 * registered {@code ListSelectionListeners}. 1764 * 1765 * @param firstIndex the first index in the range, {@code <= lastIndex} 1766 * @param lastIndex the last index in the range, {@code >= firstIndex} 1767 * @param isAdjusting whether or not this is one in a series of 1768 * multiple events, where changes are still being made 1769 * 1770 * @see #addListSelectionListener 1771 * @see #removeListSelectionListener 1772 * @see javax.swing.event.ListSelectionEvent 1773 * @see EventListenerList 1774 */ 1775 protected void fireSelectionValueChanged(int firstIndex, int lastIndex, 1776 boolean isAdjusting) 1777 { 1778 Object[] listeners = listenerList.getListenerList(); 1779 ListSelectionEvent e = null; 1780 1781 for (int i = listeners.length - 2; i >= 0; i -= 2) { 1782 if (listeners[i] == ListSelectionListener.class) { 1783 if (e == null) { 1784 e = new ListSelectionEvent(this, firstIndex, lastIndex, 1785 isAdjusting); 1786 } 1787 ((ListSelectionListener)listeners[i+1]).valueChanged(e); 1788 } 1789 } 1790 } 1791 1792 1793 /* A ListSelectionListener that forwards ListSelectionEvents from 1794 * the selectionModel to the JList ListSelectionListeners. The 1795 * forwarded events only differ from the originals in that their 1796 * source is the JList instead of the selectionModel itself. 1797 */ 1798 private class ListSelectionHandler implements ListSelectionListener, Serializable 1799 { 1800 public void valueChanged(ListSelectionEvent e) { 1801 fireSelectionValueChanged(e.getFirstIndex(), 1802 e.getLastIndex(), 1803 e.getValueIsAdjusting()); 1804 } 1805 } 1806 1807 1808 /** 1809 * Adds a listener to the list, to be notified each time a change to the 1810 * selection occurs; the preferred way of listening for selection state 1811 * changes. {@code JList} takes care of listening for selection state 1812 * changes in the selection model, and notifies the given listener of 1813 * each change. {@code ListSelectionEvent}s sent to the listener have a 1814 * {@code source} property set to this list. 1815 * 1816 * @param listener the {@code ListSelectionListener} to add 1817 * @see #getSelectionModel 1818 * @see #getListSelectionListeners 1819 */ 1820 public void addListSelectionListener(ListSelectionListener listener) 1821 { 1822 if (selectionListener == null) { 1823 selectionListener = new ListSelectionHandler(); 1824 getSelectionModel().addListSelectionListener(selectionListener); 1825 } 1826 1827 listenerList.add(ListSelectionListener.class, listener); 1828 } 1829 1830 1831 /** 1832 * Removes a selection listener from the list. 1833 * 1834 * @param listener the {@code ListSelectionListener} to remove 1835 * @see #addListSelectionListener 1836 * @see #getSelectionModel 1837 */ 1838 public void removeListSelectionListener(ListSelectionListener listener) { 1839 listenerList.remove(ListSelectionListener.class, listener); 1840 } 1841 1842 1843 /** 1844 * Returns an array of all the {@code ListSelectionListener}s added 1845 * to this {@code JList} by way of {@code addListSelectionListener}. 1846 * 1847 * @return all of the {@code ListSelectionListener}s on this list, or 1848 * an empty array if no listeners have been added 1849 * @see #addListSelectionListener 1850 * @since 1.4 1851 */ 1852 @BeanProperty(bound = false) 1853 public ListSelectionListener[] getListSelectionListeners() { 1854 return listenerList.getListeners(ListSelectionListener.class); 1855 } 1856 1857 1858 /** 1859 * Sets the <code>selectionModel</code> for the list to a 1860 * non-<code>null</code> <code>ListSelectionModel</code> 1861 * implementation. The selection model handles the task of making single 1862 * selections, selections of contiguous ranges, and non-contiguous 1863 * selections. 1864 * <p> 1865 * This is a JavaBeans bound property. 1866 * 1867 * @param selectionModel the <code>ListSelectionModel</code> that 1868 * implements the selections 1869 * @exception IllegalArgumentException if <code>selectionModel</code> 1870 * is <code>null</code> 1871 * @see #getSelectionModel 1872 */ 1873 @BeanProperty(description 1874 = "The selection model, recording which cells are selected.") 1875 public void setSelectionModel(ListSelectionModel selectionModel) { 1876 if (selectionModel == null) { 1877 throw new IllegalArgumentException("selectionModel must be non null"); 1878 } 1879 1880 /* Remove the forwarding ListSelectionListener from the old 1881 * selectionModel, and add it to the new one, if necessary. 1882 */ 1883 if (selectionListener != null) { 1884 this.selectionModel.removeListSelectionListener(selectionListener); 1885 selectionModel.addListSelectionListener(selectionListener); 1886 } 1887 1888 ListSelectionModel oldValue = this.selectionModel; 1889 this.selectionModel = selectionModel; 1890 firePropertyChange("selectionModel", oldValue, selectionModel); 1891 } 1892 1893 1894 /** 1895 * Sets the selection mode for the list. This is a cover method that sets 1896 * the selection mode directly on the selection model. 1897 * <p> 1898 * The following list describes the accepted selection modes: 1899 * <ul> 1900 * <li>{@code ListSelectionModel.SINGLE_SELECTION} - 1901 * Only one list index can be selected at a time. In this mode, 1902 * {@code setSelectionInterval} and {@code addSelectionInterval} are 1903 * equivalent, both replacing the current selection with the index 1904 * represented by the second argument (the "lead"). 1905 * <li>{@code ListSelectionModel.SINGLE_INTERVAL_SELECTION} - 1906 * Only one contiguous interval can be selected at a time. 1907 * In this mode, {@code addSelectionInterval} behaves like 1908 * {@code setSelectionInterval} (replacing the current selection}, 1909 * unless the given interval is immediately adjacent to or overlaps 1910 * the existing selection, and can be used to grow the selection. 1911 * <li>{@code ListSelectionModel.MULTIPLE_INTERVAL_SELECTION} - 1912 * In this mode, there's no restriction on what can be selected. 1913 * This mode is the default. 1914 * </ul> 1915 * 1916 * @param selectionMode the selection mode 1917 * @see #getSelectionMode 1918 * @throws IllegalArgumentException if the selection mode isn't 1919 * one of those allowed 1920 */ 1921 @BeanProperty(bound = false, enumerationValues = { 1922 "ListSelectionModel.SINGLE_SELECTION", 1923 "ListSelectionModel.SINGLE_INTERVAL_SELECTION", 1924 "ListSelectionModel.MULTIPLE_INTERVAL_SELECTION"}, description 1925 = "The selection mode.") 1926 public void setSelectionMode(int selectionMode) { 1927 getSelectionModel().setSelectionMode(selectionMode); 1928 } 1929 1930 /** 1931 * Returns the current selection mode for the list. This is a cover 1932 * method that delegates to the method of the same name on the 1933 * list's selection model. 1934 * 1935 * @return the current selection mode 1936 * @see #setSelectionMode 1937 */ 1938 public int getSelectionMode() { 1939 return getSelectionModel().getSelectionMode(); 1940 } 1941 1942 1943 /** 1944 * Returns the anchor selection index. This is a cover method that 1945 * delegates to the method of the same name on the list's selection model. 1946 * 1947 * @return the anchor selection index 1948 * @see ListSelectionModel#getAnchorSelectionIndex 1949 */ 1950 @BeanProperty(bound = false) 1951 public int getAnchorSelectionIndex() { 1952 return getSelectionModel().getAnchorSelectionIndex(); 1953 } 1954 1955 1956 /** 1957 * Returns the lead selection index. This is a cover method that 1958 * delegates to the method of the same name on the list's selection model. 1959 * 1960 * @return the lead selection index 1961 * @see ListSelectionModel#getLeadSelectionIndex 1962 */ 1963 @BeanProperty(bound = false, description 1964 = "The lead selection index.") 1965 public int getLeadSelectionIndex() { 1966 return getSelectionModel().getLeadSelectionIndex(); 1967 } 1968 1969 1970 /** 1971 * Returns the smallest selected cell index, or {@code -1} if the selection 1972 * is empty. This is a cover method that delegates to the method of the same 1973 * name on the list's selection model. 1974 * 1975 * @return the smallest selected cell index, or {@code -1} 1976 * @see ListSelectionModel#getMinSelectionIndex 1977 */ 1978 @BeanProperty(bound = false) 1979 public int getMinSelectionIndex() { 1980 return getSelectionModel().getMinSelectionIndex(); 1981 } 1982 1983 1984 /** 1985 * Returns the largest selected cell index, or {@code -1} if the selection 1986 * is empty. This is a cover method that delegates to the method of the same 1987 * name on the list's selection model. 1988 * 1989 * @return the largest selected cell index 1990 * @see ListSelectionModel#getMaxSelectionIndex 1991 */ 1992 @BeanProperty(bound = false) 1993 public int getMaxSelectionIndex() { 1994 return getSelectionModel().getMaxSelectionIndex(); 1995 } 1996 1997 1998 /** 1999 * Returns {@code true} if the specified index is selected, 2000 * else {@code false}. This is a cover method that delegates to the method 2001 * of the same name on the list's selection model. 2002 * 2003 * @param index index to be queried for selection state 2004 * @return {@code true} if the specified index is selected, 2005 * else {@code false} 2006 * @see ListSelectionModel#isSelectedIndex 2007 * @see #setSelectedIndex 2008 */ 2009 public boolean isSelectedIndex(int index) { 2010 return getSelectionModel().isSelectedIndex(index); 2011 } 2012 2013 2014 /** 2015 * Returns {@code true} if nothing is selected, else {@code false}. 2016 * This is a cover method that delegates to the method of the same 2017 * name on the list's selection model. 2018 * 2019 * @return {@code true} if nothing is selected, else {@code false} 2020 * @see ListSelectionModel#isSelectionEmpty 2021 * @see #clearSelection 2022 */ 2023 @BeanProperty(bound = false) 2024 public boolean isSelectionEmpty() { 2025 return getSelectionModel().isSelectionEmpty(); 2026 } 2027 2028 2029 /** 2030 * Clears the selection; after calling this method, {@code isSelectionEmpty} 2031 * will return {@code true}. This is a cover method that delegates to the 2032 * method of the same name on the list's selection model. 2033 * 2034 * @see ListSelectionModel#clearSelection 2035 * @see #isSelectionEmpty 2036 */ 2037 public void clearSelection() { 2038 getSelectionModel().clearSelection(); 2039 } 2040 2041 2042 /** 2043 * Selects the specified interval. Both {@code anchor} and {@code lead} 2044 * indices are included. {@code anchor} doesn't have to be less than or 2045 * equal to {@code lead}. This is a cover method that delegates to the 2046 * method of the same name on the list's selection model. 2047 * <p> 2048 * Refer to the documentation of the selection model class being used 2049 * for details on how values less than {@code 0} are handled. 2050 * 2051 * @param anchor the first index to select 2052 * @param lead the last index to select 2053 * @see ListSelectionModel#setSelectionInterval 2054 * @see DefaultListSelectionModel#setSelectionInterval 2055 * @see #createSelectionModel 2056 * @see #addSelectionInterval 2057 * @see #removeSelectionInterval 2058 */ 2059 public void setSelectionInterval(int anchor, int lead) { 2060 getSelectionModel().setSelectionInterval(anchor, lead); 2061 } 2062 2063 2064 /** 2065 * Sets the selection to be the union of the specified interval with current 2066 * selection. Both the {@code anchor} and {@code lead} indices are 2067 * included. {@code anchor} doesn't have to be less than or 2068 * equal to {@code lead}. This is a cover method that delegates to the 2069 * method of the same name on the list's selection model. 2070 * <p> 2071 * Refer to the documentation of the selection model class being used 2072 * for details on how values less than {@code 0} are handled. 2073 * 2074 * @param anchor the first index to add to the selection 2075 * @param lead the last index to add to the selection 2076 * @see ListSelectionModel#addSelectionInterval 2077 * @see DefaultListSelectionModel#addSelectionInterval 2078 * @see #createSelectionModel 2079 * @see #setSelectionInterval 2080 * @see #removeSelectionInterval 2081 */ 2082 public void addSelectionInterval(int anchor, int lead) { 2083 getSelectionModel().addSelectionInterval(anchor, lead); 2084 } 2085 2086 2087 /** 2088 * Sets the selection to be the set difference of the specified interval 2089 * and the current selection. Both the {@code index0} and {@code index1} 2090 * indices are removed. {@code index0} doesn't have to be less than or 2091 * equal to {@code index1}. This is a cover method that delegates to the 2092 * method of the same name on the list's selection model. 2093 * <p> 2094 * Refer to the documentation of the selection model class being used 2095 * for details on how values less than {@code 0} are handled. 2096 * 2097 * @param index0 the first index to remove from the selection 2098 * @param index1 the last index to remove from the selection 2099 * @see ListSelectionModel#removeSelectionInterval 2100 * @see DefaultListSelectionModel#removeSelectionInterval 2101 * @see #createSelectionModel 2102 * @see #setSelectionInterval 2103 * @see #addSelectionInterval 2104 */ 2105 public void removeSelectionInterval(int index0, int index1) { 2106 getSelectionModel().removeSelectionInterval(index0, index1); 2107 } 2108 2109 2110 /** 2111 * Sets the selection model's {@code valueIsAdjusting} property. When 2112 * {@code true}, upcoming changes to selection should be considered part 2113 * of a single change. This property is used internally and developers 2114 * typically need not call this method. For example, when the model is being 2115 * updated in response to a user drag, the value of the property is set 2116 * to {@code true} when the drag is initiated and set to {@code false} 2117 * when the drag is finished. This allows listeners to update only 2118 * when a change has been finalized, rather than handling all of the 2119 * intermediate values. 2120 * <p> 2121 * You may want to use this directly if making a series of changes 2122 * that should be considered part of a single change. 2123 * <p> 2124 * This is a cover method that delegates to the method of the same name on 2125 * the list's selection model. See the documentation for 2126 * {@link javax.swing.ListSelectionModel#setValueIsAdjusting} for 2127 * more details. 2128 * 2129 * @param b the new value for the property 2130 * @see ListSelectionModel#setValueIsAdjusting 2131 * @see javax.swing.event.ListSelectionEvent#getValueIsAdjusting 2132 * @see #getValueIsAdjusting 2133 */ 2134 public void setValueIsAdjusting(boolean b) { 2135 getSelectionModel().setValueIsAdjusting(b); 2136 } 2137 2138 2139 /** 2140 * Returns the value of the selection model's {@code isAdjusting} property. 2141 * <p> 2142 * This is a cover method that delegates to the method of the same name on 2143 * the list's selection model. 2144 * 2145 * @return the value of the selection model's {@code isAdjusting} property. 2146 * 2147 * @see #setValueIsAdjusting 2148 * @see ListSelectionModel#getValueIsAdjusting 2149 */ 2150 public boolean getValueIsAdjusting() { 2151 return getSelectionModel().getValueIsAdjusting(); 2152 } 2153 2154 2155 /** 2156 * Returns an array of all of the selected indices, in increasing 2157 * order. 2158 * 2159 * @return all of the selected indices, in increasing order, 2160 * or an empty array if nothing is selected 2161 * @see #removeSelectionInterval 2162 * @see #addListSelectionListener 2163 */ 2164 @Transient 2165 public int[] getSelectedIndices() { 2166 ListSelectionModel sm = getSelectionModel(); 2167 int iMin = sm.getMinSelectionIndex(); 2168 int iMax = sm.getMaxSelectionIndex(); 2169 2170 if ((iMin < 0) || (iMax < 0)) { 2171 return new int[0]; 2172 } 2173 2174 int[] rvTmp = new int[1+ (iMax - iMin)]; 2175 int n = 0; 2176 for(int i = iMin; i <= iMax; i++) { 2177 if (sm.isSelectedIndex(i)) { 2178 rvTmp[n++] = i; 2179 } 2180 } 2181 int[] rv = new int[n]; 2182 System.arraycopy(rvTmp, 0, rv, 0, n); 2183 return rv; 2184 } 2185 2186 2187 /** 2188 * Selects a single cell. Does nothing if the given index is greater 2189 * than or equal to the model size. This is a convenience method that uses 2190 * {@code setSelectionInterval} on the selection model. Refer to the 2191 * documentation for the selection model class being used for details on 2192 * how values less than {@code 0} are handled. 2193 * 2194 * @param index the index of the cell to select 2195 * @see ListSelectionModel#setSelectionInterval 2196 * @see #isSelectedIndex 2197 * @see #addListSelectionListener 2198 */ 2199 @BeanProperty(bound = false, description 2200 = "The index of the selected cell.") 2201 public void setSelectedIndex(int index) { 2202 if (index >= getModel().getSize()) { 2203 return; 2204 } 2205 getSelectionModel().setSelectionInterval(index, index); 2206 } 2207 2208 2209 /** 2210 * Changes the selection to be the set of indices specified by the given 2211 * array. Indices greater than or equal to the model size are ignored. 2212 * This is a convenience method that clears the selection and then uses 2213 * {@code addSelectionInterval} on the selection model to add the indices. 2214 * Refer to the documentation of the selection model class being used for 2215 * details on how values less than {@code 0} are handled. 2216 * 2217 * @param indices an array of the indices of the cells to select, 2218 * {@code non-null} 2219 * @see ListSelectionModel#addSelectionInterval 2220 * @see #isSelectedIndex 2221 * @see #addListSelectionListener 2222 * @throws NullPointerException if the given array is {@code null} 2223 */ 2224 public void setSelectedIndices(int[] indices) { 2225 ListSelectionModel sm = getSelectionModel(); 2226 sm.clearSelection(); 2227 int size = getModel().getSize(); 2228 for (int i : indices) { 2229 if (i < size) { 2230 sm.addSelectionInterval(i, i); 2231 } 2232 } 2233 } 2234 2235 2236 /** 2237 * Returns an array of all the selected values, in increasing order based 2238 * on their indices in the list. 2239 * 2240 * @return the selected values, or an empty array if nothing is selected 2241 * @see #isSelectedIndex 2242 * @see #getModel 2243 * @see #addListSelectionListener 2244 * 2245 * @deprecated As of JDK 1.7, replaced by {@link #getSelectedValuesList()} 2246 */ 2247 @Deprecated 2248 @BeanProperty(bound = false) 2249 public Object[] getSelectedValues() { 2250 ListSelectionModel sm = getSelectionModel(); 2251 ListModel<E> dm = getModel(); 2252 2253 int iMin = sm.getMinSelectionIndex(); 2254 int iMax = sm.getMaxSelectionIndex(); 2255 2256 if ((iMin < 0) || (iMax < 0)) { 2257 return new Object[0]; 2258 } 2259 2260 Object[] rvTmp = new Object[1+ (iMax - iMin)]; 2261 int n = 0; 2262 for(int i = iMin; i <= iMax; i++) { 2263 if (sm.isSelectedIndex(i)) { 2264 rvTmp[n++] = dm.getElementAt(i); 2265 } 2266 } 2267 Object[] rv = new Object[n]; 2268 System.arraycopy(rvTmp, 0, rv, 0, n); 2269 return rv; 2270 } 2271 2272 /** 2273 * Returns a list of all the selected items, in increasing order based 2274 * on their indices in the list. 2275 * 2276 * @return the selected items, or an empty list if nothing is selected 2277 * @see #isSelectedIndex 2278 * @see #getModel 2279 * @see #addListSelectionListener 2280 * 2281 * @since 1.7 2282 */ 2283 @BeanProperty(bound = false) 2284 public List<E> getSelectedValuesList() { 2285 ListSelectionModel sm = getSelectionModel(); 2286 ListModel<E> dm = getModel(); 2287 2288 int iMin = sm.getMinSelectionIndex(); 2289 int iMax = sm.getMaxSelectionIndex(); 2290 2291 if ((iMin < 0) || (iMax < 0)) { 2292 return Collections.emptyList(); 2293 } 2294 2295 List<E> selectedItems = new ArrayList<E>(); 2296 for(int i = iMin; i <= iMax; i++) { 2297 if (sm.isSelectedIndex(i)) { 2298 selectedItems.add(dm.getElementAt(i)); 2299 } 2300 } 2301 return selectedItems; 2302 } 2303 2304 2305 /** 2306 * Returns the smallest selected cell index; <i>the selection</i> when only 2307 * a single item is selected in the list. When multiple items are selected, 2308 * it is simply the smallest selected index. Returns {@code -1} if there is 2309 * no selection. 2310 * <p> 2311 * This method is a cover that delegates to {@code getMinSelectionIndex}. 2312 * 2313 * @return the smallest selected cell index 2314 * @see #getMinSelectionIndex 2315 * @see #addListSelectionListener 2316 */ 2317 public int getSelectedIndex() { 2318 return getMinSelectionIndex(); 2319 } 2320 2321 2322 /** 2323 * Returns the value for the smallest selected cell index; 2324 * <i>the selected value</i> when only a single item is selected in the 2325 * list. When multiple items are selected, it is simply the value for the 2326 * smallest selected index. Returns {@code null} if there is no selection. 2327 * <p> 2328 * This is a convenience method that simply returns the model value for 2329 * {@code getMinSelectionIndex}. 2330 * 2331 * @return the first selected value 2332 * @see #getMinSelectionIndex 2333 * @see #getModel 2334 * @see #addListSelectionListener 2335 */ 2336 @BeanProperty(bound = false) 2337 public E getSelectedValue() { 2338 int i = getMinSelectionIndex(); 2339 return (i == -1) ? null : getModel().getElementAt(i); 2340 } 2341 2342 2343 /** 2344 * Selects the specified object from the list. 2345 * 2346 * @param anObject the object to select 2347 * @param shouldScroll {@code true} if the list should scroll to display 2348 * the selected object, if one exists; otherwise {@code false} 2349 */ 2350 public void setSelectedValue(Object anObject,boolean shouldScroll) { 2351 if(anObject == null) 2352 setSelectedIndex(-1); 2353 else if(!anObject.equals(getSelectedValue())) { 2354 int i,c; 2355 ListModel<E> dm = getModel(); 2356 for(i=0,c=dm.getSize();i<c;i++) 2357 if(anObject.equals(dm.getElementAt(i))){ 2358 setSelectedIndex(i); 2359 if(shouldScroll) 2360 ensureIndexIsVisible(i); 2361 repaint(); /** FIX-ME setSelectedIndex does not redraw all the time with the basic l&f**/ 2362 return; 2363 } 2364 setSelectedIndex(-1); 2365 } 2366 repaint(); /** FIX-ME setSelectedIndex does not redraw all the time with the basic l&f**/ 2367 } 2368 2369 2370 2371 /** 2372 * --- The Scrollable Implementation --- 2373 */ 2374 2375 private void checkScrollableParameters(Rectangle visibleRect, int orientation) { 2376 if (visibleRect == null) { 2377 throw new IllegalArgumentException("visibleRect must be non-null"); 2378 } 2379 switch (orientation) { 2380 case SwingConstants.VERTICAL: 2381 case SwingConstants.HORIZONTAL: 2382 break; 2383 default: 2384 throw new IllegalArgumentException("orientation must be one of: VERTICAL, HORIZONTAL"); 2385 } 2386 } 2387 2388 2389 /** 2390 * Computes the size of viewport needed to display {@code visibleRowCount} 2391 * rows. The value returned by this method depends on the layout 2392 * orientation: 2393 * <p> 2394 * <b>{@code VERTICAL}:</b> 2395 * <br> 2396 * This is trivial if both {@code fixedCellWidth} and {@code fixedCellHeight} 2397 * have been set (either explicitly or by specifying a prototype cell value). 2398 * The width is simply the {@code fixedCellWidth} plus the list's horizontal 2399 * insets. The height is the {@code fixedCellHeight} multiplied by the 2400 * {@code visibleRowCount}, plus the list's vertical insets. 2401 * <p> 2402 * If either {@code fixedCellWidth} or {@code fixedCellHeight} haven't been 2403 * specified, heuristics are used. If the model is empty, the width is 2404 * the {@code fixedCellWidth}, if greater than {@code 0}, or a hard-coded 2405 * value of {@code 256}. The height is the {@code fixedCellHeight} multiplied 2406 * by {@code visibleRowCount}, if {@code fixedCellHeight} is greater than 2407 * {@code 0}, otherwise it is a hard-coded value of {@code 16} multiplied by 2408 * {@code visibleRowCount}. 2409 * <p> 2410 * If the model isn't empty, the width is the preferred size's width, 2411 * typically the width of the widest list element. The height is the 2412 * {@code fixedCellHeight} multiplied by the {@code visibleRowCount}, 2413 * plus the list's vertical insets. 2414 * <p> 2415 * <b>{@code VERTICAL_WRAP} or {@code HORIZONTAL_WRAP}:</b> 2416 * <br> 2417 * This method simply returns the value from {@code getPreferredSize}. 2418 * The list's {@code ListUI} is expected to override {@code getPreferredSize} 2419 * to return an appropriate value. 2420 * 2421 * @return a dimension containing the size of the viewport needed 2422 * to display {@code visibleRowCount} rows 2423 * @see #getPreferredScrollableViewportSize 2424 * @see #setPrototypeCellValue 2425 */ 2426 @BeanProperty(bound = false) 2427 public Dimension getPreferredScrollableViewportSize() 2428 { 2429 if (getLayoutOrientation() != VERTICAL) { 2430 return getPreferredSize(); 2431 } 2432 Insets insets = getInsets(); 2433 int dx = insets.left + insets.right; 2434 int dy = insets.top + insets.bottom; 2435 2436 int visibleRowCount = getVisibleRowCount(); 2437 int fixedCellWidth = getFixedCellWidth(); 2438 int fixedCellHeight = getFixedCellHeight(); 2439 2440 if ((fixedCellWidth > 0) && (fixedCellHeight > 0)) { 2441 int width = fixedCellWidth + dx; 2442 int height = (visibleRowCount * fixedCellHeight) + dy; 2443 return new Dimension(width, height); 2444 } 2445 else if (getModel().getSize() > 0) { 2446 int width = getPreferredSize().width; 2447 int height; 2448 Rectangle r = getCellBounds(0, 0); 2449 if (r != null) { 2450 height = (visibleRowCount * r.height) + dy; 2451 } 2452 else { 2453 // Will only happen if UI null, shouldn't matter what we return 2454 height = 1; 2455 } 2456 return new Dimension(width, height); 2457 } 2458 else { 2459 fixedCellWidth = (fixedCellWidth > 0) ? fixedCellWidth : 256; 2460 fixedCellHeight = (fixedCellHeight > 0) ? fixedCellHeight : 16; 2461 return new Dimension(fixedCellWidth, fixedCellHeight * visibleRowCount); 2462 } 2463 } 2464 2465 2466 /** 2467 * Returns the distance to scroll to expose the next or previous 2468 * row (for vertical scrolling) or column (for horizontal scrolling). 2469 * <p> 2470 * For horizontal scrolling, if the layout orientation is {@code VERTICAL}, 2471 * then the list's font size is returned (or {@code 1} if the font is 2472 * {@code null}). 2473 * 2474 * @param visibleRect the view area visible within the viewport 2475 * @param orientation {@code SwingConstants.HORIZONTAL} or 2476 * {@code SwingConstants.VERTICAL} 2477 * @param direction less or equal to zero to scroll up/back, 2478 * greater than zero for down/forward 2479 * @return the "unit" increment for scrolling in the specified direction; 2480 * always positive 2481 * @see #getScrollableBlockIncrement 2482 * @see Scrollable#getScrollableUnitIncrement 2483 * @throws IllegalArgumentException if {@code visibleRect} is {@code null}, or 2484 * {@code orientation} isn't one of {@code SwingConstants.VERTICAL} or 2485 * {@code SwingConstants.HORIZONTAL} 2486 */ 2487 public int getScrollableUnitIncrement(Rectangle visibleRect, int orientation, int direction) 2488 { 2489 checkScrollableParameters(visibleRect, orientation); 2490 2491 if (orientation == SwingConstants.VERTICAL) { 2492 int row = locationToIndex(visibleRect.getLocation()); 2493 2494 if (row == -1) { 2495 return 0; 2496 } 2497 else { 2498 /* Scroll Down */ 2499 if (direction > 0) { 2500 Rectangle r = getCellBounds(row, row); 2501 return (r == null) ? 0 : r.height - (visibleRect.y - r.y); 2502 } 2503 /* Scroll Up */ 2504 else { 2505 Rectangle r = getCellBounds(row, row); 2506 2507 /* The first row is completely visible and it's row 0. 2508 * We're done. 2509 */ 2510 if ((r.y == visibleRect.y) && (row == 0)) { 2511 return 0; 2512 } 2513 /* The first row is completely visible, return the 2514 * height of the previous row or 0 if the first row 2515 * is the top row of the list. 2516 */ 2517 else if (r.y == visibleRect.y) { 2518 Point loc = r.getLocation(); 2519 loc.y--; 2520 int prevIndex = locationToIndex(loc); 2521 Rectangle prevR = getCellBounds(prevIndex, prevIndex); 2522 2523 if (prevR == null || prevR.y >= r.y) { 2524 return 0; 2525 } 2526 return prevR.height; 2527 } 2528 /* The first row is partially visible, return the 2529 * height of hidden part. 2530 */ 2531 else { 2532 return visibleRect.y - r.y; 2533 } 2534 } 2535 } 2536 } else if (orientation == SwingConstants.HORIZONTAL && 2537 getLayoutOrientation() != JList.VERTICAL) { 2538 boolean leftToRight = getComponentOrientation().isLeftToRight(); 2539 int index; 2540 Point leadingPoint; 2541 2542 if (leftToRight) { 2543 leadingPoint = visibleRect.getLocation(); 2544 } 2545 else { 2546 leadingPoint = new Point(visibleRect.x + visibleRect.width -1, 2547 visibleRect.y); 2548 } 2549 index = locationToIndex(leadingPoint); 2550 2551 if (index != -1) { 2552 Rectangle cellBounds = getCellBounds(index, index); 2553 if (cellBounds != null && cellBounds.contains(leadingPoint)) { 2554 int leadingVisibleEdge; 2555 int leadingCellEdge; 2556 2557 if (leftToRight) { 2558 leadingVisibleEdge = visibleRect.x; 2559 leadingCellEdge = cellBounds.x; 2560 } 2561 else { 2562 leadingVisibleEdge = visibleRect.x + visibleRect.width; 2563 leadingCellEdge = cellBounds.x + cellBounds.width; 2564 } 2565 2566 if (leadingCellEdge != leadingVisibleEdge) { 2567 if (direction < 0) { 2568 // Show remainder of leading cell 2569 return Math.abs(leadingVisibleEdge - leadingCellEdge); 2570 2571 } 2572 else if (leftToRight) { 2573 // Hide rest of leading cell 2574 return leadingCellEdge + cellBounds.width - leadingVisibleEdge; 2575 } 2576 else { 2577 // Hide rest of leading cell 2578 return leadingVisibleEdge - cellBounds.x; 2579 } 2580 } 2581 // ASSUME: All cells are the same width 2582 return cellBounds.width; 2583 } 2584 } 2585 } 2586 Font f = getFont(); 2587 return (f != null) ? f.getSize() : 1; 2588 } 2589 2590 2591 /** 2592 * Returns the distance to scroll to expose the next or previous block. 2593 * <p> 2594 * For vertical scrolling, the following rules are used: 2595 * <ul> 2596 * <li>if scrolling down, returns the distance to scroll so that the last 2597 * visible element becomes the first completely visible element 2598 * <li>if scrolling up, returns the distance to scroll so that the first 2599 * visible element becomes the last completely visible element 2600 * <li>returns {@code visibleRect.height} if the list is empty 2601 * </ul> 2602 * <p> 2603 * For horizontal scrolling, when the layout orientation is either 2604 * {@code VERTICAL_WRAP} or {@code HORIZONTAL_WRAP}: 2605 * <ul> 2606 * <li>if scrolling right, returns the distance to scroll so that the 2607 * last visible element becomes 2608 * the first completely visible element 2609 * <li>if scrolling left, returns the distance to scroll so that the first 2610 * visible element becomes the last completely visible element 2611 * <li>returns {@code visibleRect.width} if the list is empty 2612 * </ul> 2613 * <p> 2614 * For horizontal scrolling and {@code VERTICAL} orientation, 2615 * returns {@code visibleRect.width}. 2616 * <p> 2617 * Note that the value of {@code visibleRect} must be the equal to 2618 * {@code this.getVisibleRect()}. 2619 * 2620 * @param visibleRect the view area visible within the viewport 2621 * @param orientation {@code SwingConstants.HORIZONTAL} or 2622 * {@code SwingConstants.VERTICAL} 2623 * @param direction less or equal to zero to scroll up/back, 2624 * greater than zero for down/forward 2625 * @return the "block" increment for scrolling in the specified direction; 2626 * always positive 2627 * @see #getScrollableUnitIncrement 2628 * @see Scrollable#getScrollableBlockIncrement 2629 * @throws IllegalArgumentException if {@code visibleRect} is {@code null}, or 2630 * {@code orientation} isn't one of {@code SwingConstants.VERTICAL} or 2631 * {@code SwingConstants.HORIZONTAL} 2632 */ 2633 public int getScrollableBlockIncrement(Rectangle visibleRect, int orientation, int direction) { 2634 checkScrollableParameters(visibleRect, orientation); 2635 if (orientation == SwingConstants.VERTICAL) { 2636 int inc = visibleRect.height; 2637 /* Scroll Down */ 2638 if (direction > 0) { 2639 // last cell is the lowest left cell 2640 int last = locationToIndex(new Point(visibleRect.x, visibleRect.y+visibleRect.height-1)); 2641 if (last != -1) { 2642 Rectangle lastRect = getCellBounds(last,last); 2643 if (lastRect != null) { 2644 inc = lastRect.y - visibleRect.y; 2645 if ( (inc == 0) && (last < getModel().getSize()-1) ) { 2646 inc = lastRect.height; 2647 } 2648 } 2649 } 2650 } 2651 /* Scroll Up */ 2652 else { 2653 int newFirst = locationToIndex(new Point(visibleRect.x, visibleRect.y-visibleRect.height)); 2654 int first = getFirstVisibleIndex(); 2655 if (newFirst != -1) { 2656 if (first == -1) { 2657 first = locationToIndex(visibleRect.getLocation()); 2658 } 2659 Rectangle newFirstRect = getCellBounds(newFirst,newFirst); 2660 Rectangle firstRect = getCellBounds(first,first); 2661 if ((newFirstRect != null) && (firstRect!=null)) { 2662 while ( (newFirstRect.y + visibleRect.height < 2663 firstRect.y + firstRect.height) && 2664 (newFirstRect.y < firstRect.y) ) { 2665 newFirst++; 2666 newFirstRect = getCellBounds(newFirst,newFirst); 2667 } 2668 inc = visibleRect.y - newFirstRect.y; 2669 if ( (inc <= 0) && (newFirstRect.y > 0)) { 2670 newFirst--; 2671 newFirstRect = getCellBounds(newFirst,newFirst); 2672 if (newFirstRect != null) { 2673 inc = visibleRect.y - newFirstRect.y; 2674 } 2675 } 2676 } 2677 } 2678 } 2679 return inc; 2680 } 2681 else if (orientation == SwingConstants.HORIZONTAL && 2682 getLayoutOrientation() != JList.VERTICAL) { 2683 boolean leftToRight = getComponentOrientation().isLeftToRight(); 2684 int inc = visibleRect.width; 2685 /* Scroll Right (in ltr mode) or Scroll Left (in rtl mode) */ 2686 if (direction > 0) { 2687 // position is upper right if ltr, or upper left otherwise 2688 int x = visibleRect.x + (leftToRight ? (visibleRect.width - 1) : 0); 2689 int last = locationToIndex(new Point(x, visibleRect.y)); 2690 2691 if (last != -1) { 2692 Rectangle lastRect = getCellBounds(last,last); 2693 if (lastRect != null) { 2694 if (leftToRight) { 2695 inc = lastRect.x - visibleRect.x; 2696 } else { 2697 inc = visibleRect.x + visibleRect.width 2698 - (lastRect.x + lastRect.width); 2699 } 2700 if (inc < 0) { 2701 inc += lastRect.width; 2702 } else if ( (inc == 0) && (last < getModel().getSize()-1) ) { 2703 inc = lastRect.width; 2704 } 2705 } 2706 } 2707 } 2708 /* Scroll Left (in ltr mode) or Scroll Right (in rtl mode) */ 2709 else { 2710 // position is upper left corner of the visibleRect shifted 2711 // left by the visibleRect.width if ltr, or upper right shifted 2712 // right by the visibleRect.width otherwise 2713 int x = visibleRect.x + (leftToRight 2714 ? -visibleRect.width 2715 : visibleRect.width - 1 + visibleRect.width); 2716 int first = locationToIndex(new Point(x, visibleRect.y)); 2717 2718 if (first != -1) { 2719 Rectangle firstRect = getCellBounds(first,first); 2720 if (firstRect != null) { 2721 // the right of the first cell 2722 int firstRight = firstRect.x + firstRect.width; 2723 2724 if (leftToRight) { 2725 if ((firstRect.x < visibleRect.x - visibleRect.width) 2726 && (firstRight < visibleRect.x)) { 2727 inc = visibleRect.x - firstRight; 2728 } else { 2729 inc = visibleRect.x - firstRect.x; 2730 } 2731 } else { 2732 int visibleRight = visibleRect.x + visibleRect.width; 2733 2734 if ((firstRight > visibleRight + visibleRect.width) 2735 && (firstRect.x > visibleRight)) { 2736 inc = firstRect.x - visibleRight; 2737 } else { 2738 inc = firstRight - visibleRight; 2739 } 2740 } 2741 } 2742 } 2743 } 2744 return inc; 2745 } 2746 return visibleRect.width; 2747 } 2748 2749 2750 /** 2751 * Returns {@code true} if this {@code JList} is displayed in a 2752 * {@code JViewport} and the viewport is wider than the list's 2753 * preferred width, or if the layout orientation is {@code HORIZONTAL_WRAP} 2754 * and {@code visibleRowCount <= 0}; otherwise returns {@code false}. 2755 * <p> 2756 * If {@code false}, then don't track the viewport's width. This allows 2757 * horizontal scrolling if the {@code JViewport} is itself embedded in a 2758 * {@code JScrollPane}. 2759 * 2760 * @return whether or not an enclosing viewport should force the list's 2761 * width to match its own 2762 * @see Scrollable#getScrollableTracksViewportWidth 2763 */ 2764 @BeanProperty(bound = false) 2765 public boolean getScrollableTracksViewportWidth() { 2766 if (getLayoutOrientation() == HORIZONTAL_WRAP && 2767 getVisibleRowCount() <= 0) { 2768 return true; 2769 } 2770 Container parent = SwingUtilities.getUnwrappedParent(this); 2771 if (parent instanceof JViewport) { 2772 return parent.getWidth() > getPreferredSize().width; 2773 } 2774 return false; 2775 } 2776 2777 /** 2778 * Returns {@code true} if this {@code JList} is displayed in a 2779 * {@code JViewport} and the viewport is taller than the list's 2780 * preferred height, or if the layout orientation is {@code VERTICAL_WRAP} 2781 * and {@code visibleRowCount <= 0}; otherwise returns {@code false}. 2782 * <p> 2783 * If {@code false}, then don't track the viewport's height. This allows 2784 * vertical scrolling if the {@code JViewport} is itself embedded in a 2785 * {@code JScrollPane}. 2786 * 2787 * @return whether or not an enclosing viewport should force the list's 2788 * height to match its own 2789 * @see Scrollable#getScrollableTracksViewportHeight 2790 */ 2791 @BeanProperty(bound = false) 2792 public boolean getScrollableTracksViewportHeight() { 2793 if (getLayoutOrientation() == VERTICAL_WRAP && 2794 getVisibleRowCount() <= 0) { 2795 return true; 2796 } 2797 Container parent = SwingUtilities.getUnwrappedParent(this); 2798 if (parent instanceof JViewport) { 2799 return parent.getHeight() > getPreferredSize().height; 2800 } 2801 return false; 2802 } 2803 2804 2805 /* 2806 * See {@code readObject} and {@code writeObject} in {@code JComponent} 2807 * for more information about serialization in Swing. 2808 */ 2809 private void writeObject(ObjectOutputStream s) throws IOException { 2810 s.defaultWriteObject(); 2811 if (getUIClassID().equals(uiClassID)) { 2812 byte count = JComponent.getWriteObjCounter(this); 2813 JComponent.setWriteObjCounter(this, --count); 2814 if (count == 0 && ui != null) { 2815 ui.installUI(this); 2816 } 2817 } 2818 } 2819 2820 2821 /** 2822 * Returns a {@code String} representation of this {@code JList}. 2823 * This method is intended to be used only for debugging purposes, 2824 * and the content and format of the returned {@code String} may vary 2825 * between implementations. The returned {@code String} may be empty, 2826 * but may not be {@code null}. 2827 * 2828 * @return a {@code String} representation of this {@code JList}. 2829 */ 2830 protected String paramString() { 2831 String selectionForegroundString = (selectionForeground != null ? 2832 selectionForeground.toString() : 2833 ""); 2834 String selectionBackgroundString = (selectionBackground != null ? 2835 selectionBackground.toString() : 2836 ""); 2837 2838 return super.paramString() + 2839 ",fixedCellHeight=" + fixedCellHeight + 2840 ",fixedCellWidth=" + fixedCellWidth + 2841 ",horizontalScrollIncrement=" + horizontalScrollIncrement + 2842 ",selectionBackground=" + selectionBackgroundString + 2843 ",selectionForeground=" + selectionForegroundString + 2844 ",visibleRowCount=" + visibleRowCount + 2845 ",layoutOrientation=" + layoutOrientation; 2846 } 2847 2848 2849 /** 2850 * --- Accessibility Support --- 2851 */ 2852 2853 /** 2854 * Gets the {@code AccessibleContext} associated with this {@code JList}. 2855 * For {@code JList}, the {@code AccessibleContext} takes the form of an 2856 * {@code AccessibleJList}. 2857 * <p> 2858 * A new {@code AccessibleJList} instance is created if necessary. 2859 * 2860 * @return an {@code AccessibleJList} that serves as the 2861 * {@code AccessibleContext} of this {@code JList} 2862 */ 2863 @BeanProperty(bound = false) 2864 public AccessibleContext getAccessibleContext() { 2865 if (accessibleContext == null) { 2866 accessibleContext = new AccessibleJList(); 2867 } 2868 return accessibleContext; 2869 } 2870 2871 /** 2872 * This class implements accessibility support for the 2873 * {@code JList} class. It provides an implementation of the 2874 * Java Accessibility API appropriate to list user-interface 2875 * elements. 2876 * <p> 2877 * <strong>Warning:</strong> 2878 * Serialized objects of this class will not be compatible with 2879 * future Swing releases. The current serialization support is 2880 * appropriate for short term storage or RMI between applications running 2881 * the same version of Swing. As of 1.4, support for long term storage 2882 * of all JavaBeans™ 2883 * has been added to the <code>java.beans</code> package. 2884 * Please see {@link java.beans.XMLEncoder}. 2885 */ 2886 @SuppressWarnings("serial") // Same-version serialization only 2887 protected class AccessibleJList extends AccessibleJComponent 2888 implements AccessibleSelection, PropertyChangeListener, 2889 ListSelectionListener, ListDataListener { 2890 2891 int leadSelectionIndex; 2892 2893 /** 2894 * Constructs an {@code AccessibleJList}. 2895 */ 2896 public AccessibleJList() { 2897 super(); 2898 JList.this.addPropertyChangeListener(this); 2899 JList.this.getSelectionModel().addListSelectionListener(this); 2900 JList.this.getModel().addListDataListener(this); 2901 leadSelectionIndex = JList.this.getLeadSelectionIndex(); 2902 } 2903 2904 /** 2905 * Property Change Listener change method. Used to track changes 2906 * to the DataModel and ListSelectionModel, in order to re-set 2907 * listeners to those for reporting changes there via the Accessibility 2908 * PropertyChange mechanism. 2909 * 2910 * @param e PropertyChangeEvent 2911 */ 2912 public void propertyChange(PropertyChangeEvent e) { 2913 String name = e.getPropertyName(); 2914 Object oldValue = e.getOldValue(); 2915 Object newValue = e.getNewValue(); 2916 2917 // re-set listData listeners 2918 if (name.compareTo("model") == 0) { 2919 2920 if (oldValue != null && oldValue instanceof ListModel) { 2921 ((ListModel) oldValue).removeListDataListener(this); 2922 } 2923 if (newValue != null && newValue instanceof ListModel) { 2924 ((ListModel) newValue).addListDataListener(this); 2925 } 2926 2927 // re-set listSelectionModel listeners 2928 } else if (name.compareTo("selectionModel") == 0) { 2929 2930 if (oldValue != null && oldValue instanceof ListSelectionModel) { 2931 ((ListSelectionModel) oldValue).removeListSelectionListener(this); 2932 } 2933 if (newValue != null && newValue instanceof ListSelectionModel) { 2934 ((ListSelectionModel) newValue).addListSelectionListener(this); 2935 } 2936 2937 firePropertyChange( 2938 AccessibleContext.ACCESSIBLE_SELECTION_PROPERTY, 2939 Boolean.valueOf(false), Boolean.valueOf(true)); 2940 } 2941 } 2942 2943 /** 2944 * List Selection Listener value change method. Used to fire 2945 * the property change 2946 * 2947 * @param e ListSelectionEvent 2948 * 2949 */ 2950 public void valueChanged(ListSelectionEvent e) { 2951 int oldLeadSelectionIndex = leadSelectionIndex; 2952 leadSelectionIndex = JList.this.getLeadSelectionIndex(); 2953 if (oldLeadSelectionIndex != leadSelectionIndex) { 2954 Accessible oldLS, newLS; 2955 oldLS = (oldLeadSelectionIndex >= 0) 2956 ? getAccessibleChild(oldLeadSelectionIndex) 2957 : null; 2958 newLS = (leadSelectionIndex >= 0) 2959 ? getAccessibleChild(leadSelectionIndex) 2960 : null; 2961 firePropertyChange(AccessibleContext.ACCESSIBLE_ACTIVE_DESCENDANT_PROPERTY, 2962 oldLS, newLS); 2963 } 2964 2965 firePropertyChange(AccessibleContext.ACCESSIBLE_VISIBLE_DATA_PROPERTY, 2966 Boolean.valueOf(false), Boolean.valueOf(true)); 2967 firePropertyChange(AccessibleContext.ACCESSIBLE_SELECTION_PROPERTY, 2968 Boolean.valueOf(false), Boolean.valueOf(true)); 2969 2970 // Process the State changes for Multiselectable 2971 AccessibleStateSet s = getAccessibleStateSet(); 2972 ListSelectionModel lsm = JList.this.getSelectionModel(); 2973 if (lsm.getSelectionMode() != ListSelectionModel.SINGLE_SELECTION) { 2974 if (!s.contains(AccessibleState.MULTISELECTABLE)) { 2975 s.add(AccessibleState.MULTISELECTABLE); 2976 firePropertyChange(AccessibleContext.ACCESSIBLE_STATE_PROPERTY, 2977 null, AccessibleState.MULTISELECTABLE); 2978 } 2979 } else { 2980 if (s.contains(AccessibleState.MULTISELECTABLE)) { 2981 s.remove(AccessibleState.MULTISELECTABLE); 2982 firePropertyChange(AccessibleContext.ACCESSIBLE_STATE_PROPERTY, 2983 AccessibleState.MULTISELECTABLE, null); 2984 } 2985 } 2986 } 2987 2988 /** 2989 * List Data Listener interval added method. Used to fire the visible data property change 2990 * 2991 * @param e ListDataEvent 2992 * 2993 */ 2994 public void intervalAdded(ListDataEvent e) { 2995 firePropertyChange(AccessibleContext.ACCESSIBLE_VISIBLE_DATA_PROPERTY, 2996 Boolean.valueOf(false), Boolean.valueOf(true)); 2997 } 2998 2999 /** 3000 * List Data Listener interval removed method. Used to fire the visible data property change 3001 * 3002 * @param e ListDataEvent 3003 * 3004 */ 3005 public void intervalRemoved(ListDataEvent e) { 3006 firePropertyChange(AccessibleContext.ACCESSIBLE_VISIBLE_DATA_PROPERTY, 3007 Boolean.valueOf(false), Boolean.valueOf(true)); 3008 } 3009 3010 /** 3011 * List Data Listener contents changed method. Used to fire the visible data property change 3012 * 3013 * @param e ListDataEvent 3014 * 3015 */ 3016 public void contentsChanged(ListDataEvent e) { 3017 firePropertyChange(AccessibleContext.ACCESSIBLE_VISIBLE_DATA_PROPERTY, 3018 Boolean.valueOf(false), Boolean.valueOf(true)); 3019 } 3020 3021 // AccessibleContext methods 3022 3023 /** 3024 * Get the state set of this object. 3025 * 3026 * @return an instance of AccessibleState containing the current state 3027 * of the object 3028 * @see AccessibleState 3029 */ 3030 public AccessibleStateSet getAccessibleStateSet() { 3031 AccessibleStateSet states = super.getAccessibleStateSet(); 3032 if (selectionModel.getSelectionMode() != 3033 ListSelectionModel.SINGLE_SELECTION) { 3034 states.add(AccessibleState.MULTISELECTABLE); 3035 } 3036 return states; 3037 } 3038 3039 /** 3040 * Get the role of this object. 3041 * 3042 * @return an instance of AccessibleRole describing the role of the 3043 * object 3044 * @see AccessibleRole 3045 */ 3046 public AccessibleRole getAccessibleRole() { 3047 return AccessibleRole.LIST; 3048 } 3049 3050 /** 3051 * Returns the <code>Accessible</code> child contained at 3052 * the local coordinate <code>Point</code>, if one exists. 3053 * Otherwise returns <code>null</code>. 3054 * 3055 * @return the <code>Accessible</code> at the specified 3056 * location, if it exists 3057 */ 3058 public Accessible getAccessibleAt(Point p) { 3059 int i = locationToIndex(p); 3060 if (i >= 0) { 3061 return new AccessibleJListChild(JList.this, i); 3062 } else { 3063 return null; 3064 } 3065 } 3066 3067 /** 3068 * Returns the number of accessible children in the object. If all 3069 * of the children of this object implement Accessible, than this 3070 * method should return the number of children of this object. 3071 * 3072 * @return the number of accessible children in the object. 3073 */ 3074 public int getAccessibleChildrenCount() { 3075 return getModel().getSize(); 3076 } 3077 3078 /** 3079 * Return the nth Accessible child of the object. 3080 * 3081 * @param i zero-based index of child 3082 * @return the nth Accessible child of the object 3083 */ 3084 public Accessible getAccessibleChild(int i) { 3085 if (i >= getModel().getSize()) { 3086 return null; 3087 } else { 3088 return new AccessibleJListChild(JList.this, i); 3089 } 3090 } 3091 3092 /** 3093 * Get the AccessibleSelection associated with this object. In the 3094 * implementation of the Java Accessibility API for this class, 3095 * return this object, which is responsible for implementing the 3096 * AccessibleSelection interface on behalf of itself. 3097 * 3098 * @return this object 3099 */ 3100 public AccessibleSelection getAccessibleSelection() { 3101 return this; 3102 } 3103 3104 3105 // AccessibleSelection methods 3106 3107 /** 3108 * Returns the number of items currently selected. 3109 * If no items are selected, the return value will be 0. 3110 * 3111 * @return the number of items currently selected. 3112 */ 3113 public int getAccessibleSelectionCount() { 3114 return JList.this.getSelectedIndices().length; 3115 } 3116 3117 /** 3118 * Returns an Accessible representing the specified selected item 3119 * in the object. If there isn't a selection, or there are 3120 * fewer items selected than the integer passed in, the return 3121 * value will be <code>null</code>. 3122 * 3123 * @param i the zero-based index of selected items 3124 * @return an Accessible containing the selected item 3125 */ 3126 public Accessible getAccessibleSelection(int i) { 3127 int len = getAccessibleSelectionCount(); 3128 if (i < 0 || i >= len) { 3129 return null; 3130 } else { 3131 return getAccessibleChild(JList.this.getSelectedIndices()[i]); 3132 } 3133 } 3134 3135 /** 3136 * Returns true if the current child of this object is selected. 3137 * 3138 * @param i the zero-based index of the child in this Accessible 3139 * object. 3140 * @see AccessibleContext#getAccessibleChild 3141 */ 3142 public boolean isAccessibleChildSelected(int i) { 3143 return isSelectedIndex(i); 3144 } 3145 3146 /** 3147 * Adds the specified selected item in the object to the object's 3148 * selection. If the object supports multiple selections, 3149 * the specified item is added to any existing selection, otherwise 3150 * it replaces any existing selection in the object. If the 3151 * specified item is already selected, this method has no effect. 3152 * 3153 * @param i the zero-based index of selectable items 3154 */ 3155 public void addAccessibleSelection(int i) { 3156 JList.this.addSelectionInterval(i, i); 3157 } 3158 3159 /** 3160 * Removes the specified selected item in the object from the object's 3161 * selection. If the specified item isn't currently selected, this 3162 * method has no effect. 3163 * 3164 * @param i the zero-based index of selectable items 3165 */ 3166 public void removeAccessibleSelection(int i) { 3167 JList.this.removeSelectionInterval(i, i); 3168 } 3169 3170 /** 3171 * Clears the selection in the object, so that nothing in the 3172 * object is selected. 3173 */ 3174 public void clearAccessibleSelection() { 3175 JList.this.clearSelection(); 3176 } 3177 3178 /** 3179 * Causes every selected item in the object to be selected 3180 * if the object supports multiple selections. 3181 */ 3182 public void selectAllAccessibleSelection() { 3183 JList.this.addSelectionInterval(0, getAccessibleChildrenCount() -1); 3184 } 3185 3186 /** 3187 * This class implements accessibility support appropriate 3188 * for list children. 3189 */ 3190 protected class AccessibleJListChild extends AccessibleContext 3191 implements Accessible, AccessibleComponent, AccessibleAction { 3192 private JList<E> parent = null; 3193 int indexInParent; 3194 private Component component = null; 3195 private AccessibleContext accessibleContext = null; 3196 private ListModel<E> listModel; 3197 private ListCellRenderer<? super E> cellRenderer = null; 3198 3199 /** 3200 * Constructs an {@code AccessibleJListChild}. 3201 * @param parent the parent 3202 * @param indexInParent the index in the parent 3203 */ 3204 public AccessibleJListChild(JList<E> parent, int indexInParent) { 3205 this.parent = parent; 3206 this.setAccessibleParent(parent); 3207 this.indexInParent = indexInParent; 3208 if (parent != null) { 3209 listModel = parent.getModel(); 3210 cellRenderer = parent.getCellRenderer(); 3211 } 3212 } 3213 3214 private Component getCurrentComponent() { 3215 return getComponentAtIndex(indexInParent); 3216 } 3217 3218 AccessibleContext getCurrentAccessibleContext() { 3219 Component c = getComponentAtIndex(indexInParent); 3220 if (c instanceof Accessible) { 3221 return c.getAccessibleContext(); 3222 } else { 3223 return null; 3224 } 3225 } 3226 3227 private Component getComponentAtIndex(int index) { 3228 if (index < 0 || index >= listModel.getSize()) { 3229 return null; 3230 } 3231 if ((parent != null) 3232 && (listModel != null) 3233 && cellRenderer != null) { 3234 E value = listModel.getElementAt(index); 3235 boolean isSelected = parent.isSelectedIndex(index); 3236 boolean isFocussed = parent.isFocusOwner() 3237 && (index == parent.getLeadSelectionIndex()); 3238 return cellRenderer.getListCellRendererComponent( 3239 parent, 3240 value, 3241 index, 3242 isSelected, 3243 isFocussed); 3244 } else { 3245 return null; 3246 } 3247 } 3248 3249 3250 // Accessible Methods 3251 /** 3252 * Get the AccessibleContext for this object. In the 3253 * implementation of the Java Accessibility API for this class, 3254 * returns this object, which is its own AccessibleContext. 3255 * 3256 * @return this object 3257 */ 3258 public AccessibleContext getAccessibleContext() { 3259 return this; 3260 } 3261 3262 3263 // AccessibleContext methods 3264 3265 public String getAccessibleName() { 3266 AccessibleContext ac = getCurrentAccessibleContext(); 3267 if (ac != null) { 3268 return ac.getAccessibleName(); 3269 } else { 3270 return null; 3271 } 3272 } 3273 3274 public void setAccessibleName(String s) { 3275 AccessibleContext ac = getCurrentAccessibleContext(); 3276 if (ac != null) { 3277 ac.setAccessibleName(s); 3278 } 3279 } 3280 3281 public String getAccessibleDescription() { 3282 AccessibleContext ac = getCurrentAccessibleContext(); 3283 if (ac != null) { 3284 return ac.getAccessibleDescription(); 3285 } else { 3286 return null; 3287 } 3288 } 3289 3290 public void setAccessibleDescription(String s) { 3291 AccessibleContext ac = getCurrentAccessibleContext(); 3292 if (ac != null) { 3293 ac.setAccessibleDescription(s); 3294 } 3295 } 3296 3297 public AccessibleRole getAccessibleRole() { 3298 AccessibleContext ac = getCurrentAccessibleContext(); 3299 if (ac != null) { 3300 return ac.getAccessibleRole(); 3301 } else { 3302 return null; 3303 } 3304 } 3305 3306 public AccessibleStateSet getAccessibleStateSet() { 3307 AccessibleContext ac = getCurrentAccessibleContext(); 3308 AccessibleStateSet s; 3309 if (ac != null) { 3310 s = ac.getAccessibleStateSet(); 3311 } else { 3312 s = new AccessibleStateSet(); 3313 } 3314 3315 s.add(AccessibleState.SELECTABLE); 3316 if (parent.isFocusOwner() 3317 && (indexInParent == parent.getLeadSelectionIndex())) { 3318 s.add(AccessibleState.ACTIVE); 3319 } 3320 if (parent.isSelectedIndex(indexInParent)) { 3321 s.add(AccessibleState.SELECTED); 3322 } 3323 if (this.isShowing()) { 3324 s.add(AccessibleState.SHOWING); 3325 } else if (s.contains(AccessibleState.SHOWING)) { 3326 s.remove(AccessibleState.SHOWING); 3327 } 3328 if (this.isVisible()) { 3329 s.add(AccessibleState.VISIBLE); 3330 } else if (s.contains(AccessibleState.VISIBLE)) { 3331 s.remove(AccessibleState.VISIBLE); 3332 } 3333 s.add(AccessibleState.TRANSIENT); // cell-rendered 3334 return s; 3335 } 3336 3337 public int getAccessibleIndexInParent() { 3338 return indexInParent; 3339 } 3340 3341 public int getAccessibleChildrenCount() { 3342 AccessibleContext ac = getCurrentAccessibleContext(); 3343 if (ac != null) { 3344 return ac.getAccessibleChildrenCount(); 3345 } else { 3346 return 0; 3347 } 3348 } 3349 3350 public Accessible getAccessibleChild(int i) { 3351 AccessibleContext ac = getCurrentAccessibleContext(); 3352 if (ac != null) { 3353 Accessible accessibleChild = ac.getAccessibleChild(i); 3354 ac.setAccessibleParent(this); 3355 return accessibleChild; 3356 } else { 3357 return null; 3358 } 3359 } 3360 3361 public Locale getLocale() { 3362 AccessibleContext ac = getCurrentAccessibleContext(); 3363 if (ac != null) { 3364 return ac.getLocale(); 3365 } else { 3366 return null; 3367 } 3368 } 3369 3370 public void addPropertyChangeListener(PropertyChangeListener l) { 3371 AccessibleContext ac = getCurrentAccessibleContext(); 3372 if (ac != null) { 3373 ac.addPropertyChangeListener(l); 3374 } 3375 } 3376 3377 public void removePropertyChangeListener(PropertyChangeListener l) { 3378 AccessibleContext ac = getCurrentAccessibleContext(); 3379 if (ac != null) { 3380 ac.removePropertyChangeListener(l); 3381 } 3382 } 3383 3384 /** 3385 * Get the AccessibleComponent associated with this object. In the 3386 * implementation of the Java Accessibility API for this class, 3387 * return this object, which is responsible for implementing the 3388 * AccessibleComponent interface on behalf of itself. 3389 * 3390 * @return this object 3391 */ 3392 public AccessibleComponent getAccessibleComponent() { 3393 return this; // to override getBounds() 3394 } 3395 3396 public AccessibleSelection getAccessibleSelection() { 3397 return getCurrentAccessibleContext().getAccessibleSelection(); 3398 } 3399 3400 public AccessibleText getAccessibleText() { 3401 return getCurrentAccessibleContext().getAccessibleText(); 3402 } 3403 3404 public AccessibleValue getAccessibleValue() { 3405 return getCurrentAccessibleContext().getAccessibleValue(); 3406 } 3407 3408 3409 // AccessibleComponent methods 3410 3411 public Color getBackground() { 3412 AccessibleContext ac = getCurrentAccessibleContext(); 3413 if (ac instanceof AccessibleComponent) { 3414 return ((AccessibleComponent) ac).getBackground(); 3415 } else { 3416 Component c = getCurrentComponent(); 3417 if (c != null) { 3418 return c.getBackground(); 3419 } else { 3420 return null; 3421 } 3422 } 3423 } 3424 3425 public void setBackground(Color c) { 3426 AccessibleContext ac = getCurrentAccessibleContext(); 3427 if (ac instanceof AccessibleComponent) { 3428 ((AccessibleComponent) ac).setBackground(c); 3429 } else { 3430 Component cp = getCurrentComponent(); 3431 if (cp != null) { 3432 cp.setBackground(c); 3433 } 3434 } 3435 } 3436 3437 public Color getForeground() { 3438 AccessibleContext ac = getCurrentAccessibleContext(); 3439 if (ac instanceof AccessibleComponent) { 3440 return ((AccessibleComponent) ac).getForeground(); 3441 } else { 3442 Component c = getCurrentComponent(); 3443 if (c != null) { 3444 return c.getForeground(); 3445 } else { 3446 return null; 3447 } 3448 } 3449 } 3450 3451 public void setForeground(Color c) { 3452 AccessibleContext ac = getCurrentAccessibleContext(); 3453 if (ac instanceof AccessibleComponent) { 3454 ((AccessibleComponent) ac).setForeground(c); 3455 } else { 3456 Component cp = getCurrentComponent(); 3457 if (cp != null) { 3458 cp.setForeground(c); 3459 } 3460 } 3461 } 3462 3463 public Cursor getCursor() { 3464 AccessibleContext ac = getCurrentAccessibleContext(); 3465 if (ac instanceof AccessibleComponent) { 3466 return ((AccessibleComponent) ac).getCursor(); 3467 } else { 3468 Component c = getCurrentComponent(); 3469 if (c != null) { 3470 return c.getCursor(); 3471 } else { 3472 Accessible ap = getAccessibleParent(); 3473 if (ap instanceof AccessibleComponent) { 3474 return ((AccessibleComponent) ap).getCursor(); 3475 } else { 3476 return null; 3477 } 3478 } 3479 } 3480 } 3481 3482 public void setCursor(Cursor c) { 3483 AccessibleContext ac = getCurrentAccessibleContext(); 3484 if (ac instanceof AccessibleComponent) { 3485 ((AccessibleComponent) ac).setCursor(c); 3486 } else { 3487 Component cp = getCurrentComponent(); 3488 if (cp != null) { 3489 cp.setCursor(c); 3490 } 3491 } 3492 } 3493 3494 public Font getFont() { 3495 AccessibleContext ac = getCurrentAccessibleContext(); 3496 if (ac instanceof AccessibleComponent) { 3497 return ((AccessibleComponent) ac).getFont(); 3498 } else { 3499 Component c = getCurrentComponent(); 3500 if (c != null) { 3501 return c.getFont(); 3502 } else { 3503 return null; 3504 } 3505 } 3506 } 3507 3508 public void setFont(Font f) { 3509 AccessibleContext ac = getCurrentAccessibleContext(); 3510 if (ac instanceof AccessibleComponent) { 3511 ((AccessibleComponent) ac).setFont(f); 3512 } else { 3513 Component c = getCurrentComponent(); 3514 if (c != null) { 3515 c.setFont(f); 3516 } 3517 } 3518 } 3519 3520 public FontMetrics getFontMetrics(Font f) { 3521 AccessibleContext ac = getCurrentAccessibleContext(); 3522 if (ac instanceof AccessibleComponent) { 3523 return ((AccessibleComponent) ac).getFontMetrics(f); 3524 } else { 3525 Component c = getCurrentComponent(); 3526 if (c != null) { 3527 return c.getFontMetrics(f); 3528 } else { 3529 return null; 3530 } 3531 } 3532 } 3533 3534 public boolean isEnabled() { 3535 AccessibleContext ac = getCurrentAccessibleContext(); 3536 if (ac instanceof AccessibleComponent) { 3537 return ((AccessibleComponent) ac).isEnabled(); 3538 } else { 3539 Component c = getCurrentComponent(); 3540 if (c != null) { 3541 return c.isEnabled(); 3542 } else { 3543 return false; 3544 } 3545 } 3546 } 3547 3548 public void setEnabled(boolean b) { 3549 AccessibleContext ac = getCurrentAccessibleContext(); 3550 if (ac instanceof AccessibleComponent) { 3551 ((AccessibleComponent) ac).setEnabled(b); 3552 } else { 3553 Component c = getCurrentComponent(); 3554 if (c != null) { 3555 c.setEnabled(b); 3556 } 3557 } 3558 } 3559 3560 public boolean isVisible() { 3561 int fi = parent.getFirstVisibleIndex(); 3562 int li = parent.getLastVisibleIndex(); 3563 // The UI incorrectly returns a -1 for the last 3564 // visible index if the list is smaller than the 3565 // viewport size. 3566 if (li == -1) { 3567 li = parent.getModel().getSize() - 1; 3568 } 3569 return ((indexInParent >= fi) 3570 && (indexInParent <= li)); 3571 } 3572 3573 public void setVisible(boolean b) { 3574 } 3575 3576 public boolean isShowing() { 3577 return (parent.isShowing() && isVisible()); 3578 } 3579 3580 public boolean contains(Point p) { 3581 AccessibleContext ac = getCurrentAccessibleContext(); 3582 if (ac instanceof AccessibleComponent) { 3583 Rectangle r = ((AccessibleComponent) ac).getBounds(); 3584 return r.contains(p); 3585 } else { 3586 Component c = getCurrentComponent(); 3587 if (c != null) { 3588 Rectangle r = c.getBounds(); 3589 return r.contains(p); 3590 } else { 3591 return getBounds().contains(p); 3592 } 3593 } 3594 } 3595 3596 public Point getLocationOnScreen() { 3597 if (parent != null) { 3598 Point listLocation; 3599 try { 3600 listLocation = parent.getLocationOnScreen(); 3601 } catch (IllegalComponentStateException e) { 3602 // This can happen if the component isn't visisble 3603 return null; 3604 } 3605 Point componentLocation = parent.indexToLocation(indexInParent); 3606 if (componentLocation != null) { 3607 componentLocation.translate(listLocation.x, listLocation.y); 3608 return componentLocation; 3609 } else { 3610 return null; 3611 } 3612 } else { 3613 return null; 3614 } 3615 } 3616 3617 public Point getLocation() { 3618 if (parent != null) { 3619 return parent.indexToLocation(indexInParent); 3620 } else { 3621 return null; 3622 } 3623 } 3624 3625 public void setLocation(Point p) { 3626 if ((parent != null) && (parent.contains(p))) { 3627 ensureIndexIsVisible(indexInParent); 3628 } 3629 } 3630 3631 public Rectangle getBounds() { 3632 if (parent != null) { 3633 return parent.getCellBounds(indexInParent,indexInParent); 3634 } else { 3635 return null; 3636 } 3637 } 3638 3639 public void setBounds(Rectangle r) { 3640 AccessibleContext ac = getCurrentAccessibleContext(); 3641 if (ac instanceof AccessibleComponent) { 3642 ((AccessibleComponent) ac).setBounds(r); 3643 } 3644 } 3645 3646 public Dimension getSize() { 3647 Rectangle cellBounds = this.getBounds(); 3648 if (cellBounds != null) { 3649 return cellBounds.getSize(); 3650 } else { 3651 return null; 3652 } 3653 } 3654 3655 public void setSize (Dimension d) { 3656 AccessibleContext ac = getCurrentAccessibleContext(); 3657 if (ac instanceof AccessibleComponent) { 3658 ((AccessibleComponent) ac).setSize(d); 3659 } else { 3660 Component c = getCurrentComponent(); 3661 if (c != null) { 3662 c.setSize(d); 3663 } 3664 } 3665 } 3666 3667 public Accessible getAccessibleAt(Point p) { 3668 AccessibleContext ac = getCurrentAccessibleContext(); 3669 if (ac instanceof AccessibleComponent) { 3670 return ((AccessibleComponent) ac).getAccessibleAt(p); 3671 } else { 3672 return null; 3673 } 3674 } 3675 3676 @SuppressWarnings("deprecation") 3677 public boolean isFocusTraversable() { 3678 AccessibleContext ac = getCurrentAccessibleContext(); 3679 if (ac instanceof AccessibleComponent) { 3680 return ((AccessibleComponent) ac).isFocusTraversable(); 3681 } else { 3682 Component c = getCurrentComponent(); 3683 if (c != null) { 3684 return c.isFocusTraversable(); 3685 } else { 3686 return false; 3687 } 3688 } 3689 } 3690 3691 public void requestFocus() { 3692 AccessibleContext ac = getCurrentAccessibleContext(); 3693 if (ac instanceof AccessibleComponent) { 3694 ((AccessibleComponent) ac).requestFocus(); 3695 } else { 3696 Component c = getCurrentComponent(); 3697 if (c != null) { 3698 c.requestFocus(); 3699 } 3700 } 3701 } 3702 3703 public void addFocusListener(FocusListener l) { 3704 AccessibleContext ac = getCurrentAccessibleContext(); 3705 if (ac instanceof AccessibleComponent) { 3706 ((AccessibleComponent) ac).addFocusListener(l); 3707 } else { 3708 Component c = getCurrentComponent(); 3709 if (c != null) { 3710 c.addFocusListener(l); 3711 } 3712 } 3713 } 3714 3715 public void removeFocusListener(FocusListener l) { 3716 AccessibleContext ac = getCurrentAccessibleContext(); 3717 if (ac instanceof AccessibleComponent) { 3718 ((AccessibleComponent) ac).removeFocusListener(l); 3719 } else { 3720 Component c = getCurrentComponent(); 3721 if (c != null) { 3722 c.removeFocusListener(l); 3723 } 3724 } 3725 } 3726 3727 // TIGER - 4733624 3728 /** 3729 * Returns the icon for the element renderer, as the only item 3730 * of an array of <code>AccessibleIcon</code>s or a <code>null</code> array 3731 * if the renderer component contains no icons. 3732 * 3733 * @return an array containing the accessible icon 3734 * or a <code>null</code> array if none 3735 * @since 1.3 3736 */ 3737 public AccessibleIcon [] getAccessibleIcon() { 3738 AccessibleContext ac = getCurrentAccessibleContext(); 3739 if (ac != null) { 3740 return ac.getAccessibleIcon(); 3741 } else { 3742 return null; 3743 } 3744 } 3745 3746 /** 3747 * {@inheritDoc} 3748 * @implSpec Returns the AccessibleAction for this AccessibleJListChild 3749 * as follows: First getListCellRendererComponent of the ListCellRenderer 3750 * for the component at the "index in parent" of this child is called. 3751 * Then its AccessibleContext is fetched and that AccessibleContext's 3752 * AccessibleAction is returned. Note that if an AccessibleAction 3753 * is not found using this process then this object with its implementation 3754 * of the AccessibleAction interface is returned. 3755 * @since 9 3756 */ 3757 @Override 3758 public AccessibleAction getAccessibleAction() { 3759 AccessibleContext ac = getCurrentAccessibleContext(); 3760 if (ac == null) { 3761 return null; 3762 } else { 3763 AccessibleAction aa = ac.getAccessibleAction(); 3764 if (aa != null) { 3765 return aa; 3766 } else { 3767 return this; 3768 } 3769 } 3770 } 3771 3772 /** 3773 * {@inheritDoc} 3774 * @implSpec If i == 0 selects this AccessibleJListChild by calling 3775 * JList.this.setSelectedIndex(indexInParent) and then returns true; 3776 * otherwise returns false. 3777 * @since 9 3778 */ 3779 @Override 3780 public boolean doAccessibleAction(int i) { 3781 if (i == 0) { 3782 JList.this.setSelectedIndex(indexInParent); 3783 return true; 3784 } else { 3785 return false; 3786 } 3787 } 3788 3789 /** 3790 * {@inheritDoc} 3791 * @implSpec If i == 0 returns the action description fetched from 3792 * UIManager.getString("AbstractButton.clickText"); 3793 * otherwise returns null. 3794 * @since 9 3795 */ 3796 @Override 3797 public String getAccessibleActionDescription(int i) { 3798 if (i == 0) { 3799 return UIManager.getString("AbstractButton.clickText"); 3800 } else { 3801 return null; 3802 } 3803 } 3804 3805 /** 3806 * {@inheritDoc} 3807 * @implSpec Returns 1, i.e. there is only one action. 3808 * @since 9 3809 */ 3810 @Override 3811 public int getAccessibleActionCount() { 3812 return 1; 3813 } 3814 3815 } // inner class AccessibleJListChild 3816 3817 } // inner class AccessibleJList 3818 }