Adding ActionListeners and calling methods in other classes

前端 未结 1 893
轻奢々
轻奢々 2020-12-22 06:38

I need some help, as I am quite the noob.

The program im trying to make here, used to work for my intentions, but as I tried to make my code more readable, I ran int

相关标签:
1条回答
  • 2020-12-22 07:25

    Despite the tutorials' examples show the use of listeners implemented in the way you do, IMHO is more useful use anonymous inner classes to implement listeners. For instance:

    cfgButton.addActionListener(new ActionListener() {
        @Override
        public void actionPerfomed(ActionEvent e) {
            // do the stuff related to cfgButton here
        }
    };
    
    newButton.addActionListener(new ActionListener() {
        @Override
        public void actionPerfomed(ActionEvent e) {
            // do the stuff related to newButton here
        }
    };
    
    exitButton.addActionListener(new ActionListener() {
        @Override
        public void actionPerfomed(ActionEvent e) {
            // do the stuff related to exitButton here
        }
    };
    

    This approach has these advantages:

    • Listeners logic is well separated.
    • You don't need those nested if blocks asking who is the source of the event.
    • If you add a new button you don't have to modify your listener. Just add a new one.

    Of course it depends on the case. If the behaviour will be the same for a set of components (for instance radio buttons or check boxes) then it makes sense have only one listener and use EventObject.getSource() to work with the event's source. This approach is suggested here and exemplified here. Note the examples also make use of anonymous inner classes in this way:

    ActionListener actionListener = new ActionListener() {
        @Override
        public void actionPerformed(ActionEvent e) {
            // do something here
        }
    };
    
    0 讨论(0)
提交回复
热议问题