0

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
}
SatyaTNV
  • 4,137
  • 3
  • 15
  • 31
Isha
  • 27
  • 1
  • 6
  • this code is not giving the desired output as per the problem statement described above – Isha Jan 28 '16 at 05:38

2 Answers2

1

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;
    }
}
TomN
  • 574
  • 3
  • 18
  • 1
    Swing components need to be updated on the Event Dispatch Thread. You should NOT be updating the text in the doInBackground() method because that code does not run on the EDT. You need to either wrap that code in a SwingUtilities.invokeLater(...) or "publish" the text you want to display and then update the text in the "process" method of the SwingWorker. Read the section from the Swing tutorial on [Concurrency](http://docs.oracle.com/javase/tutorial/uiswing/concurrency/index.html) for more information and SwingWorker examples. – camickr Jan 28 '16 at 16:02
0

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

Community
  • 1
  • 1
Iamat8
  • 3,888
  • 9
  • 25
  • 35