簡體   English   中英

使用內部類(java)有問題

[英]Having a issue using inner class (java)

我正在嘗試使用內部類設置,但是我遇到了一些問題。 這是我正在嘗試使用的代碼:

public class GUI
{
   class ButtonHandler implements ActionListener
   {
       public void actionPerformed(ActionEvent e)
       {
         // do something
       }
   }

   private static void someMethod()
   {
      JButton button = new JButton( "Foo" );
      button.addActionListener(new ButtonHandler());
   }
}

這是我得到的錯誤消息(在eclipse中):

No enclosing instance of type GUI is accessible. Must qualify the allocation with an enclosing instance of type GUI (e.g. x.new A() where x is an 
 instance of GUI).

請有人幫幫我嗎?

更改聲明:

class ButtonHandler implements ActionListener

至:

static class ButtonHandler implements ActionListener

如果沒有“靜態”修飾符,它就是一個實例級內部類,這意味着您需要一個封閉GUI類的實例才能工作。 如果你把它作為一個“靜態”內部類,它就像一個普通的頂級類(隱式靜態)。

(並且在您的示例中,這是必要的關鍵原因是someMethod是靜態的,因此在該上下文中沒有封閉類的實例。)

我相信它會給你這個錯誤,因為這是在靜態方法中完成的。 由於ButtonHandler是一個非靜態嵌套類,因此它必須綁定到一個封閉的GUI實例。 您很可能只想要一個靜態嵌套類:

static class ButtonHandler implements ActionListener
{
    public void actionPerformed(ActionEvent e)
    {
      // do something
    }
}

讓你的內部類靜態。 :)

要創建非靜態內部類的實例,您需要擁有周圍外部類的實例(並且沒有,因為someMethod是靜態的):

JButton button = new JButton( "Foo" );
button.addActionListener(new GUI().new ButtonHandler());

如果內部類不需要訪問外部類的成員/方法,那么使內部類成為靜態,那么您可以創建內部類的實例,如下所示:

static class ButtonHandler implements ActionListener { ... }

...

JButton button = new JButton( "Foo" );
button.addActionListener(new GUI.ButtonHandler());

(在這種情況下,即使是普通的new ButtonHandler()也可以工作,因為someMethod()是在外部類GUI定義的,即與ButtonHandler在同一個“命名空間”中

您正試圖從靜態成員中訪問非靜態成員。 當您在靜態函數中訪問ButtonHandler時,成員類不可見,因為它與GUI類的實例相關聯。

你應該使ButtonHandler成為一個靜態類。 例如:

static class ButtonHandler implements ActionListener

在Java中, static內部類不需要實例化容器類的實例。 您可以簡單地執行new ButtonHandler() (就像您目前所做的那樣)。

僅供參考,您也可以更改該行

button.addActionListener(new ButtonHandler());

button.addActionListener(this.new ButtonHandler());

但我不推薦它。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM