Lambda expression: Use Jframe to demonstrate the simplicity of the code with and without lambda

Lambda expression: Use Jframe to demonstrate the simplicity of the code with and without lambda

introduction

In java8, a very important feature has been introduced. This is Lambda expressions, which can make our code more concise and readable. It allows functions to be used as parameters. It is a functional programming-oriented idea. To a certain extent, it can make the code look more concise.
But the disadvantage is that Java programmers generally use object-oriented thinking for programming. In a sense, Lambda does not fit the object-oriented way of thinking.

text

Use Jfame as an example to demonstrate the code when the JButton button listens to events, comparing the simplicity of using lambda and not using lambda

package com.moonl.jvm.jframe;


import javax.swing.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

public class Jframe extends JFrame {
    
    


    public Jframe() {
    
    
        this.setBounds(400, 400, 450, 450);
        this.setTitle("lambda test");
        this.setVisible(true);
        this.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);

        JPanel jPanel = new JPanel();
        jPanel.setBounds(400,400,0,0);
        this.add(jPanel);
        //
        jPanel.add(_createButton("偷袭", "大意了"));
        jPanel.add(_createButtonLambda("我没有闪", "年轻人不讲武德"));
    }

    /**
     * 按钮控件监听
     * @param name
     * @param msg
     * @return
     */
    public JButton _createButton(String name, String msg) {
    
    

        JButton jb = new JButton(name);
        jb.addActionListener(new ActionListener() {
    
    
            @Override
            public void actionPerformed(ActionEvent e) {
    
    
                System.out.println(msg);
            }
        });
        return jb;
    }

    /**
     * 按钮控件使用lambda监听
     * @param name
     * @param msg
     * @return
     */
    public JButton _createButtonLambda(String name, String msg) {
    
    
        JButton jb = new JButton(name);
        jb.addActionListener(event -> System.out.println(msg));
        return jb;
    }

    public static void main(String[] args) {
    
    
        new Jframe();
    }
}

The code has been posted, and you can see that the syntax format of lambda is indeed much more concise for code readable.
Now we take a look at the effect of operation:

The program runs
Now, we click on the two buttons separately.
Effect output
Now we can see that the listening events of the two buttons have printed the msg we want.
The effect is the same.

postscript

Dear students who have read this article, in the actual development process, which method would you use to write code?
Would you consider trying to use lambda syntax?

Guess you like

Origin blog.csdn.net/liaoyue11/article/details/110955671
Recommended