2 回答
TA贡献1878条经验 获得超4个赞
我建议创建一个自定义按钮类,用于保存money数组中相应值的索引。例如:
public class MyButton extends JButton {
private int moneyIndex;
public MyButton(String text, int moneyIndex){
super(text);
this.moneyIndex = monexIndex;
}
public int getMoneyIndex(){
return moneyIndex;
}
}
然后,您可以使用与之前相同的方式创建一个按钮,但将货币索引传递给它:
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);
}
然后,在你的动作监听器中(我假设你的主类已经扩展了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]));
}
这种方法的优点是索引由按钮存储,因此您不需要搜索所有按钮来检查哪个按钮被按下。随着您拥有的按钮数量的增加,这一点变得更加重要,但无论大小,都需要考虑这一点。
此外,当这个项目变得更复杂时,这种方法会让你的生活更轻松,因为每个按钮都可以存储特定于它的信息,而无需一堆数组或操作命令。
TA贡献1895条经验 获得超3个赞
作为自定义按钮类解决方案的替代方案,您可以将按钮保留在地图中,及其索引和操作处理程序上,根据源获取索引:
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);
...
}
添加回答
举报