2016-05-08 20 views
0

複数のノードにSetOnMousePressed関数を追加するメソッドを作ろうとしていますが、いくつかの異なるループを使ってみましたが、私はいつも "Local variable包囲範囲内で定義されたxは、最終的なものでなければならない。これは、私の知る限り得ているようです:Javafxがループ内にイベントハンドラを追加する

public static int playerSelectingCategory(int intScorecard[][], Rectangle[][] scoreboardBackground, int categoryCounter, int nrOfPlayers, boolean limitCheck) 

    { 
    int counter = 0; 
    int y = 0; 

    for(int x = 0; x<YatzyConstants.getNrCategories(); x++) 
    { 
    if(counter < nrOfPlayers) 
    { 
     if(y < YatzyConstants.getNrCategories()) 
     { 
      scoreboardBackground[counter][y].setOnMousePressed(e -> 
      { 
        scoreboardBackground[counter][y].setFill(javafx.scene.paint.Color.ALICEBLUE); 
      }); 
      y++; 
     } 
     counter++; 

    }} 
    return intScorecard[counter][y]; 
} 

私はもともと1で、すべて1を宣言したが、私はそれを行うためのより効果的な方法があるはずだと思うしなければなりません。どんな助けもありがたいです、本当にここのレンガの壁に当たってください。

答えて

0

yはあなたのコードによって修正されているため、最終的な最終結果ではないため、匿名クラスまたはラムダ式からアクセスすることはできません。 counterについても同様です。

私は変数にscoreboardBackground[counter][y]を格納お勧めしたいものである(事実上)final(つまり、配列が変更されない限り、あなたは、元の矩形が格納されていた位置にRectangleを色付けしたい...):

final Rectangle rect = scoreboardBackground[counter][y]; 
rect.setOnMousePressed(e -> { 
    rect.setFill(javafx.scene.paint.Color.ALICEBLUE); 
}); 

または代替的に、単にイベントのソースであるNodeを使用:

final EventHandler<MouseEvent> handler = event -> { 
    ((Shape) event.getSource()).setFill(javafx.scene.paint.Color.ALICEBLUE); 
}; 

for(int x = 0; x<YatzyConstants.getNrCategories(); x++) 
{ 
    if(counter < nrOfPlayers) 
    { 
     if(y < YatzyConstants.getNrCategories()) 
     { 
      scoreboardBackground[counter][y].setOnMousePressed(handler); 
      y++; 
     } 
.... 
関連する問題