Soujanya
Soujanya

Reputation: 59

Pausing Swingworker

I hava a GUI that has a button that need to be pressed periodically in the sense it should pause in between. But i am not able to do that. I have tried with Thread.sleep(). Below is the code.

protected Object doInBackground() throws Exception {

            while(true){
                 btnSend.doClick();
                  try { 
                    Thread.sleep(2000);
                    continue;
                } catch (InterruptedException e1) {

                }
              }

    return null;
}

Can anyone tell me where i am going wrong and how to solve it?

Upvotes: 0

Views: 126

Answers (1)

Hovercraft Full Of Eels
Hovercraft Full Of Eels

Reputation: 285402

You shouldn't use a SwingWorker for this since you should not call doClick() off the event thread. If al you want to do is make this call intermittently, then simply use a Swing Timer for calls that need to be done intermittently and on the event thread.

int timerDelay = 2000;

new Timer(timerDelay, new ActionListener() {
  public void actionPerformed(ActionEvent evt) {
    btnSend.doClick();
  }
}).start();

Edit
You ask in comment:

But i need to update another UI on that button click event. If i dont use swingworker the other UI will freeze. I have to use swingworker. Is it possible to do so?

You've got it wrong, I fear. The button click and GUI code should all be on the EDT. Any background non-GUI code that is generated by the button click's ActionListener should be done in a SwingWorker but not the click itself.

e.g.,

elsewhere

btnSend.addActionListener(new ActionListener() {
  public void actionPerformed(ActionEvent evt) {
    new SwingWorker<Void, Void>() {
      public Void doInBackground() throws Exception {
        //.....
        return null;
      }
    }
  }
});

If you need more specific advice regarding your situation, then you'll want to consider creating and posting a Minimal, Complete, and Verifiable Example Program where you condense your code into the smallest bit that still compiles and runs, has no outside dependencies (such as need to link to a database or images), has no extra code that's not relevant to your problem, but still demonstrates your problem.

Upvotes: 4

Related Questions