1

I created a JFrame with combo boxes and a button which will create a new thread and continue to do an action. I want a new JFrame to start with every new thread to output logs to the new JFrame. But even if I put the code related to the JFrame in the new thread and close that JFrame it ends the whole program instead of that running thread. What the best approach to making what I want possible? I simply want a new JFrame to open with each new thread started and when I close that JFrame it would end that thread.

Regards!

mKorbel
  • 109,525
  • 20
  • 134
  • 319
Arya
  • 8,473
  • 27
  • 105
  • 175

2 Answers2

6

By default, closing a JFrame will simply hide it (see the documentation for setDefaultCloseOperation()). If closing a window is exiting your application, this must be due to your own code. You're not, by chance, calling setDefaultCloseOperation(JFrame. EXIT_ON_CLOSE), are you?

Ernest Friedman-Hill
  • 80,601
  • 10
  • 150
  • 186
  • yes I have setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE) I thought it would end the thread it runs in but it ended the whole program. – Arya Jun 09 '12 at 03:40
  • 1
    @Arya -- OK, well, don't do that! Instead, add a `WindowListener` to each `JFrame`, and in the `windowClosing()` method, stop the corresponding `Thread`. – Ernest Friedman-Hill Jun 09 '12 at 03:55
4

Here are some ideas:

  • Don't block the event dispatch thread; use SwingWorker instead, as shown here.

  • Don't use multiple frames; use panels in a container having a suitable layout.

Community
  • 1
  • 1
trashgod
  • 203,806
  • 29
  • 246
  • 1,045
  • 1
    "Don't block the event dispatch thread" thats not just an idea, thats something that is mandatory for Swing to function properly :-). There is only one Thread (the EDT) which does the actual UI rendering (ie. painting in Swing) and event handling. Best case scenario is that the EDT delegates all non UI work to worker threads. The model (ie. backend) of your UI however can consist of thousands of separate threads all making updates and processing UI events and then scheduling the result to be rendered by the EDT via a SwingWorker. – Jasper Siepkes Jun 09 '12 at 13:12