Saad Attieh
Saad Attieh

Reputation: 1486

prevent GUI from freezing and have button to cancel operation/kill thread

Here is what I am trying to do:

I have a JFrame containing a JTextArea displaying updates on an on going connection. The user is supposed to be able to press the JButton to the right of it if they want to cancel the connection. However, since the connection is blocking (using) the thread while trying to connect, the GUI becomes frozen. I am looking for a quick fix. Having the ActionListener on a separate thread possibly? I do not have much experience with threads though I can make basic use of runnables.

Does the answer have something to do with using the EDT? If so how should this be implemented?

PS for clarification, the button should be able to kill a thread creating the connection. After reading it seems that an executorService. could help with this? Yes? or not at all?

Upvotes: 0

Views: 1293

Answers (2)

Daniel Schneller
Daniel Schneller

Reputation: 13936

It would be advisable to first get up to speed regarding Swing (or virtually any UI framework) and multi-threading. This is the napkin version:

  • Any modifications to the UI or reads from it (e. g. to get the value of a textfield) must be done only on the UI thread (which is also sometimes called the "Swing Thread" or "Event Dispatch Thread" (EDT)
  • Any blocking or long-running operations - like network communications - must NOT be run on the UI thread. Otherwise they will prevent buttons from working, texts from being updated etc.
  • In Java, the ExecutorService and its friends will make it relatively easy to let long-running or blocking stuff run on a background thread
  • If something happens on the background thread that requires you to update the UI, encapsulate the UI-related code in an EventQueue.invokeLater call. This will make sure the Runnable you pass gets executed on the UI thread.

The SwingWorker class encapsulates this logic and provides an easy to use helper for simpler cases.

When doing this the first time, it can be a bit daunting, but it pays off to understand this thoroughly, because it does not only apply to Swing, but to any other UI code, too.

Upvotes: 5

mKorbel
mKorbel

Reputation: 109823

for clarification, the button should be able to kill a thread creating the connection. After reading it seems that an executorService. could help with this? Yes? or not at all?

yes

  • while(localBooleanVariable) inside Runnable#Thread, plain Thread

  • by using SwingWorker.cancel()

  • easiest could be SwingWorker, because is cancelable and output from publish(), progress() is on EDT

Upvotes: 1

Related Questions