简体   繁体   中英

Updating message in JOptionPane

I am trying to make a digital clock which displays the time in a JOptionPane. I've managed to display the time on the message dialog box. However, I can't figure out how to make it update the time at every second in the dialog box.

This is what I currently have:

    Date now = Calendar.getInstance().getTime();
    DateFormat time = new SimpleDateFormat("hh:mm:ss a.");

    String s = time.format(now);

    JLabel label = new JLabel(s, JLabel.CENTER);
    label.setFont(new Font("DigifaceWide Regular", Font.PLAIN, 20));

    Toolkit.getDefaultToolkit().beep();

    int choice = JOptionPane.showConfirmDialog(null, label, "Alarm Clock", JOptionPane.YES_NO_OPTION, JOptionPane.PLAIN_MESSAGE);

That was scary, it worked easier that I thought it should...

Basically, you need some kind of "ticker" that you can use to update the text of the label...

public class OptionClock {

    public static void main(String[] args) {
        new OptionClock();
    }

    public OptionClock() {
        EventQueue.invokeLater(new Runnable() {
            @Override
            public void run() {
                try {
                    UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
                } catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
                }

                Date now = Calendar.getInstance().getTime();
                final DateFormat time = new SimpleDateFormat("hh:mm:ss a.");

                String s = time.format(now);

                final JLabel label = new JLabel(s, JLabel.CENTER);
                label.setFont(new Font("DigifaceWide Regular", Font.PLAIN, 20));

                Timer t = new Timer(500, new ActionListener() {
                    @Override
                    public void actionPerformed(ActionEvent e) {
                        Date now = Calendar.getInstance().getTime();
                        label.setText(time.format(now));
                    }
                });
                t.setRepeats(true);
                t.start();

                int choice = JOptionPane.showConfirmDialog(null, label, "Alarm Clock", JOptionPane.YES_NO_OPTION, JOptionPane.PLAIN_MESSAGE);

                t.stop();
            }
        });
    }
}

Because we don't want to violate the single thread rules of Swing, the simplest solution would be to use a javax.swing.Timer that ticks every 500 milliseconds or so (catch edge cases).

By virtual of setting the label's text, it automatically posts a repaint request, which makes our life simple...

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