在GridLayout JPanel中访问本地定义的JButton

假设您在NxN网格中有一个JButtons的GridLayout,代码如下:

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); } } 

如何在网格中单独访问每个按钮以通过setText()更改按钮的名称? 这需要在实际按下相关按钮之外完成。

因为每个按钮在本地实例化为“b”,所以当前不可能为每个按钮提供全局可访问的名称。 如何独立访问每个按钮? 像JButton [] []这样的数组是否可以保存对所有按钮的引用? 如何在上面的代码中设置?

任何输入都表示赞赏。

谢谢。

您可以,

1) putClientProperty

 buttons[i][j].putClientProperty("column", i); buttons[i][j].putClientProperty("row", j); buttons[i][j].addActionListener(new MyActionListener()); 

 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

您可以创建一个数组(或列表或其他内容)来存储所有按钮。 或者您可以使用bPanel(Container)的public Component[] getComponents()方法。