2

I would like to run new Swing thread and pass a parameter into them. Something like this:

String str;

SwingUtilities.invokeLater(new Runnable() {
public void run() {
    Play game = new Play(this.str);
        game.setVisible(true);
    }
});

I found answer, how to pass a parameter into thread, but I am not sure how to rebuild it for my need. Thanks for ideas.

Community
  • 1
  • 1
Andrew
  • 958
  • 13
  • 25
  • You could use SwingWorker or create a custom class that implements Runnable and takes the parameters you want to pass it – MadProgrammer Apr 14 '13 at 09:19
  • This is my first graphic java application and it is very simple. @trashgod idea works, so I will not rebuild my code, but I will think at your notice next time :) – Andrew Apr 14 '13 at 11:21

2 Answers2

3

Alternatively, your anonymous Runnable can access final fields in the enclosing scope:

final String str = "one";

SwingUtilities.invokeLater(new Runnable() {
    @Override
    public void run() {
        Play game = new Play(str);
        game.setVisible(true);
    }
});
trashgod
  • 203,806
  • 29
  • 246
  • 1,045
  • You are welcome. For reference, see also [*Defining and Starting a Thread*](http://docs.oracle.com/javase/tutorial/essential/concurrency/runthread.html). – trashgod Apr 14 '13 at 11:21
0

You can't. Make a new Thead instead.

Edit: Here's some code since you're confused.

import javax.swing.SwingUtilities;

public class Main {
  public static void main(String[] args) {
    SwingUtilities.invokeLater(new MyThread("StackOverflow"));
  }

  private static class MyThread extends Thread {
    String text;

    public MyThread(String text) {
      this.text = text;
    }

    @Override
    public void run() {
      System.out.println(this.text);
    }
  }
}
Sanchit
  • 2,240
  • 4
  • 23
  • 34