Code
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class jResponsiveUIwEventDispatcher extends JFrame {
private boolean stop = false;
private JTextField tfCount;
private int countValue = 1;
// Create the GUI and show it. For thread safety, this method should
// be invoked from the event-dispatching thread instead of the main thread
private void createAndShowGUI() {
Container cp = getContentPane();
cp.setLayout(new FlowLayout(FlowLayout.CENTER, 10, 10));
cp.add(new JLabel("Counter"));
tfCount = new JTextField("" + countValue, 10);
tfCount.setEditable(false);
cp.add(tfCount);
JButton btnStart = new JButton("Start Counting");
cp.add(btnStart);
btnStart.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent evt) {
stop = false;
// start a new thread to do the counting
Thread t = new Thread() {
public void run() {
while (!stop) {
tfCount.setText("" + countValue);
countValue++;
// suspend itself and yield control to other threads
try {
sleep(10);
} catch (InterruptedException ex) {}
}
}
};
t.start();
}
});
JButton btnStop = new JButton("Stop Counting");
cp.add(btnStop);
btnStop.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent evt) {
stop = true;
}
});
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setSize(300, 120);
setTitle("Counter");
setVisible(true); // show and realize the window
}
public static void main(String[] args) {
// The main thread schedules a job for the event-dispatching thread to create the GUI
javax.swing.SwingUtilities.invokeLater(new Runnable() {
public void run() {
new jResponsiveUIwEventDispatcher().createAndShowGUI();
}
});
}
}