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