Reputation: 1486
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
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:
ExecutorService
and its friends will make it relatively easy to let long-running or blocking stuff run on a background threadEventQueue.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
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