Reputation: 21329
I get an error that says :
no suitable method found for showMessageDialog(<anonymous Runnable>,String,String,int)
as I try to use the JOptionPane.show...
method. Why is that ?
private void connectivityChecker() {
Runnable r = new Runnable() {
@Override
public void run() {
try {
Thread.sleep(3000);
}catch(Exception exc) {
System.out.println("Thread Interrupted !");
}
boolean isConnected = Internet.isConnected();
if(!isConnected) {
JOptionPane.showMessageDialog(this, "You have lost connectivity to the server", "Connection Error", JOptionPane.ERROR_MESSAGE);
}
}
};
new Thread(r,"Connectivity Checker - UserGUI").start();
}
Upvotes: 0
Views: 205
Reputation: 41
The code snippet did not even compile for me and throwing an error on JOptionPane.showMessageDialog(this ...
Because this should be extending Component. Anyways I tried extended my outer class with Component and the code below worked for me without any issues.
if (!isConnected) {
JOptionPane.showMessageDialog(ThisAmbiguity.this, "You have lost connectivity to the server", "Connection Error", JOptionPane.ERROR_MESSAGE);
}
ThisAmbiguity is my outer class. So, when you are referring to this in anonymous inner class so its pointing inner class.
Upvotes: 0
Reputation: 121998
When you are referring to this
it points to inner class, not the outer class which you are thinking.
Try to tell that point to outer class
, not the anonymous inner class
.
JOptionPane.showMessageDialog(OuterClassName.this, <--------
"You have lost connectivity to the server",
"Connection Error", JOptionPane.ERROR_MESSAGE);
Upvotes: 2
Reputation: 17622
when you refer this
within the anonymous class, it refers to the anonymous class instance itself. Since you are creating a Runnable
anonymous instance, this refers to that Runnable
instance.
JOptionPane.showMessageDialog(..)
does't accept Runnable
, so you might want to do something like this
private void connectivityChecker() {
Runnable r = new Runnable() {
@Override
public void run() {
try {
Thread.sleep(3000);
}catch(Exception exc) {
System.out.println("Thread Interrupted !");
}
boolean isConnected = Internet.isConnected();
if(!isConnected) {
showErrorMessage("You have lost connectivity to the server", "Connection Error" );
}
}
};
new Thread(r,"Connectivity Checker - UserGUI").start();
}
private void showErrorMessage(String message, String header) {
JOptionPane.showMessageDialog(this, message, header, JOptionPane.ERROR_MESSAGE);
}
In above, since this
is called from showMessage()
, it refers to the instance of the main class in which showMessage()
is defined
Upvotes: 1