Java Reference
In-Depth Information
first task of the search() method, in lines 289 through 293, is to clear the
JTextPane and display the headings as it did in the addTextToTextPane() method.
285
public void search ( String searchField, String searchArray [])
286
{
287
try
288
{
289
Document doc = textPane.getDocument () ; //assign text to document object
290
doc.remove ( 0,doc.getLength ()) ; //clear previous text
291
292
//display column titles
293
doc.insertString ( 0, "TITLE\tSTUDIO\tYEAR\n" ,textPane.getStyle ( "large" )) ;
294
295
//prompt user for search data
296
String search = JOptionPane.showInputDialog ( null , "Please enter the " +
searchField ) ;
297
boolean found = false ;
298
299
//search arrays
300
for ( int i = 0; i<title.length; i++ )
301
{
302
if ( search.compareTo ( searchArray [ i ]) ==0 )
303
{
304
doc.insertString ( doc.getLength () , title [ i ] + "\t" ,
textPane.getStyle ( "bold" )) ;
305
doc.insertString ( doc.getLength () , studio [ i ]
+ "\t" , textPane.getStyle ( "italic" )) ;
306
doc.insertString ( doc.getLength () , year [ i ] + "\n" ,
textPane.getStyle ( "regular" )) ;
found = true ;
307
308
}
309
}
310
if ( found == false )
311
{
312
JOptionPane.showMessageDialog ( null , "Your search produced no results." ,
"No results found" ,JOptionPane.INFORMATION_MESSAGE ) ;
313
sort ( title ) ;
314
}
315
}
316
catch ( BadLocationException ble )
317
{
318
System .err.println ( "Couldn't insert text." ) ;
319
}
320
}
321
FIGURE 7-34
Line 296 displays a JOptionPane input dialog box, which asks the user to
enter the search argument for the passed search field. A boolean flag named
found is set to false. The for() loop that begins in line 300 continues through the
entire array. Line 302 uses the compareTo() method to compare the search data
with the array member. If the method returns a 0, a match is found and inserted
in the Document, the flag is set to true (line 307), and the for() loop continues
evaluating the remaining elements in the array.
If the flag is not set to true, then a match was not found. Line 312 then dis-
plays a message dialog box, and the data displays sorted again, by title, in line
313. The code involved in inserting new information in the JTextPane Document
is placed inside a try block, as it was in the addTextToTextPane() method.
Search WWH ::




Custom Search