-1

I have many GUI forms with many buttons on each GUI form. I am wanting to detect when a user clicks on any of these buttons.

My question is this: Should I add code individually to each button, or can I cater to each button press by a public method that is called whenever a button is pressed? If I use a public method (that I would rather do), how does the method detect the button that called the function? Do the buttons have to be a public variable?

Currently I am using this code (that works, I am wondering if I can do it better):

loginButton.addActionListener(new ActionListener() {  
        public void actionPerformed(ActionEvent e)
        {
            System.out.println("You clicked the button");
        }});
Andrew Thompson
  • 168,117
  • 40
  • 217
  • 433
user2351151
  • 725
  • 4
  • 12
  • 16
  • *"I am wanting to detect when a user clicks on any of these buttons."* Then you typically need to figure which button was pressed, in order to make the appropriate action. For that reason it is typically considered better to use one `ActionListener` or `AbstractAction` per button/menu item. – Andrew Thompson May 12 '13 at 11:56
  • Noting that the 1 question has now expanded to 3 questions: It is best to limit it to one question per ..question. And please don't forget to add a question mark.. – Andrew Thompson May 12 '13 at 11:57
  • see if ActionEvent can be used to get target . learn to work with sdk – qwr May 12 '13 at 11:59
  • see this link http://stackoverflow.com/questions/10271924/how-to-implement-and-mantain-multiple-actionlistener – qwr May 12 '13 at 12:00

1 Answers1

1

Should I add code individually to each button, or can I cater to each button press by a public method that is called whenever a button is pressed?

To my mind (and sanity), I'd separate the action listeners/handlers. Generally speaking it keeps the individual actions/code simple and to the point.

Each button/menu can have more then one action listener if need be.

I'd also take a look at the Action API

If I use a public method (that I would rather do), how does the method detect the button that called the function? Do the buttons have to be a public variable?

If your really keen to follow this method, you can pass the ActionEvent to it, which would contain a reference to the source of the action as well as the action command.

Personally, I wouldn't. These kind of methods are notoriously difficult to manage, maintain, debug and update

MadProgrammer
  • 343,457
  • 22
  • 230
  • 366