[英]Get the parameters of a method in a anonymous class
我對鍵綁定有疑問。 我有以下Java代碼:
private void registerPressedReleasedKey(String keyChar, boolean key, boolean pressedKey) {
// 1. decide if the key is pressed or released
// 2. save key and its action name
// 3. decide, what to do, when the action name is being mentioned
// 4. change the boolean value in actionPerformed(ActionEvent ae)
String keyStatus;
if(pressedKey == true)
keyStatus = "pressed ";
else
keyStatus = "released ";
getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW).put(KeyStroke.getKeyStroke(keyStatus + keyChar), keyStatus + keyChar);
getActionMap().put(keyStatus + keyChar, new AbstractAction() {
@Override
public void actionPerformed(ActionEvent ae) {
key = pressedKey;
}
});
}
Eclipse對我說key = keyPressed;
是錯誤的,因為我只能使用final
變量。 我的問題是,是否有可能在actionPerformed(ActionEvent ae)
方法內訪問和更改key
。
不能以您嘗試的方式修改匿名類中的外部變量,因為這些變量必須是最終的。
如果這是您課程的一個字段,則可以直接使用它(在Java> 7中)或使用訪問器(設置器)。 既然不是,那么方法就是使用包裝器 : final
意味着您不能分配新值,但是仍然可以調用其方法,任何訪問器基本上都是方法。
我假設您的代碼不完整,如本例所示,您嘗試設置變量key
,該變量在任何地方都不會使用。
但是, 將新值分配給參數通常是一種不好的做法 。
此外, getActionMap()
和AbstractAction
建議使用一個Swing組件,這意味着即使在registerPressedReleaseKey()
完成之后,Swing線程也會調用actionPerformed()。 結果,為此方法更新參數是沒有意義的。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.