在Java中的JOptionPane中自动更新计时器

时间:2015-05-21 01:08:06

标签: java timer joptionpane

我已经搜索过,但我找不到任何具体的东西。我正在制作一个计时器,我是Java的初学者。我已经制作了计时器并且它可以工作,但我想要一个窗口说明剩下的时间。 这就是我所拥有的:

    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);
    }
}

1 个答案:

答案 0 :(得分:0)

我解决了自己的问题。我是通过使用JFrame完成的。这是一个示例:

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);
    }