Search code examples
javaswingjbuttonactionlistener

Identifier expected in an ActionListener


I compiled my code and got the error:

C:\Users\RJ\Desktop>javac  windowTest.java
windowTest.java:17: error: <identifier> expected
        click.addActionListener(new ActionListener(){
                               ^
windowTest.java:22: error: ';' expected
          });
           ^
2 errors

I am still very new to java and would appreciate examples and/or step by step help with explanations. If I move the override I get an error saying I didn't override. My code is:

import java.awt.*;
import java.awt.event.*;
import javax.swing.JFrame;
import javax.swing.*;
import java.util.Scanner;


public class windowTest extends JFrame implements ActionListener{
public static void main(String args[]){
    JFrame frame = new JFrame();
    JLabel label = new JLabel("This is a test.");
        JButton click = new JButton("Test");
    JPanel buttonPan = new JPanel();
    JPanel textPan = new JPanel();
    final JTextField textIn = new JTextField();
    @Override
    click.addActionListener(new ActionListener(){      
    public void actionPerformed(ActionEvent e){
        String text = textIn.getText();
        System.out.println(text);
        }
      });
    buttonPan.setSize(100, 100);
    textIn.setPreferredSize(new Dimension(700, 48));
    textPan.add(textIn);
    buttonPan.add(click);
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setSize(800, 700);
    frame.setLocationRelativeTo(null);
    frame.setLayout(new BorderLayout());
        label.setHorizontalAlignment(JLabel.CENTER);
        label.setVerticalAlignment(JLabel.CENTER);
        frame.add(label, BorderLayout.NORTH);
    frame.add(buttonPan, BorderLayout.SOUTH);
    frame.add(textPan, BorderLayout.CENTER);
    frame.setVisible(true);
    frame.setTitle("Window Test");
       }
    }

Solution

  • First problem, you need to move @Override down, because that is an annotation which applies to a method definition, which is inside the anonymous class.

    click.addActionListener(new ActionListener(){      
    @Override
    public void actionPerformed(ActionEvent e){
        String text = textIn.getText();
        System.out.println(text);
        }
      });
    

    Second problem, your windowTest class claims that it implements ActionListener but does not implement actionPerformed. Since you do not seem to need it, you can just remove that in the declaration.

    public class windowTest extends JFrame{
    ...
    }
    

    With these two changes, your application will compile and run.