Java display current time

前端 未结 6 1948
一向
一向 2021-01-02 02:05

I have a code which shows me the current date and time when I run my application

DateFormat dateFormat = new SimpleDateFormat(\"yyyy/MM/dd HH:mm:ss\");
Calen         


        
6条回答
  •  滥情空心
    2021-01-02 02:50

    How about using a timer, such as javax.swing.Timer? (Do not make mistake in the import, there are more Timer classes.)

    public static void main(String... args) throws InterruptedException {
        final DateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
        int interval = 1000; // 1000 ms
    
        new Timer(interval, new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                Calendar now = Calendar.getInstance();
                System.out.println(dateFormat.format(now.getTime()));
            }
        }).start();
    
        Thread.currentThread().join();
    }
    

    This will simply execute the body of the ActionListener every second, printing the current time.

    The Thread.join call on the last line is not universally necessary, it's just needed for this example piece of code to run until the process is manually stopped. Otherwise, it would immediately stop.

    In a real application, in case it's a Swing app, then the timer should handle threading by itself, so you won't have to worry about it.


    Edit

    Integrating the above sample into your application is fairly simple, just add it into the initGUI method and instead of printing the current time to System.out set change the text of the given label:

    public void initGUI() {
        setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);        
        setPreferredSize(new Dimension(800, 600));
        setLayout(null);
    
        Calendar now = Calendar.getInstance();
        tijd = new JLabel(dateFormat.format(now.getTime()));
        tijd.setBounds(100, 100, 125, 125);
        window.add(tijd);
    
        new Timer(1000, new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                Calendar now = Calendar.getInstance();
                tijd.setText(dateFormat.format(now.getTime()));
            }
        }).start();
    
        pack();
    }
    

提交回复
热议问题