I have a JPanel with many objects, and one main action that can be performed: a calculation. There is a button to do this, but also a JTextField and other components in which the user might want to press enter in. For example, if you are selecting something from a JComboBox and press enter, the calculation will happen. Is there an easy way to add such a listener to all the contents from a JPanel, instead of adding actionListeners to every single component?
JPanel
extends JComponent
, that inherits Container
. You can use getComponents()
. You get a Component[]
array, which you can loop through and add for each component, that is a subclass of Component
like Button
, and add the same ActionListener
for each component. See http://docs.oracle.com/javase/6/docs/api/java/awt/Component.html