Add on click listener to Java Swing frame button

Add on click listener to Java Swing frame button

1 Lambda expression

import javax.swing.*;
import java.awt.*;

public class MainFrame extends JFrame {

    private JTextArea textArea;
    private JButton button;

    public MainFrame(){
        super("Hello world");

        textArea = new JTextArea();
        button = new JButton("Click here!");

        button.addActionListener(e -> {
            System.out.println(textArea.getText());
        });

        setLayout(new BorderLayout());
        add(textArea, BorderLayout.CENTER);
        add(button, BorderLayout.SOUTH);

        this.setSize(400, 400);
        this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        this.setVisible(true);
    }

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

2 Anonymous class

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

public class MainFrame extends JFrame {

    private JTextArea textArea;
    private JButton button;

    public MainFrame(){
        super("Hello world");

        textArea = new JTextArea();
        button = new JButton("Click here!");

        button.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                System.out.println(textArea.getText());
            }
        });

        setLayout(new BorderLayout());
        add(textArea, BorderLayout.CENTER);
        add(button, BorderLayout.SOUTH);

        this.setSize(400, 400);
        this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        this.setVisible(true);
    }

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