Hey all.I got a question about the use of action listeners.Actually its more about actionEvents.Anyway,my question is: Supposing i have a frame with four buttons,say "A","B","C","D". I want each time i press a different button something different to appear on TextField.I know i can make 4 different button subclasses,each with a different actionPerformed.Or i can make 4 different actionListeners.But i wonder if there is a simpler way to do that,in case i eg have 40 buttons. Can i somehow find out what was the "actionEvent" aka which of the same-but differently named-buttons was pushed?Thanks!

Recommended Answers

All 5 Replies

Hi, I think that you can get the button that was clicked using the source property of the ActionEvent object that you receive inside your listener.

Also you can create a subclass of Button with a property that contains the text that you want to appear on the TextField.

This way you can get the button that was clicked and cast it to your subclass. Afterwars you can get the text property and update the TextField.

Regards,
Komyg

You can get the source of the event from the ActionEvent itself eg e.getSource() - this will be the particular button that was pressed.

Also you can create a subclass of Button with a property that contains the text that you want to appear on the TextField.

JButtons have valuable "client property" attribute that you can use to store/retrieve anything you like for that particular button
putClientProperty(Object key, Object value) / getClientProperty(Object key)
this is a better way to associate some text with a button, rather than sub-classing.

awesome and very fast answers all of them. Ill try the James' Client solution and see how it goes.Thanks!!

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.