Skip to content
Advertisement

Java (latest version) Lambda: replace anonymous inner class by lambda

I have got a class which contains the following:

slider.addChangeListener(new ChangeListener() {
        public void stateChanged(ChangeEvent e) {
            // creating font object and store textarea value font
            Font font = area.getFont();
            // setting size from getting slider value
            float size = ((JSlider) e.getSource()).getValue();
            // setting font size for textarea
            area.setFont(font.deriveFont(size));

        }
    });

VScode Insider tells me to replace the inner class with lambda,

Here is a screenshot if you want to see what I mean, ChangeListener is underline as yellow

So I tried to think of ways and couldn’t come up with any since I am not experienced enough, any one want to help me find other ways how to write this “ChangeListener” please…?

Advertisement

Answer

If you use Intellij IDEA it will do it for you.

slider.addChangeListener(e -> {
            // creating font object and store textarea value font
            Font font = area.getFont();
            // setting size from getting slider value
            float size = ((JSlider) e.getSource()).getValue();
            // setting font size for textarea
            area.setFont(font.deriveFont(size));
    });
6 People found this is helpful
Advertisement