2015-04-18 63 views
0

我試着這樣做:無法創建一個匿名對象

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

    } 
}); 

,它給了我一個編譯錯誤稱爲語法錯誤令牌「(」和「)」。

你能告訴我我哪裏出錯了。我想創建一個實現接口ActionListener的類的匿名對象。

+0

你錯位了假名 – panagdu

回答

2

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

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

    } 
}; 
2

您需要將您的括號

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

在您需要先調用構造函數new ActionListener()然後添加的匿名身體換句話說類{...}

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

    } 
}; 

您無法通過代碼塊作爲參數new ActionListener({...})