简体   繁体   中英

Update my textField every 5 seconds

I'm just starting with Java and I need help please, I want to update my JtextField every 5 seconds, I searched something and I tried with thread.sleep(5000) but its not working (and i don't know why). Here is the code of my JtextField :

    textField_1 = new JTextField();
    textField_1.setText("0656");
    textField_1.setFont(new Font("Verdana", Font.PLAIN, 80));
    textField_1.setToolTipText("");
    textField_1.setHorizontalAlignment(SwingConstants.CENTER);
    textField_1.setBounds(212, 120, 600, 150);
    frame.getContentPane().add(textField_1);
    textField_1.setColumns(10);

The easiest way to achieve this is using class Timer.

    Timer t = new Timer();
    t.schedule(new TimerTask() {
        @Override public void run() {
              // textField_t.setText(YOUR TEXT); 
        }
    }, 0L, 5000L);

Use Swing Timer component for repetitive tasks with Swing GUI toolkit:

ActionListener task = new ActionListener() {
            public void actionPerformed(ActionEvent evt) {
                // Do stuff
            }
};
Timer timer = new Timer(100 ,task); // Execute task each 100 miliseconds
timer.setRepeats(true);
timer.start();

Just remember that the 5000 is 5000 milliseconds and 1000 milliseconds is equal to 1 second.

 `javax.swing.Timer

  final Timer updater = new Timer(5000, new ActionListener() {
  public void actionPerformed(ActionEvent e) 
  {
  // update JTextField
  }
  });
  JButton button = new JButton("Start");
  button.addActionListener(new ActionListener() {

  public void actionPerformed(ActionEvent e) {
  updater.start();
  }
  });`

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