簡體   English   中英

無法創建匿名對象

[英]Unable to create an anonymous object

我嘗試這樣做:

ActionListener listener = new ActionListener( {
    public void actionPerformed(ActionEvent e) {        

    }
});

它給了我一個編譯錯誤,稱為令牌“(”和“)”上的語法錯誤。

您能告訴我我要去哪里了嗎? 我想創建實現接口ActionListener的類的匿名對象。

您正在使用匿名類的內容作為ActionListener構造函數的參數。 首先關閉括號,然后添加匿名類的主體:

ActionListener listener = new ActionListener() {
    public void actionPerformed(ActionEvent e) {        

    }
};

您需要移動括號

                                             ↓<<<<<<<+
ActionListener listener = new ActionListener( {      |
    public void actionPerformed(ActionEvent e) {     |  
                                                     |  
    }                                                |
});                                                  |
 ^>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>+

換句話說,您首先需要調用構造函數new ActionListener() ,然后添加匿名類{...}

ActionListener listener = new ActionListener() {
    public void actionPerformed(ActionEvent e) {        

    }
};  

您不能將代碼塊作為參數new ActionListener( {...} )傳遞

暫無
暫無

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

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