Search code examples
javadatejtextfield

How to update this textField with the Date every second


I've get the Date, but it's static i want to get the actual date every second. How can I do it?

    Date fecha=new java.util.Date();
    textField = new JTextField(fecha.toLocaleString());
    textField.setFont(new Font("Verdana", Font.BOLD, 15));
    textField.setHorizontalAlignment(SwingConstants.CENTER);
    textField.setBackground(UIManager.getColor("Button.background"));
    textField.setBounds(362, 665, 300, 50);
    frame.getContentPane().add(textField);
    textField.setColumns(10);

Solution

  • javax.swing.Timer - Fires one or more ActionEvents at specified intervals

    refer java doc

    int delay = 1000; //milliseconds
      ActionListener taskPerformer = new ActionListener() {
          public void actionPerformed(ActionEvent evt) {
              //...Perform a task...
          }
      };
      new Timer(delay, taskPerformer).start();
    

    Edit : If you need both timers in your code don't import both.import one timer.and for other timer use explicitly.import only util.timer an for swing timer use new javax.swing.Timer(delay, taskPerformer).start()