TLD
TLD

Reputation: 8135

Share data between threads and JOptionPane needs thread to run!

            public void aMethod(){
              new Thread(new Runnable() {

                public void run() {
                   int decide = JOptionPane.showConfirmDialog(null, confirmName?, JOptionPane.YES_NO_OPTION);
                }
            }).start();
            System.out.println("Number of decison " + decide); //Can't find symbol "decide"
               }


JOptionPane can't run without being put to a thread(I don't know why). Yet when put it to a thread, I can't get the varible decide from that. P/s: This is a method in callbackImplement Java RMI. Thank you. happy new year :P

Upvotes: 0

Views: 534

Answers (2)

MeBigFatGuy
MeBigFatGuy

Reputation: 28598

I don't think it's possible to do this with an anonymous class as the runnable class. You need to create a named class, that has a getter for the value of the 'decide' variable.

The problem is of course, that the main thread must wait until the created thread is finished before calling the getter to get the value of the 'decide' variable.

Given this, it seems dubious why you would be using a separate thread in the first place to show the dialog.

If you still want to do this, the main thread needs to call Thread.join on the created thread before calling the getter to get the value of 'decide'.

Upvotes: 1

casablanca
casablanca

Reputation: 70731

You can define custom fields in your Runnable subclass and pass them through the constructor:

public class MyRunnable implements Runnable {
  private int decide;

  public MyRunnable(int decide) {
    this.decide = decide;
  }

  public void run() {
    ...
  }
}

As for why you need to invoke Swing methods on their own thread, you can read this article: Threads and Swing. In fact, you shouldn't be creating your own thread but instead just schedule it on the Swing event dispatch thread:

SwingUtilities.invokeLater(new MyRunnable(decide));

Upvotes: 1

Related Questions