I have a gridLayout of JButtons. I'd like to distinguish every JButton from each other in the actionPerformed function. I don't want to "name" each JButton. The user press a JButton randomly. Is there any method to know which button has been pressed? It is possible?
[....]
tUsuariCPU = new JButton[mida][mida];
for (int i=0;i<size;i++){
for (int j=0;j<size;j++){
JButton temp = new JButton();
tUsuariCPU[i][j] = temp;
temp.addActionListener(this);
panel.add(temp);
}
}
}
public void actionPerformed(ActionEvent e) {}
[....]
}
If you wish to use a single ActionListener
, you can check which Component fired the event by using the getSource
button and comparing the instance to the JButton instances. Below uses a loop to loop over the 2D array of JButtons:
public void actionPerformed(ActionEvent e) {}
for ( int i = 0; i < tUsuariCPU.length; i++ ){
for ( int j = 0; j < tUsuariCPU[i].length; j++ ){
if ( e.getSource() == tUsuariCPU[i][j] ){
//do something
}
}
}
}
Alternatively, you can add a single ActionListener per button, or set the ActionCommand of the JButton and use this value to determine which JButton fired the event ( e.getActionCommand().equals(myButton.getActionCommand())
)
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.