Updating message in JOptionPane

泄露秘密 提交于 2019-12-23 19:39:51

问题


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

回答1:


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...



来源:https://stackoverflow.com/questions/15104259/updating-message-in-joptionpane

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!