Access location of a button in GridLayout
I have a grid of buttons and i want to know if theres a way to retrieve the location of the button pressed, i have an action listener for the but开发者_运维问答tons but i need the Row and column of the button that was pressed and i cant seem to figure out how
You can use
JButton.setActionCommand(String actionCommand)
to associate any information you want with the button, so you can encode some value that specifies the information you want there.
Then when you get your actionListener called, you can retrieve it thru
public void actionPerformed(ActionEvent ae) {
String cmd = ae.getActionCommand();
//based on cmd, do something
}
One relatively easy way is to put the buttons in a 2D array and then iterate through the array with a pair of nested for loops til you find the button that matches the current (via ActionEvent#getSource(). Then your row and column are the loop indices.
精彩评论