【问题标题】:Accessing locally defined JButtons in a GridLayout JPanel在 GridLayout JPanel 中访问本地定义的 JButton
【发布时间】:2012-05-10 05:03:04
【问题描述】:

假设您在 NxN 网格中有一个 JButton 的 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[][] 这样的数组可以保存对所有按钮的引用吗?如何在上面的代码中设置?

感谢任何输入。

谢谢。

【问题讨论】:

标签: java swing jbutton grid-layout


【解决方案1】:

你可以,

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

【讨论】:

  • 哦,这很整洁! putClientProperty 的所有内部。我可能会尝试这个而不是一组 JButton 引用。谢谢!
  • 您不需要为每个按钮创建一个 MyActionListener 实例。一个实例适用于所有按钮。否则,一个很好的答案。
  • 嗯 putClientProperty。我从你的每一篇文章中都学到了一些新东西!
【解决方案2】:

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

【讨论】:

    猜你喜欢
    • 2012-05-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-03-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多