Isha
Isha

Reputation: 27

JTextfield looping text issue

I have created a GUI using swings package containing a button and a text field, and have also added event handling on button such that when it gets clicked, the textfield should display a message continuously for 5 times as it is in loop.

public void actionPerformed(ActionEvent ae){
for(int i=0;i<5;i++){
tx.setText("Running"+i);// here tx is the JTextField object
}

Upvotes: 0

Views: 90

Answers (2)

Iamat8
Iamat8

Reputation: 3906

Use Runnable and put thread inside it..

Runnable run = new Runnable() {
      @Override
        public void run() {
            for(int i=0 ; i<5;i++){
                try {
                    Thread.sleep(1000);                        //time to wait
                    jTextField_Cost.setText("Running"+i+"");
                }catch(InterruptedException e1){
                    e1.printStackTrace();
                }
            }
        }
};
ExecutorService _ex = Executors.newCachedThreadPool();
_ex.execute(run);

You can also use

new Thread(run).start();

But ExecutorService is useful when we are using large number of thread in program.. have a look at this post

Upvotes: 0

TomN
TomN

Reputation: 584

if you wish to show it as an animation, you have to do it at background or another thread.

here is a sample

private Task task;
private void ButtonActionPerformed(java.awt.event.ActionEvent evt)
{                                       
    task = new Task();        
    setCursor(Cursor.getPredefinedCursor(Cursor.WAIT_CURSOR));
    task.execute();
}                                      

class Task extends SwingWorker<Void, Void> 
{
    @Override
    public Void doInBackground() throws Exception 
    {
        for(int i=0;i<5;i++)
        {
            Lab.setText("Running"+i);
            Thread.sleep(200);
        }
        return null;
    }
}

Upvotes: 1

Related Questions