How do I programmatically send ActionEvent to JButton?

前端 未结 5 1970
太阳男子
太阳男子 2020-12-20 11:56

How do I programmatically send an ActionEvent (eg button pressed/ACTION_PERFORMED) to a JButton?

I know of:

button.doClick(         


        
5条回答
  •  心在旅途
    2020-12-20 12:33

    Even if you could, why would you want to? Usually when people want to do something like this, it means they haven't properly separated the concerns of the UI from business logic. Typically they want to invoke some logic that occurs in an ActionListener without needing the action to take place.

    public void actionPerformed(ActionEvent ae) {
        //SomeLogic
    }
    
    //...
    
    public void someOtherPlace() {
        //I want to invoke SomeLogic from here though!
    }
    

    But really the solution is to extract that logic from the ActionListener and invoke it from both the ActionListener and that second location:

    public void someLogic() {
        //SomeLogic
    }
    
    public void actionPerformed(ActionEvent ae) {
        someLogic();
    }
    
    //...
    
    public void someOtherPlace() {
        someLogic();
    }
    

提交回复
热议问题