当我在匿名类中尝试时,为什么会出现此错误?

时间:2013-10-08 06:12:47

标签: java anonymous-inner-class

我收到错误消息:

当我尝试使用no suitable method found for showMessageDialog(<anonymous Runnable>,String,String,int)方法时,

JOptionPane.show...。那是为什么?

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

3 个答案:

答案 0 :(得分:2)

当你指的是this时,它指的是内部阶级,而不是你正在考虑的外部阶级。

尝试将该点告诉outer class,而不是anonymous inner class

 JOptionPane.showMessageDialog(OuterClassName.this, <--------
              "You have lost connectivity to the server", 
                  "Connection Error", JOptionPane.ERROR_MESSAGE);

答案 1 :(得分:1)

当您在匿名类中引用this时,它指的是匿名类实例本身。由于您要创建Runnable匿名实例,因此这将引用Runnable实例。

JOptionPane.showMessageDialog(..)不接受Runnable,所以您可能想要这样做

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

在上面,由于this是从showMessage()调用的,因此它引用了定义showMessage()的主类的实例

答案 2 :(得分:0)

代码片段甚至没有为我编译并在JOptionPane.showMessageDialog上抛出错误(这...

因为这应该是扩展Component。无论如何,我尝试使用Component扩展我的外部类,下面的代码对我没有任何问题。

    if (!isConnected) {
      JOptionPane.showMessageDialog(ThisAmbiguity.this, "You have lost connectivity to the server", "Connection Error", JOptionPane.ERROR_MESSAGE);
    }

ThisAmbiguity是我的外类。所以,当你在匿名内部类中引用它时,它指向内部类。