这太可怕了,它更容易工作,我认为它应该......
基本上,您需要某种“ticker”来更新标签的文本......
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 毫秒左右打勾的 a (捕捉边缘情况)。
通过虚拟设置标签的文本,它会自动发布重绘请求,这让我们的生活变得简单......