Abgehter Abgehter - 3 months ago 22
Java Question

Lambda expression for LineListener

),

These days I replaced anonymous listener with lambda expressions. For actionlisteners this works fine:

name_button.addActionListener(e->{
gui.game_menu(Saving_Handler.new_game(filenumber, name_field.getText()));
namer.dispose();
});


But with the linelistener i have some difficulties. This is the expression i want to transform:

void sound_mission_start()
{
if (sound) {
try {
Clip clip = AudioSystem.getClip();
clip.open(AudioSystem.getAudioInputStream(new File("rsc/mission_start.wav")));
clip.start();
clip.addLineListener(new LineListener() {
public void update(LineEvent myLineEvent) {
if (myLineEvent.getType() == LineEvent.Type.STOP) {
clip.close();
}
}
});
}
catch (Exception exc) {
exc.printStackTrace(System.out);
}
}
}


How I twist and turn, I'm not able to bring the LineEvent and the if() together.

Answer

You just need to define a lambda expression that takes in a LineEvent and has no return. Since the if statement makes it more than a single statement in the body of the lambda you need to have brackets.

            clip.addLineListener( myLineEvent -> {
                if (myLineEvent.getType() == LineEvent.Type.STOP) {
                    clip.close();
                }
            });