1 /* 2 * Copyright (c) 1995, 2014, Oracle and/or its affiliates. All rights reserved. 3 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. 4 * 5 * This code is free software; you can redistribute it and/or modify it 6 * under the terms of the GNU General Public License version 2 only, as 7 * published by the Free Software Foundation. Oracle designates this 8 * particular file as subject to the "Classpath" exception as provided 9 * by Oracle in the LICENSE file that accompanied this code. 10 * 11 * This code is distributed in the hope that it will be useful, but WITHOUT 12 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or 13 * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License 14 * version 2 for more details (a copy is included in the LICENSE file that 15 * accompanied this code). 16 * 17 * You should have received a copy of the GNU General Public License version 18 * 2 along with this work; if not, write to the Free Software Foundation, 19 * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. 20 * 21 * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA 22 * or visit www.oracle.com if you need additional information or have any 23 * questions. 24 */ 25 package java.awt; 26 27 import java.awt.peer.TextComponentPeer; 28 import java.awt.event.*; 29 import java.util.EventListener; 30 import java.io.ObjectOutputStream; 31 import java.io.ObjectInputStream; 32 import java.io.IOException; 33 import java.text.BreakIterator; 34 import javax.swing.text.AttributeSet; 35 import javax.accessibility.*; 36 import java.awt.im.InputMethodRequests; 37 import sun.awt.AWTPermissions; 38 import sun.awt.InputMethodSupport; 39 40 /** 41 * The <code>TextComponent</code> class is the superclass of 42 * any component that allows the editing of some text. 43 * <p> 44 * A text component embodies a string of text. The 45 * <code>TextComponent</code> class defines a set of methods 46 * that determine whether or not this text is editable. If the 47 * component is editable, it defines another set of methods 48 * that supports a text insertion caret. 49 * <p> 50 * In addition, the class defines methods that are used 51 * to maintain a current <em>selection</em> from the text. 52 * The text selection, a substring of the component's text, 53 * is the target of editing operations. It is also referred 54 * to as the <em>selected text</em>. 55 * 56 * @author Sami Shaio 57 * @author Arthur van Hoff 58 * @since 1.0 59 */ 60 public class TextComponent extends Component implements Accessible { 61 62 /** 63 * The value of the text. 64 * A <code>null</code> value is the same as "". 65 * 66 * @serial 67 * @see #setText(String) 68 * @see #getText() 69 */ 70 String text; 71 72 /** 73 * A boolean indicating whether or not this 74 * <code>TextComponent</code> is editable. 75 * It will be <code>true</code> if the text component 76 * is editable and <code>false</code> if not. 77 * 78 * @serial 79 * @see #isEditable() 80 */ 81 boolean editable = true; 82 83 /** 84 * The selection refers to the selected text, and the 85 * <code>selectionStart</code> is the start position 86 * of the selected text. 87 * 88 * @serial 89 * @see #getSelectionStart() 90 * @see #setSelectionStart(int) 91 */ 92 int selectionStart; 93 94 /** 95 * The selection refers to the selected text, and the 96 * <code>selectionEnd</code> 97 * is the end position of the selected text. 98 * 99 * @serial 100 * @see #getSelectionEnd() 101 * @see #setSelectionEnd(int) 102 */ 103 int selectionEnd; 104 105 // A flag used to tell whether the background has been set by 106 // developer code (as opposed to AWT code). Used to determine 107 // the background color of non-editable TextComponents. 108 boolean backgroundSetByClientCode = false; 109 110 /** 111 * A list of listeners that will receive events from this object. 112 */ 113 protected transient TextListener textListener; 114 115 /* 116 * JDK 1.1 serialVersionUID 117 */ 118 private static final long serialVersionUID = -2214773872412987419L; 119 120 /** 121 * Constructs a new text component initialized with the 122 * specified text. Sets the value of the cursor to 123 * <code>Cursor.TEXT_CURSOR</code>. 124 * @param text the text to be displayed; if 125 * <code>text</code> is <code>null</code>, the empty 126 * string <code>""</code> will be displayed 127 * @exception HeadlessException if 128 * <code>GraphicsEnvironment.isHeadless</code> 129 * returns true 130 * @see java.awt.GraphicsEnvironment#isHeadless 131 * @see java.awt.Cursor 132 */ 133 TextComponent(String text) throws HeadlessException { 134 GraphicsEnvironment.checkHeadless(); 135 this.text = (text != null) ? text : ""; 136 setCursor(Cursor.getPredefinedCursor(Cursor.TEXT_CURSOR)); 137 } 138 139 private void enableInputMethodsIfNecessary() { 140 if (checkForEnableIM) { 141 checkForEnableIM = false; 142 try { 143 Toolkit toolkit = Toolkit.getDefaultToolkit(); 144 boolean shouldEnable = false; 145 if (toolkit instanceof InputMethodSupport) { 146 shouldEnable = ((InputMethodSupport)toolkit) 147 .enableInputMethodsForTextComponent(); 148 } 149 enableInputMethods(shouldEnable); 150 } catch (Exception e) { 151 // if something bad happens, just don't enable input methods 152 } 153 } 154 } 155 156 /** 157 * Enables or disables input method support for this text component. If input 158 * method support is enabled and the text component also processes key events, 159 * incoming events are offered to the current input method and will only be 160 * processed by the component or dispatched to its listeners if the input method 161 * does not consume them. Whether and how input method support for this text 162 * component is enabled or disabled by default is implementation dependent. 163 * 164 * @param enable true to enable, false to disable 165 * @see #processKeyEvent 166 * @since 1.2 167 */ 168 public void enableInputMethods(boolean enable) { 169 checkForEnableIM = false; 170 super.enableInputMethods(enable); 171 } 172 173 boolean areInputMethodsEnabled() { 174 // moved from the constructor above to here and addNotify below, 175 // this call will initialize the toolkit if not already initialized. 176 if (checkForEnableIM) { 177 enableInputMethodsIfNecessary(); 178 } 179 180 // TextComponent handles key events without touching the eventMask or 181 // having a key listener, so just check whether the flag is set 182 return (eventMask & AWTEvent.INPUT_METHODS_ENABLED_MASK) != 0; 183 } 184 185 public InputMethodRequests getInputMethodRequests() { 186 TextComponentPeer peer = (TextComponentPeer)this.peer; 187 if (peer != null) return peer.getInputMethodRequests(); 188 else return null; 189 } 190 191 192 193 /** 194 * Makes this Component displayable by connecting it to a 195 * native screen resource. 196 * This method is called internally by the toolkit and should 197 * not be called directly by programs. 198 * @see java.awt.TextComponent#removeNotify 199 */ 200 public void addNotify() { 201 super.addNotify(); 202 enableInputMethodsIfNecessary(); 203 } 204 205 /** 206 * Removes the <code>TextComponent</code>'s peer. 207 * The peer allows us to modify the appearance of the 208 * <code>TextComponent</code> without changing its 209 * functionality. 210 */ 211 public void removeNotify() { 212 synchronized (getTreeLock()) { 213 TextComponentPeer peer = (TextComponentPeer)this.peer; 214 if (peer != null) { 215 text = peer.getText(); 216 selectionStart = peer.getSelectionStart(); 217 selectionEnd = peer.getSelectionEnd(); 218 } 219 super.removeNotify(); 220 } 221 } 222 223 /** 224 * Sets the text that is presented by this 225 * text component to be the specified text. 226 * @param t the new text; 227 * if this parameter is <code>null</code> then 228 * the text is set to the empty string "" 229 * @see java.awt.TextComponent#getText 230 */ 231 public synchronized void setText(String t) { 232 TextComponentPeer peer = (TextComponentPeer)this.peer; 233 if (peer != null) { 234 text = peer.getText(); 235 } 236 237 boolean skipTextEvent = (text == null || text.isEmpty()) 238 && (t == null || t.isEmpty()); 239 text = (t != null) ? t : ""; 240 // Please note that we do not want to post an event 241 // if TextArea.setText() or TextField.setText() replaces an empty text 242 // by an empty text, that is, if component's text remains unchanged. 243 if (peer != null && !skipTextEvent) { 244 peer.setText(text); 245 } 246 } 247 248 /** 249 * Returns the text that is presented by this text component. 250 * By default, this is an empty string. 251 * 252 * @return the value of this <code>TextComponent</code> 253 * @see java.awt.TextComponent#setText 254 */ 255 public synchronized String getText() { 256 TextComponentPeer peer = (TextComponentPeer)this.peer; 257 if (peer != null) { 258 text = peer.getText(); 259 } 260 return text; 261 } 262 263 /** 264 * Returns the selected text from the text that is 265 * presented by this text component. 266 * @return the selected text of this text component 267 * @see java.awt.TextComponent#select 268 */ 269 public synchronized String getSelectedText() { 270 return getText().substring(getSelectionStart(), getSelectionEnd()); 271 } 272 273 /** 274 * Indicates whether or not this text component is editable. 275 * @return <code>true</code> if this text component is 276 * editable; <code>false</code> otherwise. 277 * @see java.awt.TextComponent#setEditable 278 * @since 1.0 279 */ 280 public boolean isEditable() { 281 return editable; 282 } 283 284 /** 285 * Sets the flag that determines whether or not this 286 * text component is editable. 287 * <p> 288 * If the flag is set to <code>true</code>, this text component 289 * becomes user editable. If the flag is set to <code>false</code>, 290 * the user cannot change the text of this text component. 291 * By default, non-editable text components have a background color 292 * of SystemColor.control. This default can be overridden by 293 * calling setBackground. 294 * 295 * @param b a flag indicating whether this text component 296 * is user editable. 297 * @see java.awt.TextComponent#isEditable 298 * @since 1.0 299 */ 300 public synchronized void setEditable(boolean b) { 301 if (editable == b) { 302 return; 303 } 304 305 editable = b; 306 TextComponentPeer peer = (TextComponentPeer)this.peer; 307 if (peer != null) { 308 peer.setEditable(b); 309 } 310 } 311 312 /** 313 * Gets the background color of this text component. 314 * 315 * By default, non-editable text components have a background color 316 * of SystemColor.control. This default can be overridden by 317 * calling setBackground. 318 * 319 * @return This text component's background color. 320 * If this text component does not have a background color, 321 * the background color of its parent is returned. 322 * @see #setBackground(Color) 323 * @since 1.0 324 */ 325 public Color getBackground() { 326 if (!editable && !backgroundSetByClientCode) { 327 return SystemColor.control; 328 } 329 330 return super.getBackground(); 331 } 332 333 /** 334 * Sets the background color of this text component. 335 * 336 * @param c The color to become this text component's color. 337 * If this parameter is null then this text component 338 * will inherit the background color of its parent. 339 * @see #getBackground() 340 * @since 1.0 341 */ 342 public void setBackground(Color c) { 343 backgroundSetByClientCode = true; 344 super.setBackground(c); 345 } 346 347 /** 348 * Gets the start position of the selected text in 349 * this text component. 350 * @return the start position of the selected text 351 * @see java.awt.TextComponent#setSelectionStart 352 * @see java.awt.TextComponent#getSelectionEnd 353 */ 354 public synchronized int getSelectionStart() { 355 TextComponentPeer peer = (TextComponentPeer)this.peer; 356 if (peer != null) { 357 selectionStart = peer.getSelectionStart(); 358 } 359 return selectionStart; 360 } 361 362 /** 363 * Sets the selection start for this text component to 364 * the specified position. The new start point is constrained 365 * to be at or before the current selection end. It also 366 * cannot be set to less than zero, the beginning of the 367 * component's text. 368 * If the caller supplies a value for <code>selectionStart</code> 369 * that is out of bounds, the method enforces these constraints 370 * silently, and without failure. 371 * @param selectionStart the start position of the 372 * selected text 373 * @see java.awt.TextComponent#getSelectionStart 374 * @see java.awt.TextComponent#setSelectionEnd 375 * @since 1.1 376 */ 377 public synchronized void setSelectionStart(int selectionStart) { 378 /* Route through select method to enforce consistent policy 379 * between selectionStart and selectionEnd. 380 */ 381 select(selectionStart, getSelectionEnd()); 382 } 383 384 /** 385 * Gets the end position of the selected text in 386 * this text component. 387 * @return the end position of the selected text 388 * @see java.awt.TextComponent#setSelectionEnd 389 * @see java.awt.TextComponent#getSelectionStart 390 */ 391 public synchronized int getSelectionEnd() { 392 TextComponentPeer peer = (TextComponentPeer)this.peer; 393 if (peer != null) { 394 selectionEnd = peer.getSelectionEnd(); 395 } 396 return selectionEnd; 397 } 398 399 /** 400 * Sets the selection end for this text component to 401 * the specified position. The new end point is constrained 402 * to be at or after the current selection start. It also 403 * cannot be set beyond the end of the component's text. 404 * If the caller supplies a value for <code>selectionEnd</code> 405 * that is out of bounds, the method enforces these constraints 406 * silently, and without failure. 407 * @param selectionEnd the end position of the 408 * selected text 409 * @see java.awt.TextComponent#getSelectionEnd 410 * @see java.awt.TextComponent#setSelectionStart 411 * @since 1.1 412 */ 413 public synchronized void setSelectionEnd(int selectionEnd) { 414 /* Route through select method to enforce consistent policy 415 * between selectionStart and selectionEnd. 416 */ 417 select(getSelectionStart(), selectionEnd); 418 } 419 420 /** 421 * Selects the text between the specified start and end positions. 422 * <p> 423 * This method sets the start and end positions of the 424 * selected text, enforcing the restriction that the start position 425 * must be greater than or equal to zero. The end position must be 426 * greater than or equal to the start position, and less than or 427 * equal to the length of the text component's text. The 428 * character positions are indexed starting with zero. 429 * The length of the selection is 430 * <code>endPosition</code> - <code>startPosition</code>, so the 431 * character at <code>endPosition</code> is not selected. 432 * If the start and end positions of the selected text are equal, 433 * all text is deselected. 434 * <p> 435 * If the caller supplies values that are inconsistent or out of 436 * bounds, the method enforces these constraints silently, and 437 * without failure. Specifically, if the start position or end 438 * position is greater than the length of the text, it is reset to 439 * equal the text length. If the start position is less than zero, 440 * it is reset to zero, and if the end position is less than the 441 * start position, it is reset to the start position. 442 * 443 * @param selectionStart the zero-based index of the first 444 character (<code>char</code> value) to be selected 445 * @param selectionEnd the zero-based end position of the 446 text to be selected; the character (<code>char</code> value) at 447 <code>selectionEnd</code> is not selected 448 * @see java.awt.TextComponent#setSelectionStart 449 * @see java.awt.TextComponent#setSelectionEnd 450 * @see java.awt.TextComponent#selectAll 451 */ 452 public synchronized void select(int selectionStart, int selectionEnd) { 453 String text = getText(); 454 if (selectionStart < 0) { 455 selectionStart = 0; 456 } 457 if (selectionStart > text.length()) { 458 selectionStart = text.length(); 459 } 460 if (selectionEnd > text.length()) { 461 selectionEnd = text.length(); 462 } 463 if (selectionEnd < selectionStart) { 464 selectionEnd = selectionStart; 465 } 466 467 this.selectionStart = selectionStart; 468 this.selectionEnd = selectionEnd; 469 470 TextComponentPeer peer = (TextComponentPeer)this.peer; 471 if (peer != null) { 472 peer.select(selectionStart, selectionEnd); 473 } 474 } 475 476 /** 477 * Selects all the text in this text component. 478 * @see java.awt.TextComponent#select 479 */ 480 public synchronized void selectAll() { 481 this.selectionStart = 0; 482 this.selectionEnd = getText().length(); 483 484 TextComponentPeer peer = (TextComponentPeer)this.peer; 485 if (peer != null) { 486 peer.select(selectionStart, selectionEnd); 487 } 488 } 489 490 /** 491 * Sets the position of the text insertion caret. 492 * The caret position is constrained to be between 0 493 * and the last character of the text, inclusive. 494 * If the passed-in value is greater than this range, 495 * the value is set to the last character (or 0 if 496 * the <code>TextComponent</code> contains no text) 497 * and no error is returned. If the passed-in value is 498 * less than 0, an <code>IllegalArgumentException</code> 499 * is thrown. 500 * 501 * @param position the position of the text insertion caret 502 * @exception IllegalArgumentException if <code>position</code> 503 * is less than zero 504 * @since 1.1 505 */ 506 public synchronized void setCaretPosition(int position) { 507 if (position < 0) { 508 throw new IllegalArgumentException("position less than zero."); 509 } 510 511 int maxposition = getText().length(); 512 if (position > maxposition) { 513 position = maxposition; 514 } 515 516 TextComponentPeer peer = (TextComponentPeer)this.peer; 517 if (peer != null) { 518 peer.setCaretPosition(position); 519 } else { 520 select(position, position); 521 } 522 } 523 524 /** 525 * Returns the position of the text insertion caret. 526 * The caret position is constrained to be between 0 527 * and the last character of the text, inclusive. 528 * If the text or caret have not been set, the default 529 * caret position is 0. 530 * 531 * @return the position of the text insertion caret 532 * @see #setCaretPosition(int) 533 * @since 1.1 534 */ 535 public synchronized int getCaretPosition() { 536 TextComponentPeer peer = (TextComponentPeer)this.peer; 537 int position = 0; 538 539 if (peer != null) { 540 position = peer.getCaretPosition(); 541 } else { 542 position = selectionStart; 543 } 544 int maxposition = getText().length(); 545 if (position > maxposition) { 546 position = maxposition; 547 } 548 return position; 549 } 550 551 /** 552 * Adds the specified text event listener to receive text events 553 * from this text component. 554 * If <code>l</code> is <code>null</code>, no exception is 555 * thrown and no action is performed. 556 * <p>Refer to <a href="doc-files/AWTThreadIssues.html#ListenersThreads" 557 * >AWT Threading Issues</a> for details on AWT's threading model. 558 * 559 * @param l the text event listener 560 * @see #removeTextListener 561 * @see #getTextListeners 562 * @see java.awt.event.TextListener 563 */ 564 public synchronized void addTextListener(TextListener l) { 565 if (l == null) { 566 return; 567 } 568 textListener = AWTEventMulticaster.add(textListener, l); 569 newEventsOnly = true; 570 } 571 572 /** 573 * Removes the specified text event listener so that it no longer 574 * receives text events from this text component 575 * If <code>l</code> is <code>null</code>, no exception is 576 * thrown and no action is performed. 577 * <p>Refer to <a href="doc-files/AWTThreadIssues.html#ListenersThreads" 578 * >AWT Threading Issues</a> for details on AWT's threading model. 579 * 580 * @param l the text listener 581 * @see #addTextListener 582 * @see #getTextListeners 583 * @see java.awt.event.TextListener 584 * @since 1.1 585 */ 586 public synchronized void removeTextListener(TextListener l) { 587 if (l == null) { 588 return; 589 } 590 textListener = AWTEventMulticaster.remove(textListener, l); 591 } 592 593 /** 594 * Returns an array of all the text listeners 595 * registered on this text component. 596 * 597 * @return all of this text component's <code>TextListener</code>s 598 * or an empty array if no text 599 * listeners are currently registered 600 * 601 * 602 * @see #addTextListener 603 * @see #removeTextListener 604 * @since 1.4 605 */ 606 public synchronized TextListener[] getTextListeners() { 607 return getListeners(TextListener.class); 608 } 609 610 /** 611 * Returns an array of all the objects currently registered 612 * as <code><em>Foo</em>Listener</code>s 613 * upon this <code>TextComponent</code>. 614 * <code><em>Foo</em>Listener</code>s are registered using the 615 * <code>add<em>Foo</em>Listener</code> method. 616 * 617 * <p> 618 * You can specify the <code>listenerType</code> argument 619 * with a class literal, such as 620 * <code><em>Foo</em>Listener.class</code>. 621 * For example, you can query a 622 * <code>TextComponent</code> <code>t</code> 623 * for its text listeners with the following code: 624 * 625 * <pre>TextListener[] tls = (TextListener[])(t.getListeners(TextListener.class));</pre> 626 * 627 * If no such listeners exist, this method returns an empty array. 628 * 629 * @param listenerType the type of listeners requested; this parameter 630 * should specify an interface that descends from 631 * <code>java.util.EventListener</code> 632 * @return an array of all objects registered as 633 * <code><em>Foo</em>Listener</code>s on this text component, 634 * or an empty array if no such 635 * listeners have been added 636 * @exception ClassCastException if <code>listenerType</code> 637 * doesn't specify a class or interface that implements 638 * <code>java.util.EventListener</code> 639 * 640 * @see #getTextListeners 641 * @since 1.3 642 */ 643 public <T extends EventListener> T[] getListeners(Class<T> listenerType) { 644 EventListener l = null; 645 if (listenerType == TextListener.class) { 646 l = textListener; 647 } else { 648 return super.getListeners(listenerType); 649 } 650 return AWTEventMulticaster.getListeners(l, listenerType); 651 } 652 653 // REMIND: remove when filtering is done at lower level 654 boolean eventEnabled(AWTEvent e) { 655 if (e.id == TextEvent.TEXT_VALUE_CHANGED) { 656 if ((eventMask & AWTEvent.TEXT_EVENT_MASK) != 0 || 657 textListener != null) { 658 return true; 659 } 660 return false; 661 } 662 return super.eventEnabled(e); 663 } 664 665 /** 666 * Processes events on this text component. If the event is a 667 * <code>TextEvent</code>, it invokes the <code>processTextEvent</code> 668 * method else it invokes its superclass's <code>processEvent</code>. 669 * <p>Note that if the event parameter is <code>null</code> 670 * the behavior is unspecified and may result in an 671 * exception. 672 * 673 * @param e the event 674 */ 675 protected void processEvent(AWTEvent e) { 676 if (e instanceof TextEvent) { 677 processTextEvent((TextEvent)e); 678 return; 679 } 680 super.processEvent(e); 681 } 682 683 /** 684 * Processes text events occurring on this text component by 685 * dispatching them to any registered <code>TextListener</code> objects. 686 * <p> 687 * NOTE: This method will not be called unless text events 688 * are enabled for this component. This happens when one of the 689 * following occurs: 690 * <ul> 691 * <li>A <code>TextListener</code> object is registered 692 * via <code>addTextListener</code> 693 * <li>Text events are enabled via <code>enableEvents</code> 694 * </ul> 695 * <p>Note that if the event parameter is <code>null</code> 696 * the behavior is unspecified and may result in an 697 * exception. 698 * 699 * @param e the text event 700 * @see Component#enableEvents 701 */ 702 protected void processTextEvent(TextEvent e) { 703 TextListener listener = textListener; 704 if (listener != null) { 705 int id = e.getID(); 706 switch (id) { 707 case TextEvent.TEXT_VALUE_CHANGED: 708 listener.textValueChanged(e); 709 break; 710 } 711 } 712 } 713 714 /** 715 * Returns a string representing the state of this 716 * <code>TextComponent</code>. This 717 * method is intended to be used only for debugging purposes, and the 718 * content and format of the returned string may vary between 719 * implementations. The returned string may be empty but may not be 720 * <code>null</code>. 721 * 722 * @return the parameter string of this text component 723 */ 724 protected String paramString() { 725 String str = super.paramString() + ",text=" + getText(); 726 if (editable) { 727 str += ",editable"; 728 } 729 return str + ",selection=" + getSelectionStart() + "-" + getSelectionEnd(); 730 } 731 732 /** 733 * Assigns a valid value to the canAccessClipboard instance variable. 734 */ 735 private boolean canAccessClipboard() { 736 SecurityManager sm = System.getSecurityManager(); 737 if (sm == null) return true; 738 try { 739 sm.checkPermission(AWTPermissions.ACCESS_CLIPBOARD_PERMISSION); 740 return true; 741 } catch (SecurityException e) {} 742 return false; 743 } 744 745 /* 746 * Serialization support. 747 */ 748 /** 749 * The textComponent SerializedDataVersion. 750 * 751 * @serial 752 */ 753 private int textComponentSerializedDataVersion = 1; 754 755 /** 756 * Writes default serializable fields to stream. Writes 757 * a list of serializable TextListener(s) as optional data. 758 * The non-serializable TextListener(s) are detected and 759 * no attempt is made to serialize them. 760 * 761 * @serialData Null terminated sequence of zero or more pairs. 762 * A pair consists of a String and Object. 763 * The String indicates the type of object and 764 * is one of the following : 765 * textListenerK indicating and TextListener object. 766 * 767 * @see AWTEventMulticaster#save(ObjectOutputStream, String, EventListener) 768 * @see java.awt.Component#textListenerK 769 */ 770 private void writeObject(java.io.ObjectOutputStream s) 771 throws IOException 772 { 773 // Serialization support. Since the value of the fields 774 // selectionStart, selectionEnd, and text aren't necessarily 775 // up to date, we sync them up with the peer before serializing. 776 TextComponentPeer peer = (TextComponentPeer)this.peer; 777 if (peer != null) { 778 text = peer.getText(); 779 selectionStart = peer.getSelectionStart(); 780 selectionEnd = peer.getSelectionEnd(); 781 } 782 783 s.defaultWriteObject(); 784 785 AWTEventMulticaster.save(s, textListenerK, textListener); 786 s.writeObject(null); 787 } 788 789 /** 790 * Read the ObjectInputStream, and if it isn't null, 791 * add a listener to receive text events fired by the 792 * TextComponent. Unrecognized keys or values will be 793 * ignored. 794 * 795 * @exception HeadlessException if 796 * <code>GraphicsEnvironment.isHeadless()</code> returns 797 * <code>true</code> 798 * @see #removeTextListener 799 * @see #addTextListener 800 * @see java.awt.GraphicsEnvironment#isHeadless 801 */ 802 private void readObject(ObjectInputStream s) 803 throws ClassNotFoundException, IOException, HeadlessException 804 { 805 GraphicsEnvironment.checkHeadless(); 806 s.defaultReadObject(); 807 808 // Make sure the state we just read in for text, 809 // selectionStart and selectionEnd has legal values 810 this.text = (text != null) ? text : ""; 811 select(selectionStart, selectionEnd); 812 813 Object keyOrNull; 814 while(null != (keyOrNull = s.readObject())) { 815 String key = ((String)keyOrNull).intern(); 816 817 if (textListenerK == key) { 818 addTextListener((TextListener)(s.readObject())); 819 } else { 820 // skip value for unrecognized key 821 s.readObject(); 822 } 823 } 824 enableInputMethodsIfNecessary(); 825 } 826 827 828 ///////////////// 829 // Accessibility support 830 //////////////// 831 832 /** 833 * Gets the AccessibleContext associated with this TextComponent. 834 * For text components, the AccessibleContext takes the form of an 835 * AccessibleAWTTextComponent. 836 * A new AccessibleAWTTextComponent instance is created if necessary. 837 * 838 * @return an AccessibleAWTTextComponent that serves as the 839 * AccessibleContext of this TextComponent 840 * @since 1.3 841 */ 842 public AccessibleContext getAccessibleContext() { 843 if (accessibleContext == null) { 844 accessibleContext = new AccessibleAWTTextComponent(); 845 } 846 return accessibleContext; 847 } 848 849 /** 850 * This class implements accessibility support for the 851 * <code>TextComponent</code> class. It provides an implementation of the 852 * Java Accessibility API appropriate to text component user-interface 853 * elements. 854 * @since 1.3 855 */ 856 protected class AccessibleAWTTextComponent extends AccessibleAWTComponent 857 implements AccessibleText, TextListener 858 { 859 /* 860 * JDK 1.3 serialVersionUID 861 */ 862 private static final long serialVersionUID = 3631432373506317811L; 863 864 /** 865 * Constructs an AccessibleAWTTextComponent. Adds a listener to track 866 * caret change. 867 */ 868 public AccessibleAWTTextComponent() { 869 TextComponent.this.addTextListener(this); 870 } 871 872 /** 873 * TextListener notification of a text value change. 874 */ 875 public void textValueChanged(TextEvent textEvent) { 876 Integer cpos = Integer.valueOf(TextComponent.this.getCaretPosition()); 877 firePropertyChange(ACCESSIBLE_TEXT_PROPERTY, null, cpos); 878 } 879 880 /** 881 * Gets the state set of the TextComponent. 882 * The AccessibleStateSet of an object is composed of a set of 883 * unique AccessibleStates. A change in the AccessibleStateSet 884 * of an object will cause a PropertyChangeEvent to be fired 885 * for the AccessibleContext.ACCESSIBLE_STATE_PROPERTY property. 886 * 887 * @return an instance of AccessibleStateSet containing the 888 * current state set of the object 889 * @see AccessibleStateSet 890 * @see AccessibleState 891 * @see #addPropertyChangeListener 892 */ 893 public AccessibleStateSet getAccessibleStateSet() { 894 AccessibleStateSet states = super.getAccessibleStateSet(); 895 if (TextComponent.this.isEditable()) { 896 states.add(AccessibleState.EDITABLE); 897 } 898 return states; 899 } 900 901 902 /** 903 * Gets the role of this object. 904 * 905 * @return an instance of AccessibleRole describing the role of the 906 * object (AccessibleRole.TEXT) 907 * @see AccessibleRole 908 */ 909 public AccessibleRole getAccessibleRole() { 910 return AccessibleRole.TEXT; 911 } 912 913 /** 914 * Get the AccessibleText associated with this object. In the 915 * implementation of the Java Accessibility API for this class, 916 * return this object, which is responsible for implementing the 917 * AccessibleText interface on behalf of itself. 918 * 919 * @return this object 920 */ 921 public AccessibleText getAccessibleText() { 922 return this; 923 } 924 925 926 // --- interface AccessibleText methods ------------------------ 927 928 /** 929 * Many of these methods are just convenience methods; they 930 * just call the equivalent on the parent 931 */ 932 933 /** 934 * Given a point in local coordinates, return the zero-based index 935 * of the character under that Point. If the point is invalid, 936 * this method returns -1. 937 * 938 * @param p the Point in local coordinates 939 * @return the zero-based index of the character under Point p. 940 */ 941 public int getIndexAtPoint(Point p) { 942 return -1; 943 } 944 945 /** 946 * Determines the bounding box of the character at the given 947 * index into the string. The bounds are returned in local 948 * coordinates. If the index is invalid a null rectangle 949 * is returned. 950 * 951 * @param i the index into the String >= 0 952 * @return the screen coordinates of the character's bounding box 953 */ 954 public Rectangle getCharacterBounds(int i) { 955 return null; 956 } 957 958 /** 959 * Returns the number of characters (valid indices) 960 * 961 * @return the number of characters >= 0 962 */ 963 public int getCharCount() { 964 return TextComponent.this.getText().length(); 965 } 966 967 /** 968 * Returns the zero-based offset of the caret. 969 * 970 * Note: The character to the right of the caret will have the 971 * same index value as the offset (the caret is between 972 * two characters). 973 * 974 * @return the zero-based offset of the caret. 975 */ 976 public int getCaretPosition() { 977 return TextComponent.this.getCaretPosition(); 978 } 979 980 /** 981 * Returns the AttributeSet for a given character (at a given index). 982 * 983 * @param i the zero-based index into the text 984 * @return the AttributeSet of the character 985 */ 986 public AttributeSet getCharacterAttribute(int i) { 987 return null; // No attributes in TextComponent 988 } 989 990 /** 991 * Returns the start offset within the selected text. 992 * If there is no selection, but there is 993 * a caret, the start and end offsets will be the same. 994 * Return 0 if the text is empty, or the caret position 995 * if no selection. 996 * 997 * @return the index into the text of the start of the selection >= 0 998 */ 999 public int getSelectionStart() { 1000 return TextComponent.this.getSelectionStart(); 1001 } 1002 1003 /** 1004 * Returns the end offset within the selected text. 1005 * If there is no selection, but there is 1006 * a caret, the start and end offsets will be the same. 1007 * Return 0 if the text is empty, or the caret position 1008 * if no selection. 1009 * 1010 * @return the index into the text of the end of the selection >= 0 1011 */ 1012 public int getSelectionEnd() { 1013 return TextComponent.this.getSelectionEnd(); 1014 } 1015 1016 /** 1017 * Returns the portion of the text that is selected. 1018 * 1019 * @return the text, null if no selection 1020 */ 1021 public String getSelectedText() { 1022 String selText = TextComponent.this.getSelectedText(); 1023 // Fix for 4256662 1024 if (selText == null || selText.equals("")) { 1025 return null; 1026 } 1027 return selText; 1028 } 1029 1030 /** 1031 * Returns the String at a given index. 1032 * 1033 * @param part the AccessibleText.CHARACTER, AccessibleText.WORD, 1034 * or AccessibleText.SENTENCE to retrieve 1035 * @param index an index within the text >= 0 1036 * @return the letter, word, or sentence, 1037 * null for an invalid index or part 1038 */ 1039 public String getAtIndex(int part, int index) { 1040 if (index < 0 || index >= TextComponent.this.getText().length()) { 1041 return null; 1042 } 1043 switch (part) { 1044 case AccessibleText.CHARACTER: 1045 return TextComponent.this.getText().substring(index, index+1); 1046 case AccessibleText.WORD: { 1047 String s = TextComponent.this.getText(); 1048 BreakIterator words = BreakIterator.getWordInstance(); 1049 words.setText(s); 1050 int end = words.following(index); 1051 return s.substring(words.previous(), end); 1052 } 1053 case AccessibleText.SENTENCE: { 1054 String s = TextComponent.this.getText(); 1055 BreakIterator sentence = BreakIterator.getSentenceInstance(); 1056 sentence.setText(s); 1057 int end = sentence.following(index); 1058 return s.substring(sentence.previous(), end); 1059 } 1060 default: 1061 return null; 1062 } 1063 } 1064 1065 private static final boolean NEXT = true; 1066 private static final boolean PREVIOUS = false; 1067 1068 /** 1069 * Needed to unify forward and backward searching. 1070 * The method assumes that s is the text assigned to words. 1071 */ 1072 private int findWordLimit(int index, BreakIterator words, boolean direction, 1073 String s) { 1074 // Fix for 4256660 and 4256661. 1075 // Words iterator is different from character and sentence iterators 1076 // in that end of one word is not necessarily start of another word. 1077 // Please see java.text.BreakIterator JavaDoc. The code below is 1078 // based on nextWordStartAfter example from BreakIterator.java. 1079 int last = (direction == NEXT) ? words.following(index) 1080 : words.preceding(index); 1081 int current = (direction == NEXT) ? words.next() 1082 : words.previous(); 1083 while (current != BreakIterator.DONE) { 1084 for (int p = Math.min(last, current); p < Math.max(last, current); p++) { 1085 if (Character.isLetter(s.charAt(p))) { 1086 return last; 1087 } 1088 } 1089 last = current; 1090 current = (direction == NEXT) ? words.next() 1091 : words.previous(); 1092 } 1093 return BreakIterator.DONE; 1094 } 1095 1096 /** 1097 * Returns the String after a given index. 1098 * 1099 * @param part the AccessibleText.CHARACTER, AccessibleText.WORD, 1100 * or AccessibleText.SENTENCE to retrieve 1101 * @param index an index within the text >= 0 1102 * @return the letter, word, or sentence, null for an invalid 1103 * index or part 1104 */ 1105 public String getAfterIndex(int part, int index) { 1106 if (index < 0 || index >= TextComponent.this.getText().length()) { 1107 return null; 1108 } 1109 switch (part) { 1110 case AccessibleText.CHARACTER: 1111 if (index+1 >= TextComponent.this.getText().length()) { 1112 return null; 1113 } 1114 return TextComponent.this.getText().substring(index+1, index+2); 1115 case AccessibleText.WORD: { 1116 String s = TextComponent.this.getText(); 1117 BreakIterator words = BreakIterator.getWordInstance(); 1118 words.setText(s); 1119 int start = findWordLimit(index, words, NEXT, s); 1120 if (start == BreakIterator.DONE || start >= s.length()) { 1121 return null; 1122 } 1123 int end = words.following(start); 1124 if (end == BreakIterator.DONE || end >= s.length()) { 1125 return null; 1126 } 1127 return s.substring(start, end); 1128 } 1129 case AccessibleText.SENTENCE: { 1130 String s = TextComponent.this.getText(); 1131 BreakIterator sentence = BreakIterator.getSentenceInstance(); 1132 sentence.setText(s); 1133 int start = sentence.following(index); 1134 if (start == BreakIterator.DONE || start >= s.length()) { 1135 return null; 1136 } 1137 int end = sentence.following(start); 1138 if (end == BreakIterator.DONE || end >= s.length()) { 1139 return null; 1140 } 1141 return s.substring(start, end); 1142 } 1143 default: 1144 return null; 1145 } 1146 } 1147 1148 1149 /** 1150 * Returns the String before a given index. 1151 * 1152 * @param part the AccessibleText.CHARACTER, AccessibleText.WORD, 1153 * or AccessibleText.SENTENCE to retrieve 1154 * @param index an index within the text >= 0 1155 * @return the letter, word, or sentence, null for an invalid index 1156 * or part 1157 */ 1158 public String getBeforeIndex(int part, int index) { 1159 if (index < 0 || index > TextComponent.this.getText().length()-1) { 1160 return null; 1161 } 1162 switch (part) { 1163 case AccessibleText.CHARACTER: 1164 if (index == 0) { 1165 return null; 1166 } 1167 return TextComponent.this.getText().substring(index-1, index); 1168 case AccessibleText.WORD: { 1169 String s = TextComponent.this.getText(); 1170 BreakIterator words = BreakIterator.getWordInstance(); 1171 words.setText(s); 1172 int end = findWordLimit(index, words, PREVIOUS, s); 1173 if (end == BreakIterator.DONE) { 1174 return null; 1175 } 1176 int start = words.preceding(end); 1177 if (start == BreakIterator.DONE) { 1178 return null; 1179 } 1180 return s.substring(start, end); 1181 } 1182 case AccessibleText.SENTENCE: { 1183 String s = TextComponent.this.getText(); 1184 BreakIterator sentence = BreakIterator.getSentenceInstance(); 1185 sentence.setText(s); 1186 int end = sentence.following(index); 1187 end = sentence.previous(); 1188 int start = sentence.previous(); 1189 if (start == BreakIterator.DONE) { 1190 return null; 1191 } 1192 return s.substring(start, end); 1193 } 1194 default: 1195 return null; 1196 } 1197 } 1198 } // end of AccessibleAWTTextComponent 1199 1200 private boolean checkForEnableIM = true; 1201 }