【问题标题】:How to make a JButton unclickable after clicking on it?单击后如何使JButton无法单击?
【发布时间】:2017-04-02 02:12:49
【问题描述】:

这是我的代码:

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 循环之外。不知道怎么回事。

这是它的样子:

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

【问题讨论】:

    标签: java swing jbutton


    【解决方案1】:

    您只需将 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);
         }
     }
    

    【讨论】:

      【解决方案2】:

      因为您想禁用面板中的所有按钮。按钮动作监听器应该在 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);
      
              }
          }
      
      });
      

      【讨论】:

      • 无需为每个按钮创建单独的 ActionListener。所有按钮都可以共享同一个 ActionListener。
      • 这行得通,谢谢。现在我要为其他问题哭泣。谢谢。
      • @Anonymous 如果您认为有帮助,请接受答案
      • @camickr 你适合这个用例。看图片,我觉得可能会为一组按钮的动作侦听器添加更多功能,并且所有按钮不需要以相同的方式做出反应。
      • @Anonymous,我给了你更好的解决方案。那应该是“接受”的答案。浪费资源创建 10 个做同样事情的 ActionListener?如果您的下一个应用程序有 100 个按钮怎么办?编写通用侦听器是很常见的,这样它们就可以被重用。
      猜你喜欢
      • 2016-09-05
      • 2020-08-09
      • 2013-09-26
      • 1970-01-01
      • 2022-06-30
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-11-20
      相关资源
      最近更新 更多