img
. .
public class ThreadButtonListener implements ActionListener
{
public void actionPerformed(ActionEvent event) {
ThreadedJButton currentButton =
(ThreadedJButton)event.getSource();
System.out.println("Pressed " + currentButton);
ThreadedSwing.useThreads = !ThreadedSwing.useThreads;
if (ThreadedSwing.useThreads)
currentButton.setText("Threaded");
else
currentButton.setText("Non-Threaded");
}
}
//
ThreadedSwing/ThreadedJButton.java
/*
Once upon a time this was an interesting class.
Now it
provides a nice print string.
*/
import
java.applet.*;
import
java.awt.*;
import
com.sun.java.swing.*;
import
Extensions.*;
public class ThreadedJButton extends JButton {
public ThreadedJButton(String s) {
super(s);
}
public String toString() {
return("ThreadedJButton_" + getText());
}
}
In a "normal" windowing application, when a button is pressed, some task is executed and then
control in the program is returned to the window. This is fine if the time required to execute the
task is minimal. If the time required for the task is not minimal, the window freezes or the clock
icon is displayed while the task is executing. This behavior is not desirable in most cases, because
the graphical interface should always be active for the user to select other actions.
This example demonstrates how we can get around the freezing problem. A simple window is
created and filled with pushbutton widgets. When a button is pushed, the program simulates some
processing [i.e., sleep(6000)] that would normally cause the interface to freeze. In this
example the work is performed in separate threads. This way, when a button is pressed, a thread is
created to do the work, and the window can return to its event processing for the user (Figure 17-
1).
Figure 17-1. ThreadedSwing Window Example
Search WWH :
Custom Search
Previous Page
Multithreaded Programming with JAVA - Topic Index
Next Page
Multithreaded Programming with JAVA - Bookmarks
Home