Java Reference
In-Depth Information
148
if ( arg == "Copy" )
149
{
150
Clipboard cb = Toolkit .getDefaultToolkit () .getSystemClipboard () ;
151
StringSelection contents = new StringSelection ( lcd.getText ()) ;
152
cb.setContents ( contents, null ) ;
153
}
154
155
if ( arg == "Paste" )
156
{
157
Clipboard cb = Toolkit .getDefaultToolkit () .getSystemClipboard () ;
158
Transferable content = cb.getContents ( this ) ;
159
try
160
{
161
String s = ( String ) content.getTransferData ( DataFlavor .stringFlavor ) ;
162
lcd.setText ( calcPattern.format ( Double .parseDouble ( s ))) ;
163
}
164
catch ( Throwable exc )
165
{
166
lcd.setText ( "" ) ;
167
}
168
}
169
FIGURE 6-24
In line 151, the text from the lcd TextField is selected and stored in a variable
named contents. Line 152 then sends contents to cb with the setContents()
method.
Line 155 compares the ActionCommand stored in the variable, arg, with the
word, Paste. If a match is found, the code in lines 157 through 167 executes. In
line 157, getSystemClipboard() again is used to name the current clipboard, cb. It
is important to assign a name each time the clipboard is implemented because its
value may have changed. In line 158, the contents of the clipboard are transferred
to the buffer. This two-step approach of transferring data to the buffer and then
to the String variable is necessary because the data may or may not contain val-
ues capable of being pasted. Within the try block that begins in line 159, the data
is transferred from the buffer to a String variable; then, in line 162, it is parsed,
formatted, and sent to the lcd TextField. By including those lines in a try state-
ment, the program will continue rather than abort prematurely if the data is a
stream of characters and not numeric. Indeed, in line 166, if an error has been
thrown, the lcd TextField is set to a null string, so no data is pasted.
The following step enters the code to determine if the user clicked the Copy
or Paste commands on the Edit menu.
To Enter Code to Search for the Copy and Paste Commands
1. Enter lines 148 through 169 as shown in Figure 6-24.
The TextPad window displays the if statements to determine which menu
command the user clicked (Figure 6-25). If the user clicked the Copy com-
mand, the program will transfer the selected data to the system clipboard; if
the user clicked the Paste command, the program will transfer the data from
the system clipboard to the TextField.
Search WWH ::




Custom Search