error: <identifier> expected with addActionListener class

error: <identifier> expected with addActionListener class

我在使用这个简单的 Java 代码块时遇到问题。我应该编写一个显示 JFrame 的应用程序,该 JFrame 包含来自 A Christmas Carol 的开场白。当用户单击该按钮时,它将使用 setText() 方法在可用的 JLabel 中显示包含引用的书名。

但是,当我编译时,我收到错误,我的代码行应该为按钮添加 ActionListener。我觉得我缺少一些简单的东西,但我无法放置它。下面是我的源代码。感谢您的帮助。

import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class JBookQuote extends JFrame{
   FlowLayout flow = new FlowLayout();
   JLabel msg1 = new  JLabel("To begin with,");
   JLabel msg2 = new JLabel("Marley was dead.");
   JButton button = new JButton("Click for source");
   JLabel msg3 = new JLabel();
   String title = "**    A Christmas Carol    **";
    public JBookQuote() {
        add(msg1);
        add(msg2);
        add(button);
        add(msg3);
        setLayout(flow);
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    }

    button.addActionListener(new ActionListener(){
    @Override
    public void actionPerformed(ActionEvent e)
    {     
          msg3.setText(title);
    }
});
    public static void main(String[] args) {
        JBookQuote aFrame = new JBookQuote();
        aFrame.setSize(300, 150);
        aFrame.setVisible(true);
    }
}

将动作侦听器添加到按钮的代码不在函数中,我认为您需要在构造函数中使用它。