program-o-steve
program-o-steve

Reputation: 2678

Why do I get a "No suitable method found for anonymous " error?

Runnable r = new Runnable() {
    @Override
    public void run() {
        if(varx) {
            new displayFullScreen().setVisible(true);
        } else {
            javax.swing.JOptionPane.showMessageDialog(this, "dfv"); // this statement gives an error
        }
    }
};
new Thread(r,"full_screen_display").start();

The error in the marked line says "No suitable method found for anonymous (<java.lang.Runnable>,java.lang.String)"

Why does it so when i have directly written javax.swing._CLASS_ ?

Upvotes: 1

Views: 2266

Answers (3)

GETah
GETah

Reputation: 21409

JOptionPane.showMessageDialog documentation says:

parentComponent - determines the Frame in which the dialog is displayed; if null, or if the parentComponent has no Frame, a default Frame is used

javax.swing.JOptionPane.showMessageDialog(this, "dfv"); will not work as this is a Runnable which does not inherit from Component. Use this instead:

javax.swing.JOptionPane.showMessageDialog(null, "dfv");

Upvotes: 0

Bohemian
Bohemian

Reputation: 424993

The reason is javax.swing.JOptionPane.showMessageDialog expects a Component as the first argument, but you're passing in this, which is a Runnable (anonymous).

Upvotes: 0

Mat
Mat

Reputation: 206689

The problem is that this in that line refers to the anonymous Runnable instance you've created, not the class that surrounds it. You'll need to be more explicit about what this you mean in there.

If the enclosing class is named Foo, and is a swing Component, you should write:

javax.swing.JOptionPane.showMessageDialog(Foo.this, "dfv"); 

See the Nested Classes docs for more information.

Upvotes: 4

Related Questions