1 java swing jbutton actionlistener
我在获取按钮的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();
}
}
}
Run Code Online (Sandbox Code Playgroud)
您可以获得对通过ActionEvent的getSource()方法推送的按钮的引用.
例如,
public void actionPerformed(ActionEvent e) {
JButton selectedButton = (JButton) e.getSource();
}
Run Code Online (Sandbox Code Playgroud)
现在,如果您需要知道按钮在网格中的位置,您将需要做更多的工作,例如将按钮放入数组或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(); //!!
}
Run Code Online (Sandbox Code Playgroud)
作为旁注,每当我看到removeAll()我认为也许这可以通过使用CardLayout更好地实现
作为第二个侧面说明,当我在问题中看到"获取变量名称"时,我总是畏缩.变量"名称"并不是那么重要,对于许多对象来说并不存在,并且在编译代码中几乎不存在.如果一个对象被多个变量引用,哪一个代表该对象的"名称"?更重要的是对象引用,这是你的问题的大部分答案都在处理.