Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to Perform Multiple Action on Single Click in Java Swing

I have a Question on performing other buttons action with single button click. Some example code for three buttons:

JButton a = new JButton("a");
a.addActionListener(new ActionListener() {
  public void actionPerformed(ActionEvent e) {
    // Action of a is Here                   
  }
});

JButton b = new JButton("b");
b.addActionListener(new ActionListener() {
  public void actionPerformed(ActionEvent e) {
    // Action of b is Here                   
  }
});

Those should come together, like:

JButton c = new JButton("c");
c.addActionListener(new ActionListener() {
  public void actionPerformed(ActionEvent e) {
    // Action of c is Here
    // Action of a 
    // Action of b              
   }
});

In the above example i have three buttons a,b,c with its own action; but as you can see, C also has to run the actions of A and B. What are good ways to address this?

like image 417
Intact Abode Avatar asked Feb 05 '23 11:02

Intact Abode


1 Answers

The other answers are all correct, but there is one important aspect missing here: be careful about dong "too many things" on the AWT event dispatcher thread.

Meaning: when a button is clicked, an event gets created, and the UI framework uses that special thread to trigger the registered listeners. If one of the listeners now decides to do a intensive computation ... the UI event threads stays busy doing "that". And while doing "that thing"; this thread isn't available to dispatch any other UI event.

So, this is "not only" about creating methodA(), methodB(), methodC() and invoking them in your third action listener. It is also about understanding if combining multiple calls becomes subject to "I should better run those things in a separate thread; to not block the event dispatcher thread".

In that sense: the other answers tell you where to go from here; but be really careful about the "amount of activity" that your "joined actions" button is about to create!

like image 106
GhostCat Avatar answered Feb 07 '23 19:02

GhostCat