1 /* 2 * Copyright (c) 1995, 2006, 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 sun.awt.InputMethodSupport; 34 import java.text.BreakIterator; 35 import javax.swing.text.AttributeSet; 36 import javax.accessibility.*; 37 import java.awt.im.InputMethodRequests; 38 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 JDK1.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 * True if this <code>TextComponent</code> has access 112 * to the System clipboard. 113 */ 114 transient private boolean canAccessClipboard; 115 116 transient protected TextListener textListener; 117 118 /* 119 * JDK 1.1 serialVersionUID 120 */ 121 private static final long serialVersionUID = -2214773872412987419L; 122 123 /** 124 * Constructs a new text component initialized with the 125 * specified text. Sets the value of the cursor to 126 * <code>Cursor.TEXT_CURSOR</code>. 127 * @param text the text to be displayed; if 128 * <code>text</code> is <code>null</code>, the empty 129 * string <code>""</code> will be displayed 130 * @exception HeadlessException if 131 * <code>GraphicsEnvironment.isHeadless</code> 132 * returns true 133 * @see java.awt.GraphicsEnvironment#isHeadless 134 * @see java.awt.Cursor 135 */ 136 TextComponent(String text) throws HeadlessException { 137 GraphicsEnvironment.checkHeadless(); 138 this.text = (text != null) ? text : ""; 139 setCursor(Cursor.getPredefinedCursor(Cursor.TEXT_CURSOR)); 140 checkSystemClipboardAccess(); 141 } 142 143 private void enableInputMethodsIfNecessary() { 144 if (checkForEnableIM) { 145 checkForEnableIM = false; 146 try { 147 Toolkit toolkit = Toolkit.getDefaultToolkit(); 148 boolean shouldEnable = false; 149 if (toolkit instanceof InputMethodSupport) { 150 shouldEnable = ((InputMethodSupport)toolkit) 151 .enableInputMethodsForTextComponent(); 152 } 153 enableInputMethods(shouldEnable); 154 } catch (Exception e) { 155 // if something bad happens, just don't enable input methods 156 } 157 } 158 } 159 160 /** 161 * Enables or disables input method support for this text component. If input 162 * method support is enabled and the text component also processes key events, 163 * incoming events are offered to the current input method and will only be 164 * processed by the component or dispatched to its listeners if the input method 165 * does not consume them. Whether and how input method support for this text 166 * component is enabled or disabled by default is implementation dependent. 167 * 168 * @param enable true to enable, false to disable 169 * @see #processKeyEvent 170 * @since 1.2 171 */ 172 public void enableInputMethods(boolean enable) { 173 checkForEnableIM = false; 174 super.enableInputMethods(enable); 175 } 176 177 boolean areInputMethodsEnabled() { 178 // moved from the constructor above to here and addNotify below, 179 // this call will initialize the toolkit if not already initialized. 180 if (checkForEnableIM) { 181 enableInputMethodsIfNecessary(); 182 } 183 184 // TextComponent handles key events without touching the eventMask or 185 // having a key listener, so just check whether the flag is set 186 return (eventMask & AWTEvent.INPUT_METHODS_ENABLED_MASK) != 0; 187 } 188 189 public InputMethodRequests getInputMethodRequests() { 190 TextComponentPeer peer = (TextComponentPeer)this.peer; 191 if (peer != null) return peer.getInputMethodRequests(); 192 else return null; 193 } 194 195 196 197 /** 198 * Makes this Component displayable by connecting it to a 199 * native screen resource. 200 * This method is called internally by the toolkit and should 201 * not be called directly by programs. 202 * @see java.awt.TextComponent#removeNotify 203 */ 204 public void addNotify() { 205 super.addNotify(); 206 enableInputMethodsIfNecessary(); 207 } 208 209 /** 210 * Removes the <code>TextComponent</code>'s peer. 211 * The peer allows us to modify the appearance of the 212 * <code>TextComponent</code> without changing its 213 * functionality. 214 */ 215 public void removeNotify() { 216 synchronized (getTreeLock()) { 217 TextComponentPeer peer = (TextComponentPeer)this.peer; 218 if (peer != null) { 219 text = peer.getText(); 220 selectionStart = peer.getSelectionStart(); 221 selectionEnd = peer.getSelectionEnd(); 222 } 223 super.removeNotify(); 224 } 225 } 226 227 /** 228 * Sets the text that is presented by this 229 * text component to be the specified text. 230 * @param t the new text; 231 * if this parameter is <code>null</code> then 232 * the text is set to the empty string "" 233 * @see java.awt.TextComponent#getText 234 */ 235 public synchronized void setText(String t) { 236 boolean skipTextEvent = (text == null || text.isEmpty()) 237 && (t == null || t.isEmpty()); 238 text = (t != null) ? t : ""; 239 TextComponentPeer peer = (TextComponentPeer)this.peer; 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 JDK1.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 JDK1.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 JDK1.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 JDK1.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 JDK1.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 JDK1.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 JDK1.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 JDK1.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 JDK1.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 (TextListener[])(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 void checkSystemClipboardAccess() { 736 canAccessClipboard = true; 737 SecurityManager sm = System.getSecurityManager(); 738 if (sm != null) { 739 try { 740 sm.checkSystemClipboardAccess(); 741 } 742 catch (SecurityException e) { 743 canAccessClipboard = false; 744 } 745 } 746 } 747 748 /* 749 * Serialization support. 750 */ 751 /** 752 * The textComponent SerializedDataVersion. 753 * 754 * @serial 755 */ 756 private int textComponentSerializedDataVersion = 1; 757 758 /** 759 * Writes default serializable fields to stream. Writes 760 * a list of serializable TextListener(s) as optional data. 761 * The non-serializable TextListener(s) are detected and 762 * no attempt is made to serialize them. 763 * 764 * @serialData Null terminated sequence of zero or more pairs. 765 * A pair consists of a String and Object. 766 * The String indicates the type of object and 767 * is one of the following : 768 * textListenerK indicating and TextListener object. 769 * 770 * @see AWTEventMulticaster#save(ObjectOutputStream, String, EventListener) 771 * @see java.awt.Component#textListenerK 772 */ 773 private void writeObject(java.io.ObjectOutputStream s) 774 throws IOException 775 { 776 // Serialization support. Since the value of the fields 777 // selectionStart, selectionEnd, and text aren't necessarily 778 // up to date, we sync them up with the peer before serializing. 779 TextComponentPeer peer = (TextComponentPeer)this.peer; 780 if (peer != null) { 781 text = peer.getText(); 782 selectionStart = peer.getSelectionStart(); 783 selectionEnd = peer.getSelectionEnd(); 784 } 785 786 s.defaultWriteObject(); 787 788 AWTEventMulticaster.save(s, textListenerK, textListener); 789 s.writeObject(null); 790 } 791 792 /** 793 * Read the ObjectInputStream, and if it isn't null, 794 * add a listener to receive text events fired by the 795 * TextComponent. Unrecognized keys or values will be 796 * ignored. 797 * 798 * @exception HeadlessException if 799 * <code>GraphicsEnvironment.isHeadless()</code> returns 800 * <code>true</code> 801 * @see #removeTextListener 802 * @see #addTextListener 803 * @see java.awt.GraphicsEnvironment#isHeadless 804 */ 805 private void readObject(ObjectInputStream s) 806 throws ClassNotFoundException, IOException, HeadlessException 807 { 808 GraphicsEnvironment.checkHeadless(); 809 s.defaultReadObject(); 810 811 // Make sure the state we just read in for text, 812 // selectionStart and selectionEnd has legal values 813 this.text = (text != null) ? text : ""; 814 select(selectionStart, selectionEnd); 815 816 Object keyOrNull; 817 while(null != (keyOrNull = s.readObject())) { 818 String key = ((String)keyOrNull).intern(); 819 820 if (textListenerK == key) { 821 addTextListener((TextListener)(s.readObject())); 822 } else { 823 // skip value for unrecognized key 824 s.readObject(); 825 } 826 } 827 enableInputMethodsIfNecessary(); 828 checkSystemClipboardAccess(); 829 } 830 831 832 ///////////////// 833 // Accessibility support 834 //////////////// 835 836 837 /** 838 * 839 */ 840 int getIndexAtPoint(Point p) { 841 return -1; 842 /* To be fully implemented in a future release 843 if (peer == null) { 844 return -1; 845 } 846 TextComponentPeer peer = (TextComponentPeer)this.peer; 847 return peer.getIndexAtPoint(p.x, p.y); 848 */ 849 } 850 851 852 /** 853 * 854 */ 855 Rectangle getCharacterBounds(int i) { 856 return null; 857 /* To be fully implemented in a future release 858 if (peer == null) { 859 return null; 860 } 861 TextComponentPeer peer = (TextComponentPeer)this.peer; 862 return peer.getCharacterBounds(i); 863 */ 864 } 865 866 867 /** 868 * Gets the AccessibleContext associated with this TextComponent. 869 * For text components, the AccessibleContext takes the form of an 870 * AccessibleAWTTextComponent. 871 * A new AccessibleAWTTextComponent instance is created if necessary. 872 * 873 * @return an AccessibleAWTTextComponent that serves as the 874 * AccessibleContext of this TextComponent 875 * @since 1.3 876 */ 877 public AccessibleContext getAccessibleContext() { 878 if (accessibleContext == null) { 879 accessibleContext = new AccessibleAWTTextComponent(); 880 } 881 return accessibleContext; 882 } 883 884 /** 885 * This class implements accessibility support for the 886 * <code>TextComponent</code> class. It provides an implementation of the 887 * Java Accessibility API appropriate to text component user-interface 888 * elements. 889 * @since 1.3 890 */ 891 protected class AccessibleAWTTextComponent extends AccessibleAWTComponent 892 implements AccessibleText, TextListener 893 { 894 /* 895 * JDK 1.3 serialVersionUID 896 */ 897 private static final long serialVersionUID = 3631432373506317811L; 898 899 /** 900 * Constructs an AccessibleAWTTextComponent. Adds a listener to track 901 * caret change. 902 */ 903 public AccessibleAWTTextComponent() { 904 TextComponent.this.addTextListener(this); 905 } 906 907 /** 908 * TextListener notification of a text value change. 909 */ 910 public void textValueChanged(TextEvent textEvent) { 911 Integer cpos = Integer.valueOf(TextComponent.this.getCaretPosition()); 912 firePropertyChange(ACCESSIBLE_TEXT_PROPERTY, null, cpos); 913 } 914 915 /** 916 * Gets the state set of the TextComponent. 917 * The AccessibleStateSet of an object is composed of a set of 918 * unique AccessibleStates. A change in the AccessibleStateSet 919 * of an object will cause a PropertyChangeEvent to be fired 920 * for the AccessibleContext.ACCESSIBLE_STATE_PROPERTY property. 921 * 922 * @return an instance of AccessibleStateSet containing the 923 * current state set of the object 924 * @see AccessibleStateSet 925 * @see AccessibleState 926 * @see #addPropertyChangeListener 927 */ 928 public AccessibleStateSet getAccessibleStateSet() { 929 AccessibleStateSet states = super.getAccessibleStateSet(); 930 if (TextComponent.this.isEditable()) { 931 states.add(AccessibleState.EDITABLE); 932 } 933 return states; 934 } 935 936 937 /** 938 * Gets the role of this object. 939 * 940 * @return an instance of AccessibleRole describing the role of the 941 * object (AccessibleRole.TEXT) 942 * @see AccessibleRole 943 */ 944 public AccessibleRole getAccessibleRole() { 945 return AccessibleRole.TEXT; 946 } 947 948 /** 949 * Get the AccessibleText associated with this object. In the 950 * implementation of the Java Accessibility API for this class, 951 * return this object, which is responsible for implementing the 952 * AccessibleText interface on behalf of itself. 953 * 954 * @return this object 955 */ 956 public AccessibleText getAccessibleText() { 957 return this; 958 } 959 960 961 // --- interface AccessibleText methods ------------------------ 962 963 /** 964 * Many of these methods are just convenience methods; they 965 * just call the equivalent on the parent 966 */ 967 968 /** 969 * Given a point in local coordinates, return the zero-based index 970 * of the character under that Point. If the point is invalid, 971 * this method returns -1. 972 * 973 * @param p the Point in local coordinates 974 * @return the zero-based index of the character under Point p. 975 */ 976 public int getIndexAtPoint(Point p) { 977 return TextComponent.this.getIndexAtPoint(p); 978 } 979 980 /** 981 * Determines the bounding box of the character at the given 982 * index into the string. The bounds are returned in local 983 * coordinates. If the index is invalid a null rectangle 984 * is returned. 985 * 986 * @param i the index into the String >= 0 987 * @return the screen coordinates of the character's bounding box 988 */ 989 public Rectangle getCharacterBounds(int i) { 990 return TextComponent.this.getCharacterBounds(i); 991 } 992 993 /** 994 * Returns the number of characters (valid indicies) 995 * 996 * @return the number of characters >= 0 997 */ 998 public int getCharCount() { 999 return TextComponent.this.getText().length(); 1000 } 1001 1002 /** 1003 * Returns the zero-based offset of the caret. 1004 * 1005 * Note: The character to the right of the caret will have the 1006 * same index value as the offset (the caret is between 1007 * two characters). 1008 * 1009 * @return the zero-based offset of the caret. 1010 */ 1011 public int getCaretPosition() { 1012 return TextComponent.this.getCaretPosition(); 1013 } 1014 1015 /** 1016 * Returns the AttributeSet for a given character (at a given index). 1017 * 1018 * @param i the zero-based index into the text 1019 * @return the AttributeSet of the character 1020 */ 1021 public AttributeSet getCharacterAttribute(int i) { 1022 return null; // No attributes in TextComponent 1023 } 1024 1025 /** 1026 * Returns the start offset within the selected text. 1027 * If there is no selection, but there is 1028 * a caret, the start and end offsets will be the same. 1029 * Return 0 if the text is empty, or the caret position 1030 * if no selection. 1031 * 1032 * @return the index into the text of the start of the selection >= 0 1033 */ 1034 public int getSelectionStart() { 1035 return TextComponent.this.getSelectionStart(); 1036 } 1037 1038 /** 1039 * Returns the end offset within the selected text. 1040 * If there is no selection, but there is 1041 * a caret, the start and end offsets will be the same. 1042 * Return 0 if the text is empty, or the caret position 1043 * if no selection. 1044 * 1045 * @return the index into teh text of the end of the selection >= 0 1046 */ 1047 public int getSelectionEnd() { 1048 return TextComponent.this.getSelectionEnd(); 1049 } 1050 1051 /** 1052 * Returns the portion of the text that is selected. 1053 * 1054 * @return the text, null if no selection 1055 */ 1056 public String getSelectedText() { 1057 String selText = TextComponent.this.getSelectedText(); 1058 // Fix for 4256662 1059 if (selText == null || selText.equals("")) { 1060 return null; 1061 } 1062 return selText; 1063 } 1064 1065 /** 1066 * Returns the String at a given index. 1067 * 1068 * @param part the AccessibleText.CHARACTER, AccessibleText.WORD, 1069 * or AccessibleText.SENTENCE to retrieve 1070 * @param index an index within the text >= 0 1071 * @return the letter, word, or sentence, 1072 * null for an invalid index or part 1073 */ 1074 public String getAtIndex(int part, int index) { 1075 if (index < 0 || index >= TextComponent.this.getText().length()) { 1076 return null; 1077 } 1078 switch (part) { 1079 case AccessibleText.CHARACTER: 1080 return TextComponent.this.getText().substring(index, index+1); 1081 case AccessibleText.WORD: { 1082 String s = TextComponent.this.getText(); 1083 BreakIterator words = BreakIterator.getWordInstance(); 1084 words.setText(s); 1085 int end = words.following(index); 1086 return s.substring(words.previous(), end); 1087 } 1088 case AccessibleText.SENTENCE: { 1089 String s = TextComponent.this.getText(); 1090 BreakIterator sentence = BreakIterator.getSentenceInstance(); 1091 sentence.setText(s); 1092 int end = sentence.following(index); 1093 return s.substring(sentence.previous(), end); 1094 } 1095 default: 1096 return null; 1097 } 1098 } 1099 1100 private static final boolean NEXT = true; 1101 private static final boolean PREVIOUS = false; 1102 1103 /** 1104 * Needed to unify forward and backward searching. 1105 * The method assumes that s is the text assigned to words. 1106 */ 1107 private int findWordLimit(int index, BreakIterator words, boolean direction, 1108 String s) { 1109 // Fix for 4256660 and 4256661. 1110 // Words iterator is different from character and sentence iterators 1111 // in that end of one word is not necessarily start of another word. 1112 // Please see java.text.BreakIterator JavaDoc. The code below is 1113 // based on nextWordStartAfter example from BreakIterator.java. 1114 int last = (direction == NEXT) ? words.following(index) 1115 : words.preceding(index); 1116 int current = (direction == NEXT) ? words.next() 1117 : words.previous(); 1118 while (current != BreakIterator.DONE) { 1119 for (int p = Math.min(last, current); p < Math.max(last, current); p++) { 1120 if (Character.isLetter(s.charAt(p))) { 1121 return last; 1122 } 1123 } 1124 last = current; 1125 current = (direction == NEXT) ? words.next() 1126 : words.previous(); 1127 } 1128 return BreakIterator.DONE; 1129 } 1130 1131 /** 1132 * Returns the String after a given index. 1133 * 1134 * @param part the AccessibleText.CHARACTER, AccessibleText.WORD, 1135 * or AccessibleText.SENTENCE to retrieve 1136 * @param index an index within the text >= 0 1137 * @return the letter, word, or sentence, null for an invalid 1138 * index or part 1139 */ 1140 public String getAfterIndex(int part, int index) { 1141 if (index < 0 || index >= TextComponent.this.getText().length()) { 1142 return null; 1143 } 1144 switch (part) { 1145 case AccessibleText.CHARACTER: 1146 if (index+1 >= TextComponent.this.getText().length()) { 1147 return null; 1148 } 1149 return TextComponent.this.getText().substring(index+1, index+2); 1150 case AccessibleText.WORD: { 1151 String s = TextComponent.this.getText(); 1152 BreakIterator words = BreakIterator.getWordInstance(); 1153 words.setText(s); 1154 int start = findWordLimit(index, words, NEXT, s); 1155 if (start == BreakIterator.DONE || start >= s.length()) { 1156 return null; 1157 } 1158 int end = words.following(start); 1159 if (end == BreakIterator.DONE || end >= s.length()) { 1160 return null; 1161 } 1162 return s.substring(start, end); 1163 } 1164 case AccessibleText.SENTENCE: { 1165 String s = TextComponent.this.getText(); 1166 BreakIterator sentence = BreakIterator.getSentenceInstance(); 1167 sentence.setText(s); 1168 int start = sentence.following(index); 1169 if (start == BreakIterator.DONE || start >= s.length()) { 1170 return null; 1171 } 1172 int end = sentence.following(start); 1173 if (end == BreakIterator.DONE || end >= s.length()) { 1174 return null; 1175 } 1176 return s.substring(start, end); 1177 } 1178 default: 1179 return null; 1180 } 1181 } 1182 1183 1184 /** 1185 * Returns the String before a given index. 1186 * 1187 * @param part the AccessibleText.CHARACTER, AccessibleText.WORD, 1188 * or AccessibleText.SENTENCE to retrieve 1189 * @param index an index within the text >= 0 1190 * @return the letter, word, or sentence, null for an invalid index 1191 * or part 1192 */ 1193 public String getBeforeIndex(int part, int index) { 1194 if (index < 0 || index > TextComponent.this.getText().length()-1) { 1195 return null; 1196 } 1197 switch (part) { 1198 case AccessibleText.CHARACTER: 1199 if (index == 0) { 1200 return null; 1201 } 1202 return TextComponent.this.getText().substring(index-1, index); 1203 case AccessibleText.WORD: { 1204 String s = TextComponent.this.getText(); 1205 BreakIterator words = BreakIterator.getWordInstance(); 1206 words.setText(s); 1207 int end = findWordLimit(index, words, PREVIOUS, s); 1208 if (end == BreakIterator.DONE) { 1209 return null; 1210 } 1211 int start = words.preceding(end); 1212 if (start == BreakIterator.DONE) { 1213 return null; 1214 } 1215 return s.substring(start, end); 1216 } 1217 case AccessibleText.SENTENCE: { 1218 String s = TextComponent.this.getText(); 1219 BreakIterator sentence = BreakIterator.getSentenceInstance(); 1220 sentence.setText(s); 1221 int end = sentence.following(index); 1222 end = sentence.previous(); 1223 int start = sentence.previous(); 1224 if (start == BreakIterator.DONE) { 1225 return null; 1226 } 1227 return s.substring(start, end); 1228 } 1229 default: 1230 return null; 1231 } 1232 } 1233 } // end of AccessibleAWTTextComponent 1234 1235 private boolean checkForEnableIM = true; 1236 }