Registering ActionListener with two Sources

Shashank Anand

Greenhorn

Posts: 26

posted 8 years ago

Hi,

I am working on a Swing application that has 3 ComboBoxes and a Button. I have added ActionListeners to all these components. Now, what I want is when an item is selected from the ComboBox and the Button is pressed, some action should happen. I tried something like : button.addActionListener(this); combo1.addActionListener(this); combo2.addActionListener(this); ... public void actionPerformed (ActionEvent e) { if ((e.getSource()==combo2) && (e.getSource()==button)) { ... do something...} }

But it didnt work. Will anybody please tell me how I can do this?

Philippe Nizer

Greenhorn

Posts: 3

posted 8 years ago

There is a little problem with your code. When you execute e.getSource() the component that performed the action will be returned. But you test if the source is combo2 AND button at the same time. This test always results false, and your code never will be executed. Review your logic. Maybe you want to execute OR instead of AND:

You probably should avoid creating an ActionListener that is added to a host of different components and of necessity tries to do too many things, the so-called "switchboard" ActionListener. For instance, you should never have an ActionListener that responds to both a button press and a JComboBox selection; it just doesn't make sense and is a mess to debug or extend. Much better would be to create small inner classes (or external classes) to deal with each major type of action. [ November 13, 2008: Message edited by: pete stein ]

Michael Dunn

Ranch Hand

Posts: 4632

posted 8 years ago

if I'm reading this right, you click the button and the action depends on which comboBox is the one selected (combo1, combo2 or combo3).

if this sounds right one way might be: actionListener only for the button (so remove getSource()) make the button not focusable setFocusable(false) in actionPerformed get the focusOwner KeyboardFocusManager.getCurrentKeyboardFocusManager().getFocusOwner(); if the focusOwner is combo1, combo2 or combo3, proceed accordingly

this assumes you select an item from one of the comboBoxes (thus giving it the focus), then clicking on the button.

this should work, unless the combo's are editable, in which case their editor components would have the focus

Shashank Anand

Greenhorn

Posts: 26

posted 8 years ago

Hi Michael,

It's a nice solution indeed. Now my GUI is working very well and thanks a lot.