Jbutton.doClick () clicks buttons but does not execute function

I have a jbutton that executes a function on mouse click. To do this programmatically I have another function

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

      

When I run the clickButton () function, I see the backButton is clicked on the jFrame, but the backButton related function is not happening. When I click on it with my mouse, it works. what am i doing wrong here?

+2


source to share


3 answers


If you have ActionListener

one attached to yours button

, it fires when the method is called .doClick()

;

Example test for proof:



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

      

+4


source


You can iterate over the listeners for this 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);
}

      

+1


source


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

0


source







All Articles