在JOptionPane中更新消息 [英] Updating message in JOptionPane
问题描述
我正在尝试制作一个在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.
这是我目前拥有的:
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...
基本上,您需要某种"ticker",可用于更新标签的文本...
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();
}
});
}
}
因为我们不想违反Swing的单线程规则,所以最简单的解决方案是使用每500毫秒左右跳动一次的javax.swing.Timer
(捕获边缘情况).
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...
这篇关于在JOptionPane中更新消息的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!