2017-09-13 33 views
1

試圖做一個簡單的打字遊戲。我創建了一個由LibGDX scene2d TextButton組成的鍵盤,並將它們放入3個scene2d表(每行鍵)並將它們包裝到另一個表中。這裏的代碼到目前爲止:LibGDX原始鍵盤與每個鍵的聽衆

Gdx.input.setInputProcessor(stage); 

Table keyboard = new Table(); 
Table keysTop = new Table(); 
Table keysMid = new Table(); 
Table keysBot = new Table(); 

final char ascii[] = {'Q', 'W', 'E', 'R', 'T', 'Y', 'U', 'I', 'O', 'P', 
      'A', 'S', 'D', 'F', 'G', 'H', 'J', 'K', 'L', 
      'Z', 'X', 'C', 'V', 'B', 'N', 'M'}; 

// create all keys in order of the ascii[] table above 
for (int index = 0; index < ascii.length; index++) { 
    keys[index] = new TextButton("", skin); 
    String letter = Character.toString(ascii[index]); 
    keys[index].setText(letter); 
    keys[index].setSkin(skin); 

    // and put them in correct rows 
    if (index < 10) 
     keysTop.add(keys[index]).width(keySize).height(keySize + 5).pad(2); 
    else if (index < 19) 
     keysMid.add(keys[index]).width(keySize).height(keySize + 5).pad(2); 
    else 
     keysBot.add(keys[index]).width(keySize).height(keySize + 5).pad(2); 
} 

// add each row of keys to the keyboard Table 
keyboard.add(keysTop).pad(5).expandX().fill().row(); 
keyboard.add(keysMid).pad(5).expandX().fill().row(); 
keyboard.add(keysBot).pad(5).expandX().fill().row(); 

stage.addActor(keyboard); 

現在我想爲每個鍵添加偵聽器,最好在循環中。把下面的代碼在的結束for循環:

keys[index].addListener(new ChangeListener() { 
    @Override 
    public void changed(ChangeEvent event, Actor actor) { 
     System.out.println(letter); 
    } 
}); 

由於錯誤不能編譯「變量‘信’是從內部類中訪問,需要被聲明爲final」。 這裏的首選(或最簡單的,如果首選的話很難實施初學者)的解決方案是什麼?

回答

0
  • 通過setName(String name)聲明letter String作爲final

  • keys[index] TEXT按鈕的集名稱和改變後的方法使用內部事件取targetListener名稱。
+0

聲明該變量爲最終確實工作。早些時候,我認爲它不能被設置爲最終的,因爲最終的變量不應該改變。我是否認爲在這種情況下它的工作原理是正確的,因爲我用for循環的每一遍都重新聲明瞭該變量? – elesmod