am creating a calculator using net beans IDE so yeah i made 0 - 9 buttons.. although seems like i dont want to create an event handler on each number cause it's like a waste of time.. is it possible that the zero to nine button can only trigger one event?

if it is possible, can you show me how?? annndd also I would like to know which number triggered the button

Recommended Answers

All 4 Replies

Yes, just create an inner class that implements ActionListener. Then in the actionPerformed( ActionEvent e ) method you can call e.getSource() to find the button that was pressed and act accordingly. Then just add a single instance of your inner class to each button.

Hope this helps :)

doesn't even have to be an inner class :)

inner classes are nice because they can implicitly access the fields of the enclosing instance, so if your buttons were pointed to by a field, then you can use an inner class to access them

they're also a problem in that they prevent decoupling of responsibilities.

When they are short they're fine, but go to top level classes when they get longer than a few lines.

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.