1

Simply, I have two classes, A GUI class which has a button both for stopping and running the other class/thread which is for getting the text content from clipboard and paste it to a text file. But no matter what I tried (such as using swingworker) I couldn't achive my goal. That code can start the thread but freezes the GUI. I tried using SwingWorker, but failed. Please show me a solution.

class GUI
{
  Thread a = null;

  JButton onOffButton;
  onOffButt.addActionListener(new ActionListener()
  {
        @Override
        public void actionPerformed(ActionEvent arg0)
        {
            if (a == null)
            {
                isOn = true;
                onOffButt.setText("on");
                onOffButt.setBackground(Color.green);

                a = new Thread(new TextHandler());
                a.start();
            }
            else    
            {
                isOn = false;
                onOffButt.setText("off");
                onOffButt.setBackground(Color.red);

                a.interrupt();
                a = null;
            }
        }
    });
}


class TextHandler() extends Thread
{
   run()
    {
      for(;;)
      {
        // getClipboardContent();
        // evaluate
        // paste
      }
   }
}
David Conrad
  • 15,432
  • 2
  • 42
  • 54

1 Answers1

1

Where in your TextHandler do you do anything, like sleeping, that would catch an InterruptedException? If you don't do that, the interrupt bit will be raised but you'll never see it. If you aren't otherwise doing anything that would notice that the thread has been interrupted, you can add this to your loop:

for(;;)
{
    // getClipboardContent();
    // evaluate
    // paste
    if (Thread.currentThread().interrupted())
    {
        break;
    }
}
David Conrad
  • 15,432
  • 2
  • 42
  • 54
  • I tried your suggestion however, it still gives the same error. java.lang.InterruptedException: sleep interrupted at java.lang.Thread.sleep(Native Method) at TextHandler.run(TextHandler.java:85) at java.lang.Thread.run(Unknown Source) – user3868427 Jul 28 '14 at 19:59
  • it is supposed to give an interrupt exception because thats what u r doin: u r interrupting the thred – eldjon Jul 28 '14 at 20:04
  • I see. but it isn't helping. – user3868427 Jul 28 '14 at 20:05
  • So, if you already have a `sleep` and it's throwing an `InterruptedException`, why don't you just catch the exception and break the loop? – David Conrad Jul 28 '14 at 23:24