Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
246 views
in Technique[技术] by (71.8m points)

java - Replace many "else if" with something else

I am using an ActionListener and have lots of else if statements in order to know which button is pressed and run some code depending on the button.

Is there a way to make the code nicer? I have nearly 10 else if statements following each other, is there something else I could use instead?

Sample of code:

class BtnListener implements ActionListener {   
            @Override
        public void actionPerformed(ActionEvent e) {
            if (e.getSource() == menu.getOpen()) {
                getFile();
            } else if (e.getSource() == btnPlay) {

            } else if (e.getSource() == btnQuit)) {
         }
}

Thanks.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

You can fill Map<Object, Consumer<ActionEvent>> before using of listener, for example in constructor, where key is source and value is a consumer for action event. In action perform just get consumer by key and invoke it.

class BtnListener implements ActionListener {
    Map<Object, Consumer<ActionEvent>> eventsMap = new HashMap<>();

    public BtnListener() {
        eventsMap.put(menu.getOpen(), actionEvent -> this.getFile());
        eventsMap.put(btnPlay, actionEvent -> { //do something
        });
        eventsMap.put(btnQuit, actionEvent -> { //do something else
        });
    }

    @Override
    public void actionPerformed(ActionEvent e) {
        Optional.of(e)
                .map(ActionEvent::getSource)
                .map(eventsMap::get)
                .ifPresent(
                        actionEventConsumer -> actionEventConsumer.accept(e)
                );
    }
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...