Search code examples
javaswingjbuttonactionevent

java swing manual start an event without user input


I want to activate an event without clicking all the button interface. ex. when i click button_0, it will print red, and at the same time it will perform action on button_1 and button_2, hence will also print blue and green at the same time.

Those three operation must be separate, solution as merging both action is not applicable on my case, I only made the example as a small guide.

public void actionPerformed(ActionEvent e) 
{
    if(e.getSource()==button_0)
    {
       System.out.println("red");
    }
    else if(e.getSource()==button_1)
    {   
        System.out.println("blue");
    }
    else if(e.getSource()==button_2)
    {
        System.out.println("green");
    }
}

Solution

  • Here's a dirty way to do it:

    public void actionPerformed(ActionEvent e) 
    {
        if(e.getSource()==button_0)
        {
           System.out.println("red");
           button_1.doClick();
           button_2.doClick();
        }
        else if(e.getSource()==button_1)
        {   
            System.out.println("blue");
        }
        else if(e.getSource()==button_2)
        {
            System.out.println("green");
        }
    }