Knowee
Questions
Features
Study Tools

Develop a Java program that creates a GUI application for a stopwatch usingSwing. The stopwatch should have start, stop, and reset buttons, and displaythe elapsed time.

Question

Develop a Java program that creates a GUI application for a stopwatch usingSwing. The stopwatch should have start, stop, and reset buttons, and displaythe elapsed time.

🧐 Not the exact question you are looking for?Go ask a question

Solution

Sure, here is a simple implementation of a stopwatch using Java Swing:

import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

public class Stopwatch extends JFrame {
    private long startTime = -1;
    private long duration = 0;

    private final JLabel timeLabel = new JLabel();
    private final JButton startButton = new JButton("Start");
    private final JButton stopButton = new JButton("Stop");
    private final JButton resetButton = new JButton("Reset");

    public Stopwatch() {
        super("Stopwatch");
        setSize(300, 200);
        setDefaultCloseOperation(EXIT_ON_CLOSE);

        timeLabel.setFont(timeLabel.getFont().deriveFont(40f));
        updateDisplay();

        startButton.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                startTime = System.currentTimeMillis();
                updateDisplay();
            }
        });

        stopButton.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                duration += System.currentTimeMillis() - startTime;
                startTime = -1;
                updateDisplay();
            }
        });

        resetButton.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                startTime = -1;
                duration = 0;
                updateDisplay();
            }
        });

        JPanel contentPane = (JPanel) getContentPane();
        contentPane.setLayout(new GridLayout(2, 2, 5, 5));
        contentPane.add(timeLabel);
        contentPane.add(startButton);
        contentPane.add(stopButton);
        contentPane.add(resetButton);
    }

    private void updateDisplay() {
        String display;
        if (startTime < 0) {
            // stopwatch is stopped
            display = formatTime(duration);
        } else {
            // stopwatch is running
            long now = System.currentTimeMillis();
            long clockTime = now - startTime + duration;
            display = formatTime(clockTime);
        }
        timeLabel.setText(display);
    }

    private String formatTime(long millis) {
        int seconds = (int) (millis / 1000);
        int minutes = seconds / 60;
        int hours = minutes / 60;
        return String.format("%02d:%02d:%02d", hours, minutes % 60, seconds % 60);
    }

    public static void main(String[] args) {
        SwingUtilities.invokeLater(new Runnable() {
            public void run() {
                new Stopwatch().setVisible(true);
            }
        });
    }
}

This program creates a simple stopwatch with start, stop, and reset buttons. The elapsed time is displayed in the format "HH:MM:SS". The startButton starts the stopwatch, the stopButton stops the stopwatch, and the resetButton resets the stopwatch. The updateDisplay method updates the time displayed on the stopwatch. The formatTime method formats the time in milliseconds to the "HH:MM:SS" format.

This problem has been solved

Similar Questions

Develop a simple java program to start a thread, put the thread to sleep andto resume the thread.

Develop a Java program that creates a GUI application with a button. Whenthe button is clicked, it should change the text of a label.

evelop a Java program that simulates a simple countdown timer usingmultithreading. The program should allow users to start multiple timersconcurrently, each running independently and provide its sample input,output

Create a Time class and initialize it with hours and minutes.1. Make a method addTime which should take two time object and add them. E.g.- (2 hour and 50 min)+(1 hr and 20 min) is (4 hr and 10 min)2. Make a method displayTime which should print the time.3. Make a method DisplayMinute which should display the total minutes in the Time. E.g.- (1 hr 2 min) should display 62 minute.

Se quiere implementar un monitor Java que proporcione la funcionalidad básica del CountDownLatch, con los métodos countDown y await.public class MiCountDownLatch { private int n; public MiCountDownLatch(int n0) {  n=n0; } public synchronized void countDown() {   n--;   notifyAll(); } public void await() throws InterruptedException {   while (n > 0) wait(); }}Preguntas 14 de 20 0,5 Puntos. Puntos descontados por fallo: 0.25Esta solución no es correcta porque se pueden producir condiciones de carrera.VerdaderoFalsoBorra selecciónPreguntas 15 de 20 0,5 Puntos. Puntos descontados por fallo: 0.25Con esta solución, como el valor del contador de la barrera podría ser negativo, se podrían quedar hilos suspendidos al hacer await sobre la barrera, aunque la barrera esté ya abierta.VerdaderoFalsoBorra selecciónPreguntas 16 de 20 0,5 Puntos. Puntos descontados por fallo: 0.25Para que esta solución sea correcta hay que sustituir en el método countDown la línea actual de notifyAll() por signalAll().VerdaderoFalso

1/1

Upgrade your grade with Knowee

Get personalized homework help. Review tough concepts in more detail, or go deeper into your topic by exploring other relevant questions.