繁体   English   中英

在JOptionPane中更新消息

[英]Updating message in JOptionPane

我正在尝试制作一个在JOptionPane中显示时间的数字时钟。 我已设法在消息对话框中显示时间。 但是,我无法弄清楚如何让它在对话框中每秒更新一次。

这就是我目前拥有的:

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

这太可怕了,我觉得它应该更容易......

基本上,您需要某种“自动收报机”,您可以使用它来更新标签的文本......

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

因为我们不想违反Swing的单线程规则,所以最简单的解决方案是使用javax.swing.Timer ,每500毫秒左右(捕获边缘情况)。

通过虚拟设置标签的文本,它会自动发布重绘请求,这使我们的生活变得简单......

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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