我在获取按钮的 ID/变量名称时遇到问题。一般来说,我想创建熄灯游戏。我创建了按钮面板(NxN,来自组合框的 N),但我不知道如何在按下后获取单个按钮的 ID。有什么想法吗?
private void p1ActionPerformed(java.awt.event.ActionEvent evt) {
String temp = jComboBox1.getSelectedItem().toString();
ile=Integer.parseInt(temp);
jPanel1.removeAll();
jPanel1.setLayout(new GridLayout(ile,ile));
for (int i = 0; i < ile; i++) {
for (int j = 0; j < ile; j++) {
JButton btn = new JButton();
btn.setPreferredSize(new Dimension(40, 40));
btn.setBackground(Color.green);
btn.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e)
{
/*What put here?*/
}
});
jPanel1.add(btn);
revalidate();
pack();
}
}
}
最佳答案
您可以获得对通过 ActionEvent 的 getSource() 方法推送的按钮的引用。
例如,
public void actionPerformed(ActionEvent e) {
JButton selectedButton = (JButton) e.getSource();
}
现在,如果您需要知道按钮在您的网格中的位置,您将需要做更多的工作,例如将您的按钮放入一个数组或 ArrayList 中,然后遍历该数组以找到所选按钮的索引号按钮。
例如,
// changes to code marked with a //!! comment
private void p1ActionPerformed(java.awt.event.ActionEvent evt) {
String temp = jComboBox1.getSelectedItem().toString();
ile = Integer.parseInt(temp);
jPanel1.removeAll();
jPanel1.setLayout(new GridLayout(ile, ile));
final JButton[][] buttons = new JButton[ile][ile]; //!!
for (int i = 0; i < ile; i++) {
for (int j = 0; j < ile; j++) {
JButton btn = new JButton();
btn.setPreferredSize(new Dimension(40, 40));
btn.setBackground(Color.green);
btn.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
//!!
JButton source = (JButton) e.getSource();
for (int k = 0; k < buttons.length; k++) {
for (int l = 0; l < buttons[k].length; l++) {
if (buttons[k][l] == source) {
System.out.printf("row: %d, col: %d%n", l, k);
return;
}
}
}
}
});
jPanel1.add(btn);
buttons[i][j] = btn; //!!
//!! revalidate();
//!! pack();
}
}
jPanel1.revalidate(); //!!
jPanel1.repaint(); //!!
}
附带说明,每当我看到 removeAll()
时,我认为使用 CardLayout 可以更好地实现这一点
作为第二个旁注,当我在问题中看到“获取变量名称”时,我总是感到畏缩。变量“名称”并不是那么重要,很多对象都不存在,而且几乎不存在于编译代码中。如果一个对象被多个变量引用,那么哪个变量代表这个对象的“名称”?更重要的是对象引用,这是您问题的大部分答案所涉及的内容。
关于java - 如何在按下时获取按钮的变量名称?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25526349/