2 回答

TA貢獻(xiàn)1878條經(jīng)驗(yàn) 獲得超4個贊
我建議創(chuàng)建一個自定義按鈕類,用于保存money數(shù)組中相應(yīng)值的索引。例如:
public class MyButton extends JButton {
private int moneyIndex;
public MyButton(String text, int moneyIndex){
super(text);
this.moneyIndex = monexIndex;
}
public int getMoneyIndex(){
return moneyIndex;
}
}
然后,您可以使用與之前相同的方式創(chuàng)建一個按鈕,但將貨幣索引傳遞給它:
for (int i = 0; i < caseButton.length; i++) {
// I suspect you want the moneyIndex to match the index of the button
caseButton[i] = new MyButton("?", i);
cases.add(caseButton[i]);
// These can be moved to the custom button class if all MyButtons have these customizations
caseButton[i].setPreferredSize(new Dimension(100, 100));
caseButton[i].setFont(new Font("Dialog", Font.BOLD, 35));
caseButton[i].setForeground(new Color(255, 215, 0));
// Set this class as the action listener
caseButton[i].setActionListener(this);
}
然后,在你的動作監(jiān)聽器中(我假設(shè)你的主類已經(jīng)擴(kuò)展了ActionListener),你可以訪問 moneyIndex 變量:
public void actionPerformed(ActionEvent e){
// Get the source of the click as a MyButton
MyButton source = (MyButton) e.getSource();
// Get the moneyIndex of the source button
int moneyIndex = source.getMoneyIndex();
// Update the button's text according to the moneyIndex
source.setText(Integer.toString(money[moneyIndex]));
}
這種方法的優(yōu)點(diǎn)是索引由按鈕存儲,因此您不需要搜索所有按鈕來檢查哪個按鈕被按下。隨著您擁有的按鈕數(shù)量的增加,這一點(diǎn)變得更加重要,但無論大小,都需要考慮這一點(diǎn)。
此外,當(dāng)這個項(xiàng)目變得更復(fù)雜時,這種方法會讓你的生活更輕松,因?yàn)槊總€按鈕都可以存儲特定于它的信息,而無需一堆數(shù)組或操作命令。

TA貢獻(xiàn)1895條經(jīng)驗(yàn) 獲得超3個贊
作為自定義按鈕類解決方案的替代方案,您可以將按鈕保留在地圖中,及其索引和操作處理程序上,根據(jù)源獲取索引:
Map<JButton, Integer> caseButtons = new HashMap<>(10);
for(int i=0; i<10; i++) {
JButton button = ...
// all the other setup goes here
caseButtons.put(button, i);
}
...
public void actionPerformed(ActionEvent e){
// Get the source of the click as a MyButton
JButton source = (JButton) e.getSource();
int index = caseButtons.get(source);
...
}
添加回答
舉報(bào)