Java jbutton.doClick() 点击按钮但不执行功能

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/1355254/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-12 11:04:44  来源:igfitidea点击:

jbutton.doClick() clicks the buttons but does not perform the function

javaswingmouse

提问by kokokok

I have a jbutton which performs a function when clicked on by mouse. For doing this programatically I have this other function

我有一个 jbutton,它在用鼠标点击时执行一个功能。为了以编程方式执行此操作,我还有其他功能

void clickButton(){
      backButton.doClick();
}

When I run the clickButton() function I can see the backButton being pressed on the jFrame but the function associated with backButton does not happen. When I click on it with mouse it functions. what am I doing wrong here?

当我运行 clickButton() 函数时,我可以看到在 jFrame 上按下了 backButton,但与 backButton 关联的函数没有发生。当我用鼠标单击它时,它会起作用。我在这里做错了什么?

回答by Dan Dyer

How are you attaching the logic to the button? If you are using an ActionListener(or Action) it should fire. If you are using something else (perhaps MouseListener?), I don't think it will.

你如何将逻辑附加到按钮上?如果您使用的是ActionListener(或Action),它应该会触发。如果您正在使用其他东西(也许是 MouseListener?),我认为不会。

回答by Nettogrof

If you have an ActionListenerattached to your buttonit'll fire when you call the method .doClick();

如果您有一个ActionListener附加到您button的方法.doClick(),它会在您调用该方法时触发;

A sample test to prove it:

一个样本测试来证明它:

public class Test implements ActionListener {
    public Test() {
    }

    public void actionPerformed(ActionEvent e) {
        System.out.println("The action have been performed");
    }

    public static void main(String[] agrs) {
        JButton but = new JButton();
        but.addActionListener(new Test());
        but.doClick();
    }
}

回答by user2926110

You can iterate over the listeners for that button and call them manually.

您可以遍历该按钮的侦听器并手动调用它们。

    KeyEventDispatcher keyEventDispatcher = new KeyEventDispatcher() {
          @Override
          public boolean dispatchKeyEvent(final KeyEvent e) {
            if (e.getID() == KeyEvent.KEY_TYPED) {
              System.out.println(e);
              if (e.getKeyChar() == ' '){
                  MouseEvent me = new MouseEvent(btnStop,MouseEvent.MOUSE_CLICKED,EventQueue.getMostRecentEventTime(),0,0,1,1,false);
                  for (MouseListener ml : btnStop.getMouseListeners()) ml.mouseClicked(me);
              }
            }
            // Pass the KeyEvent to the next KeyEventDispatcher in the chain
            return false;
          }
        };
    KeyboardFocusManager.getCurrentKeyboardFocusManager().addKeyEventDispatcher(keyEventDispatcher);
}