0

我收到一条错误消息:

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

3 回答 3

2

当您提到它时,this 它指向内部类,而不是您正在考虑的外部类。

试着告诉那个点outer class,而不是anonymous inner class

 JOptionPane.showMessageDialog(OuterClassName.this, <--------
              "You have lost connectivity to the server", 
                  "Connection Error", JOptionPane.ERROR_MESSAGE);
于 2013-10-08T06:14:06.180 回答
1

当您this在匿名类中引用时,它指的是匿名类实例本身。由于您正在创建一个Runnable匿名实例,因此 this 指的是该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是 from 调用的showMessage(),它指的showMessage()是定义在其中的主类的实例

于 2013-10-08T06:14:03.533 回答
0

代码片段甚至没有为我编译并在 JOptionPane.showMessageDialog(this ...

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

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

ThisAmbiguity 是我的外层。因此,当您在匿名内部类中引用 this 时,它是指向内部类。

于 2013-10-08T06:57:33.147 回答