TThread4.java
Select all
import javax.swing.*; import java.awt.*; import java.awt.event.*; public class TThread4 extends JFrame implements Runnable { Thread ctr = null; JButton btnStart, btnStop; JLabel lblNum; int count = 0; boolean running = false; // override run() to implement Runnable public void run() { while (running && (++count < 100)) { lblNum.setText(Integer.toString(count)); try { Thread.sleep(100); } catch (InterruptedException e) { System.out.println("Application Interrupted"); } } } public static void main(String[] args) { TThread4 app = new TThread4(); app.addWindowListener(new WindowAdapter() { public void windowClosing(WindowEvent e) { System.exit(0); } }); app.init(); app.pack(); app.setVisible(true); } public void init() { Container c = this.getContentPane(); c.setLayout(new GridLayout(3,1)); lblNum = new JLabel("Running Total"); btnStart = new JButton("Start"); btnStop = new JButton("Stop"); btnStop.setEnabled(false); btnStart.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { btnStart.setEnabled(false); btnStop.setEnabled(true); running = true; ctr = new Thread(TThread4.this); ctr.start(); } }); btnStop.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { running = false; btnStart.setEnabled(true); btnStop.setEnabled(false); } }); c.add(lblNum); c.add(btnStart); c.add(btnStop); } }