257
Chapter 7
C H A P T E R S E V E N
Text
Hacks 48–55
Text handling pervades the Swing API, from the labeling of a JButton to
handling styled text in a
JTextArea. When we talk about hacking Swing’s
text handling, we often mean two different things: hacking into the repre-
sentation of the text (say, by making it searchable), or hacking into how that
text is displayed. This chapter will help you see that Swing text isn’t just
about little
JTextFields for entering your username.
H A C K
#48
Make Text Components Searchable Hack #48
This hack will show you how to add incremental search to a text area as a
simple document listener, making it very easy to integrate with your existing
software.
Many years ago, text editors had either no searching capabilities or a straight
word search only. You would type a word into a dialog box and the pro-
gram would search for that word, moving to its first location in the docu-
ment. If you were lucky, there was a command to search again, instead of
starting the process over. Then one day Emacs introduced a new kind of
searching. The program would search as you typed in each character, updat-
ing the cursor with each keystroke. To search again, you only had to hit the
Return key. If you wanted a less specific search, you could just hit the Back-
space key and remove letters. Everything updated in real time. Incremental
searching was born.
Most GUI toolkits—Java Swing included—do not provide incremental
search. Java does, however, give you the tools to build your own incremen-
tal search. The 1.4 release of Java finally added a long requested feature:
regular expressions. These are complex but concise patterns that are inter-
nally compiled into searching and matching code. With a single regular
expression (known more commonly as a regex) you could match email
addresses, split a complex data field, parse SQL expressions, or recognize

Get Swing Hacks now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.