单击后如何使 JButton 不可单击?

How to make a JButton unclickable after clicking on it?

这是我的代码:

for(int row = 0; row < 10; row++)
{
    for(int col = 0; col < 10; col++)
    {
            button = new JButton();

            panel_1.add(button);
     }
 }

    button.addActionListener(new ActionListener()
    {
        public void actionPerformed(ActionEvent e)
        {
            //If Button is clicked, make the button unclickable
            if(button == (JButton)e.getSource())
            {
                button.setEnabled(false);

            }
        }

    });

我想让我从这个 10 x 10 网格按钮布局中单击的任何 JButton 都不可单击;但是,这种方法只会使右键无法单击,有什么问题吗?我已将 ActionListener 放在负责制作按钮的 for-Loop 之外。不知道怎么回事

这是它的样子:

编辑:bsd 代码有效。在添加按钮或类似内容之前添加 ActionListener。

您只需将 ActionListener 添加到最后创建的按钮。

您需要将 ActionListener 添加到循环内创建的每个按钮。

所以代码应该是这样的:

ActionListener al = new ActionListener()
{
    public void actionPerformed(ActionEvent e)
    {
         JButton button = (JButton)e.getSource();
         button.setEnabled( false );
    }
};

for(int row = 0; row < 10; row++)
{
    for(int col = 0; col < 10; col++)
    {
            button = new JButton();
            button.addActionListener( al );
            panel_1.add(button);
     }
 }

因为您想禁用面板中的所有按钮。按钮动作侦听器应该在 for 循环内。

button = new JButton();
button.addActionListener(new ActionListener()
{
    public void actionPerformed(ActionEvent e)
    {
        //If Button is clicked, make the button unclickable
        if(button == (JButton)e.getSource())
        {
            button.setEnabled(false);

        }
    }

});