Question

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");
        }});
Was it helpful?

Solution

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

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top