问题
Lets say you have a GridLayout of JButtons in an NxN grid, in code such as this:
JPanel bPanel = new JPanel();
bPanel.setLayout(new GridLayout(N, N, 10, 10));
for (int row = 0; row < N; row++)
{
for (int col = 0; col < N; col++)
{
JButton b = new JButton("(" + row + ", " + col + ")");
b.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
}
});
bPanel.add(b);
}
}
How would one access each button individually in the grid to change the button's name through setText()? This needs to be done outside of actually pressing the button in question.
Because each button in instantiated locally as "b", a globally accessible name for each button is not possible at current. What could be done to access each button independently? Could an array like JButton[][] hold references to all the buttons? How can this be set up in the code above?
Any input is appreciated.
Thanks.
回答1:
you can,
1) putClientProperty
buttons[i][j].putClientProperty("column", i);
buttons[i][j].putClientProperty("row", j);
buttons[i][j].addActionListener(new MyActionListener());
and
public class MyActionListener implements ActionListener {
@Override
public void actionPerformed(ActionEvent e) {
JButton btn = (JButton) e.getSource();
System.out.println("clicked column " + btn.getClientProperty("column")
+ ", row " + btn.getClientProperty("row"));
}
2) ActionCommand
回答2:
You can create an array (or list or something else) to store all the buttons. Or you can use public Component[] getComponents()
method of the bPanel (Container).
来源:https://stackoverflow.com/questions/10384662/accessing-locally-defined-jbuttons-in-a-gridlayout-jpanel