简体   繁体   中英

How to add Action Listener to this button?

I'm trying to show the actual system time display on a text field when you click the button. So far it it only shows the live result if you click the button each time. I'm struggling to attach the ActionListener in so that the time can continuously update itself.

private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {

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

    dateFormat.format(time);
    ActualTime.setText(dateFormat.format(time)); 

    Calendar cal = Calendar.getInstance();
    ActualTime.setText(dateFormat.format(cal.getTime()));
}                            

Thank you for the edit to your question.

  • To have time continually update itself, use a Swing Timer and have it update the Timer display every xxx msecs, where xxx will depend on just how frequently you'd like the update to occur.
  • The Timer would use an ActionListener just like your JButton currently does.
  • You can start the Timer in a JButton's ActionListener if this is desired, simply by calling start() on the Timer from within the JButton's ActionListener.
  • If this were my code, I'd make my DateFormat object a field and create it only once. The code can be simplified some, I think.
  • Here is a link to the Swing Timer Tutorial .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM