[英]Updating message in JOptionPane with JSpinner stateChanged method
[英]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.