que1326
que1326

Reputation: 2325

How to call a method on a period of time in swing?

I have a frame with a JTextField and a JButton. When I press I want to call a method that updates the JTextField`s text at every 4/5/8 seconds. Could anyone help me with the code ?? (thank you)

The code:    

import javax.swing.*;
public class Gui{
JFrame frame = new JFrame();
public Gui(){

frame.setLayout(new FlowLayout());

JTextField tf = new JTextField(10);
JButton    bu = new JButton("Button");

  bu.addActionListener(new ActionListener(){

        public void actionPerformed(ActionEvent event){

               for(int i=0;;i++){
               tf.setText("" + i);
               }
        }
  });
}
}

Upvotes: 0

Views: 180

Answers (2)

MadProgrammer
MadProgrammer

Reputation: 347234

Personally, as @trashgod has pointed out, I'd be using the java.swing.Timer, the main reason is that it supports calling notifications within the EDT, as well as some (generally minor) management methods to help make life easier

Upvotes: 3

BaL
BaL

Reputation: 93

You could try to use timers : http://docs.oracle.com/javase/7/docs/api/java/util/Timer.html

You might want to start the timer when the actionPerformed method is called.

Though BEST bet with Swing, is the use of javax.swing.Timer, as it allows you to update your GUI on the Event Dispatch Thread.

Upvotes: 1

Related Questions