开发者

How to keep one thread to call multiple JForms?

开发者 https://www.devze.com 2023-04-11 19:51 出处:网络
Let\'s say I have one thread running (I\'m creating many instances of this thread), and inside that I instantiate a JForm. While being inside that JForm, I call another JForm. Think of it as a multipl

Let's say I have one thread running (I'm creating many instances of this thread), and inside that I instantiate a JForm. While being inside that JForm, I call another JForm. Think of it as a multiple step registration process. When I'm inside the second form, will the previously created thread still be inside the run()? Or is the new JForm creating a new thread? I want to keep the first thread alive and access a shared resource through out the lifetime of it.

class Form1 ex开发者_如何学编程tends JForm{
   public void jButton1ActionPerformed(..){
      ///show Form2
   }
}
class A extends Thread{
  public void run() {
     //show Form1
  }
}

class Main {
 public static void main(String args[]){
    new A().start();
    new A().start();
    new A().start();
}

Thanks.


When you create and run your A thread, you will simply show the Form and continue executing that Thread. Separately, on the single, dedicated Swing Thread (started automatically for you) the users click will be caught and handled, resulting in a call to jButton1ActionPerformed. That code block will execute inside the Swing thread.

Hope that helps. Note that you can name your threads and always use Thread.currentThread().getName() to help you understand further what is going on in your code.


If you want to create and show a Swing component from within a non-EDT thread, you must place the Swing code in a Runnable and queue it on the event thread like so:

class A extends Thread{
   public void run() {
      //show Form1
      SwingUtilities.invokeLater(new Runnable() {
         public void run() {
            Form1 form1 = new Form1();
            form1.setVisible(true);
         }
      });
   }
 }

So regardless of how many "A" objects you create, and thus separate new threads you create, all Swing code will be running on the same one thread.

0

精彩评论

暂无评论...
验证码 换一张
取 消