我正在用Java开发一款小游戏。我正在创建一个10 * 10的按钮网格。但是,我无法访问actionlistener中单击的按钮的ID。这是我到目前为止的代码。
String buttonID;
buttonPanel.setLayout(new GridLayout(10,10));
for (int i = 0; i < 10; i++) {
for (int j = 0; j < 10; j++) {
buttonID = Integer.toString(++buttonCount);
buttons[i][j] = new JButton();
buttons[i][j].setName(buttonID);
buttons[i][j].addActionListener(this);
buttons[i][j].setDisabledIcon(null);
buttonPanel.add(buttons[i][j]);
}
}
public void actionPerformed(ActionEvent ae) {
if (ae.getSource()==startButton) {
System.out.println("Game has been started");
}
if (ae.getSource() == "34") { //please see the description below
System.out.println("Yes I have clicked this button");
}
else {
System.out.println("Other button is clicked");
}
}
目前,我只打印了一些内容。我不知道如何将ae.getsource()与单击的按钮进行比较。我只是尝试将其与“ 34”进行比较。但是,当我单击网格上的第34个按钮时,它仍会打印“单击其他按钮”。
使用按钮actionCommand
属性可以根据您的要求唯一地标识每个按钮...
for (int i = 0; i < 10; i++) {
for (int j = 0; j < 10; j++) {
buttonID = Integer.toString(++buttonCount);
//...
buttons[i][j].setActionCommand(String.toString(buttonID));
//...
}
}
然后,在你actionPerformed
的方法,简单的外观起来actionCommand
的财产ActionEvent
....
public void actionPerformed(ActionEvent ae) {
String cmd = ae.getActionCommand();
if ("0".equals(cmd)) {
//...
} else if ...
同样,您可以使用buttons
数组根据ActionEvent
的来源查找按钮
public void actionPerformed(ActionEvent ae) {
Object source = ae.getSource();
for (int i = 0; i < 10; i++) {
for (int j = 0; j < 10; j++) {
if (source == (buttons[i][j])) {
//...
break;
}
}
}
但这取决于你...
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句