【问题标题】:How can I trigger an Action Command artificially?如何人为触发动作命令?
【发布时间】:2017-04-03 17:35:21
【问题描述】:

我有两个带有 ActionListener 的 JRadioButton 对象:

    for (JRadioButton b : rightRButtons) {
        b.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                if (e.getActionCommand().equals("Unidade")) {
                    disableAllComponents(divisiblePanel);
                    enableAllComponents(unityPanel);
                } else if (e.getActionCommand().equals("Divisível")) {
                    disableAllComponents(unityPanel);
                    enableAllComponents(divisiblePanel);
                }
            }
        });
    }

在代码的某处,我选择了其中一个:rdbtnCreationDivisible.setSelected(true);

这些单选按钮一旦被点击,就会禁用它们各自面板上的所有组件。当我使用 setSelected 方法选择它们时,组件不会被禁用。如何人为地触发一个动作命令,让 ActionListener 能够“捕捉”到这个命令?

【问题讨论】:

    标签: java swing


    【解决方案1】:

    您可以create your own event,然后将其传递给dispatchEvent

    rdbtnCreationDivisible.setSelected(true);
    ActionEvent fakeEvent = new ActionEvent(rdbtnCreationDivisible,
            ActionEvent.ACTION_PERFORMED, "Divisível");
    rdbtnCreationDivisible.dispatchEvent(fakeEvent);
    

    【讨论】:

      【解决方案2】:

      您可以尝试几件事:

      首先,您可以遍历添加到按钮的所有ActionListeners,然后调用它的actionPerformed() 方法,传入ActionEvent 和您喜欢的任何ActionCommand

           for(ActionListener al : b.getActionListeners()) {
                      al.actionPerformed(new ActionEvent(this, ActionEvent.ACTION_PERFORMED, "Unidade") { });
                  }
      

      另一种选择是将您的ActionListener 替换为ItemListener。这将在按钮被选择/取消选择时被调用,而不是被点击:

           b.addItemListener(new ItemListener() {
                      @Override
                      public void itemStateChanged(ItemEvent e) {
                          //Will get called when you change selection using .setSelected()
                      }
                  });
      

      Nemi 有更多关于使用ItemListener 而不是ActionListener 的信息来回答这里的问题:Detecting a JRadioButton state change

      【讨论】:

      • 没问题,很高兴我能帮上忙。 :)
      猜你喜欢
      • 2021-04-14
      • 2013-10-24
      • 2022-01-15
      • 1970-01-01
      • 1970-01-01
      • 2016-02-10
      • 1970-01-01
      • 2017-08-14
      • 2018-12-09
      相关资源
      最近更新 更多