Exforsys

Home arrow Reviews arrow Swing Extreme Testing

Swing Extreme Testing - Getting the Text of a Text Field

Author: Packt Publishing     Published on: 10th Jul 2008

Getting the Text of a Text Field

The method is getText(), and there is a variant to retrieve just the selected text:

Ads

Sample Code
  1. //... from UI
  2. /**
  3.  
  4.  
  5.  * Safely read the text of the given text component.
  6. */
  7. public static String getText( JTextComponent textComponent ) {
  8. return getTextImpl( textComponent, true )
  9. }
  10. /**
  11.  
  12.  
  13.  * Safely read the selected text of the given text component.
  14. */
  15. public static String getSelectedText(
  16. JTextComponent textComponent ) {
  17. return getTextImpl( textComponent, false )
  18. }
  19. private static String getTextImpl(
  20. final JTextComponent textComponent,
  21. final boolean allText ) {
  22.  
  23.  
  24.  final String[] resultHolder = new String[]{null}
  25.  
  26.  
  27.  
  28.  
  29. runInEventThread( new Runnable() {
  30. public void run() {
  31. resultHolder[0] = allText ? textComponent.getText() :
  32. textComponent.getSelectedText()
  33.  
  34.  }
  35. } )
  36. return resultHolder[0]
  37.  
  38.  
  39. }
Copyright exforsys.com


Frame Disposal

In a lot of our unit tests, we will want to dispose of any dialogs or frames that are still showing at the end of a test. This method is brutal but effective:

Sample Code
  1. //... from UI
  2. public static void disposeOfAllFrames() {
  3. Runnable runnable = new Runnable() {
  4. public void run() {
  5. Frame[] allFrames = Frame.getFrames()
  6. for (Frame allFrame : allFrames) {
  7. allFrame.dispose()
  8. }
  9. }
  10. }
  11. runInEventThread( runnable )
  12. }
Copyright exforsys.com


Ads



 
This tutorial is part of a Swing Extreme Testing tutorial series. Read it from the beginning and learn yourself.

Swing Extreme Testing

 

Comments