Answered step by step
Verified Expert Solution
Link Copied!

Question

1 Approved Answer

I need help to complete public Timer(JButton b) and public void run() method of Timer.java. The time has to display as 00:00:00. Thank you!!! Timer.java

I need help to complete public Timer(JButton b) and public void run() method of Timer.java. The time has to display as 00:00:00. Thank you!!!

Timer.java

import javax.swing.*; public class Timer extends Thread{ //??what do you want me to do? int task=0; //1-start, 2-pause 3-resume, 0-reset private JButton btn0; long tmp=0; //modify the variable and may need to add more for easy update

public Timer(JButton b){ btn0=b; } public void run(){ while(true){ switch(task){ case 1: tmp++; btn0.setText(""+tmp); break; } try{ sleep(10);}catch(Exception e){} } } public void startTimer(){ task=1; } public void resumeTimer(){ task=3; } public void resetTimer(){ task=0; } public void pauseTimer(){ task=2; } }

StopWatch.java

import java.awt.*; import java.awt.event.*; import javax.swing.*; import javax.swing.event.*; //this is is DONE! public class StopWatch extends JFrame implements ActionListener{ private final LayoutManager layout;

private JButton btn0; private JButton btn1; private JButton btn2; Timer p; public StopWatch(){ super("Add your title here"); layout = new FlowLayout(0); setLayout(layout); btn0 = new JButton("00:00:00"); btn1 = new JButton("Start"); btn2 = new JButton("Reset"); add(btn0); add(btn1); add(btn2); btn0.addActionListener(this); btn1.addActionListener(this); btn2.addActionListener(this); p=new Timer(btn0); p.start(); }

public void actionPerformed(ActionEvent event){ //event.getActionCommand() returns the lable on the button //event.getSource() returns the button object //See sample code below String label=event.getActionCommand(); switch(label){ case "Start": startTimer(); btn1.setText("Pause"); break; case "Pause": pauseTimer(); btn1.setText("Resume"); break; case "Resume": resumeTimer(); btn1.setText("Pause"); break; case "Reset": resetTimer(); btn1.setText("Start"); break; } } private void startTimer(){ p.startTimer(); } private void pauseTimer(){ p.pauseTimer(); } private void resumeTimer(){ p.resumeTimer(); } private void resetTimer(){ p.resetTimer(); } public static void main(String[] args){ StopWatch stopWatch = new StopWatch(); stopWatch.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); stopWatch.setSize(450, 350); stopWatch.setVisible(true); }

}

Step by Step Solution

There are 3 Steps involved in it

Step: 1

blur-text-image

Get Instant Access with AI-Powered Solutions

See step-by-step solutions with expert insights and AI powered tools for academic success

Step: 2

blur-text-image

Step: 3

blur-text-image

Ace Your Homework with AI

Get the answers you need in no time with our AI-driven, step-by-step assistance

Get Started

Students also viewed these Databases questions