Ave*_*eus 2 java swing jbutton grid-layout
假设您在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);
}
}
Run Code Online (Sandbox Code Playgroud)
如何在网格中单独访问每个按钮以通过setText()更改按钮的名称?这需要在实际按下相关按钮之外完成.
因为每个按钮在本地实例化为"b",所以当前不可能为每个按钮提供全局可访问的名称.如何独立访问每个按钮?像JButton [] []这样的数组是否可以保存对所有按钮的引用?如何在上面的代码中设置?
任何输入都表示赞赏.
谢谢.
您可以,
1) putClientProperty
buttons[i][j].putClientProperty("column", i);
buttons[i][j].putClientProperty("row", j);
buttons[i][j].addActionListener(new MyActionListener());
Run Code Online (Sandbox Code Playgroud)
和
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"));
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1427 次 |
| 最近记录: |