简体   繁体   中英

Auto Updating Timer in JOptionPane in Java

I have searched but I cannot find anything specifically for what I need. I am making a timer, and I am a beginner at Java. I have made the timer and it works, but I would like a window saying the time remaining. Here is what I have:

    package simpletimer;
import javax.swing.JOptionPane;
public class SimpleTimer {
    public static void main(String[] args) throws InterruptedException {
        JOptionPane.showMessageDialog(null, "Simple Timer By - -","Simple Timer", JOptionPane.INFORMATION_MESSAGE);
        double h = Integer.parseInt(JOptionPane.showInputDialog(null,"Hours:","Simple Timer",JOptionPane.PLAIN_MESSAGE));
        double m = Integer.parseInt(JOptionPane.showInputDialog(null,"Minutes:","Simple Timer",JOptionPane.PLAIN_MESSAGE));
        double s = Integer.parseInt(JOptionPane.showInputDialog(null,"Seconds:","Simple Timer",JOptionPane.PLAIN_MESSAGE));
        String Time = "Ok! The Simple Timer will go off in " + h + "h " + m + "m " + s + "s.";
        String[] Option1 = {"Start Timer"};
        JOptionPane.showOptionDialog(null, Time,"Simple Timer",JOptionPane.DEFAULT_OPTION,JOptionPane.INFORMATION_MESSAGE,null,Option1,"Start Timer");
        while(s > 0){
            Thread.sleep(1000);
            s = s - 1;
        }
        while(m > 0){
            m = m - 1;
            s = s + 59;
            Thread.sleep(60000);
        }
        while(h > 0){
            h = h - 1;
            m = m + 59;
            s = s + 59;
            Thread.sleep(3600000);
        }
        do{
                    JOptionPane.showMessageDialog(null, "Simple Timer Done!", "Simple Timer", JOptionPane.INFORMATION_MESSAGE);
        }while(h < 1 && m < 1 && s < 1);
    }
}

I solved my own question. I did this by using JFrame. Here is a sample:

JFrame Main = new JFrame();
    JLabel Label = new JLabel();
    Main.add(Label);
    Main.setVisible(true);
    Main.setResizable(false);
    Main.setBounds(0, 0, 480, 200);
    Main.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    Label.setText("Time Left: " + h + ":" + m + ":" + s + ".");
    Label.setFont(Label.getFont().deriveFont(48f));
    while(s > 0){
        s = (short) (s - 1);
        Label.setText("Time Left: " + h + ":" + m + ":" + s + ".");
        Thread.sleep(1000);
    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM