Search code examples
javaswingrunnableevent-dispatch-threadinvokelater

Swing Runnable with parameters


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.


Solution

  • 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);
        }
    });