
466
|
Chapter 12, Miscellany
#93 Code Models That Don’t Block
HACK
Models Aren’t Always Dumb
Adapt Example 12-8 to create AWTBlockModels.java. To illustrate the load-
ing, this hack has a
JProgressBar that you need to declare before the con-
structor, and which you add at the bottom of
initMainLayout( )
:
progressBar = new JProgressBar (0, 100);
getContentPane( ).add (progressBar, BorderLayout.SOUTH);
The strategy in this hack is to make the JTextArea’s model responsible for its
own threaded loading, so get rid of the
loadURL( ) method. That code will
move to the models, which subclass
javax.swing.text.PlainDocument. First,
change the actions to use these documents:
class BlockingLoadAction extends AbstractAction {
public void actionPerformed (ActionEvent e) {
BlockingURLDocument bud =
new BlockingURLDocument (urlField.getText( ));
progressBar.setEnabled (true);
progressBar.setValue (0);
contentArea.setDocument (bud);
progressBar.setValue (100);
}
}
class NonBlockingLoadAction extends AbstractAction {
public void actionPerformed (ActionEvent e) {
NonBlockingURLDocument nbud =
new NonBlockingURLDocument (urlField.getText( ));
contentArea.setDocument (nbud);
// makeProgressBarUpdaterFor (nbud);
}
}
The actions are pretty much the same, except for the fact that the blocking
version sets the
JProgressBar before and after setting the JTextArea’s docu-
ment. Why doesn’t the non-blocking action touch the progress ...