【发布时间】:2014-03-29 22:03:31
【问题描述】:
有没有办法自动更新 JPanel 上的 SimpleDateFormat 数字时钟?
SimpleDateFormat sdf = new SimpleDateFormat("HH:mm");
time.setText(sdf.format(new Date()));
如果我运行它,标签会停留在脚本启动时...
更新
到目前为止我写了什么
import java.awt.*;
import java.awt.image.BufferedImage;
import java.text.SimpleDateFormat;
import java.util.Date;
import javax.swing.*;
public class test {
private JFrame frame = new JFrame("Time");
private JPanel panel = new JPanel();
private JLabel time = new JLabel();
private JButton exit = new JButton("exit");
private boolean exit_bool = false;
public test() {
panel.setLayout(new GridBagLayout());
panel.add(time);
panel.add(exit);
panel.setBorder(BorderFactory.createEmptyBorder(10, 10, 10, 10));
frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
frame.add(panel);
frame.setLocationRelativeTo(null);
init(true, true);
createHandler();
startTime();
}
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
@Override
public void run() {
test viewable = new test();
}
});
}
public void init(boolean fullscreen, boolean mouse) {
frame.setVisible(false);
frame.dispose();
frame.setUndecorated(true);
frame.setVisible(true);
if(fullscreen) {
frame.setExtendedState(frame.MAXIMIZED_BOTH);
}
if(!mouse) {
frame.setCursor(java.awt.Toolkit.getDefaultToolkit().createCustomCursor(new BufferedImage(1,1,BufferedImage.TYPE_4BYTE_ABGR),new java.awt.Point(0,0),"NOCURSOR"));
}
}
public void startTime() {
while(!exit_bool) {
SimpleDateFormat sdf = new SimpleDateFormat("HH:mm");
time.setText(sdf.format(new Date()));
}
}
public void createHandler() {
exit.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
exitActionPerformed(evt);
}
});
}
private void exitActionPerformed(java.awt.event.ActionEvent evt) {
exit_bool = true;
}
}
【问题讨论】:
-
您必须按照您决定的任何时间间隔更新时间。
-
但是怎么做呢?我尝试了一个while循环,但脚本根本无法启动
-
这与
SimpleDateFormat无关。您的问题在于您的 GUI 和/或更新的循环。如果没有更多详细信息,我们将无法提供帮助。 -
我添加了更多信息
标签: java date time clock simpledateformat