2013-04-26 42 views
1

我试图用颜色在面板中创建一组Jbuttons。每个不同的文本和色彩特性(从阵列中得到)用颜色创建JButton

这里是我的代码

for(int e = 0;e<game.players.get(0).getHand().size();e++){ 
    panel.add(new JButton(){{ 
     setText(game.players.get(0).getHand().get(e).getValue()); 
     setBackground(game.players.get(0).getHand().get(e).getColor()); 
    }}); 
} 

但我得到一个错误。它说我不能访问变量e,因为它没有被声明为final(本地访问e是从内部类中访问的)。

,如果我做

for(int e = 0;e<game.players.get(0).getHand().size();e++){ 
    panel.add(new JButton(game.players.get(0).getHand().get(e).getValue())); 
} 

它工作完全正常,但没有颜色的按钮。

回答

0

你可以将它添加到面板之前简单地创建JButton

MyHand myHand = game.players.get(0).getHand(); 
for (int e=0; e < myHand.size(); e++) { 
    JButton button = new JButton(myHand.get(e).getValue()); 
    button.setBackground(myHand.get(e).getColor()); 
    panel.add(button); 
} 

从这个代码getHand似乎返回Iterable集合。在这种情况下,可以使用enhanced for loop