Same ActionListener for Different Buttons – Best Practices

The code works, but I wanted to know whether this was the best way/most recommended way of adding an actionListener when the buttons are performing the same task on different files. I’ve read the debate between making a class implement the ActionLister interface vs. adding an anonymous actionListener class to each button. Neither approach seemed to fit this situation. Here is my code with irrelevant bits left out:

public class ABC {
    public ABC() {
        // constructor here
    }

    private JMenuBar createMenuBar() {
        JMenuBar menuBar = new JMenuBar();
        JMenu menu1 = new JMenu("File");
        menuBar.add(menu1);

        JRadioButtonMenuItem P1 = new JRadioButtonMenuItem();
        JRadioButtonMenuItem P2 = new JRadioButtonMenuItem();

        P1.addActionListener(fileSelectionListener);
        P2.addActionListener(fileSelectionListener);
        P1.setText("P1");
        P2.setText("P2");
        menu1.add(P1);
        menu1.add(P2);

        return menuBar;
    }

    ActionListener fileSelectionListener = new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            JRadioButtonMenuItem source = (JRadioButtonMenuItem) e.getSource();
            String a = source.getText();
            loadFile(a);
        }
    };

    private void loadFile(String a) {
        // implementation of method
    }
    // adding things to the frame
    // main method
}


Download same.actionlistener.for.different.buttons.best.practices.zip
Direct Link


Download


Download same.actionlistener.for.different.buttons.best.practices.zip
Mediafire


Download


Download same.actionlistener.for.different.buttons.best.practices.zip
File.up09.com


Download


Download same.actionlistener.for.different.buttons.best.practices.zip
Uploaded


Download


Download same.actionlistener.for.different.buttons.best.practices.zip
DropBox


Download

Both comments and pings are currently closed.

Comments are closed.