在GridLayout JPanel中访问本地定义的JButton [英] Accessing locally defined JButtons in a GridLayout JPanel

查看:70
本文介绍了在GridLayout JPanel中访问本地定义的JButton的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

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

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.

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

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?

任何输入都表示赞赏。

谢谢。

推荐答案

你可以,

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

这篇关于在GridLayout JPanel中访问本地定义的JButton的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆