Java:Actionlistener标识符预期错误

时间:2015-11-16 06:22:21

标签: java override actionlistener

我正在尝试使用ActionListener创建一个方法来从文本字段中的用户获取输入。但是,当我编译时,我不断收到此错误:

Quiz.java:36: error: <identifier> expected
  tfInput.addActionListener(new  a ActionListener() {

代码:

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

public class Quiz implements ActionListener {

private static Label lblInput;         
private static TextField tfInput;  
private static String cityIn;
private static TextField tfOutput;       

public void europe() {
   JFrame frame = new JFrame();      
   frame.setLayout(null);

   lblInput = new Label("Skriv in huvudstaden i : "); // Construct Label
   lblInput.setBounds(40,30,300,40);
   frame.add(lblInput);

   tfInput = new TextField(10);
   tfInput.setBounds(40,70,300,40);
   frame.add(tfInput);     

   tfOutput = new TextField(10); // allocate TextField
   tfOutput.setEditable(false);  // read-only
   tfOutput.setBounds(100,30,300,40);
   frame.add(tfOutput);

   frame.setTitle("Europa"); 
   frame.setSize(375, 150);
   frame.setLocationRelativeTo(null);
   frame.setVisible(true);

}

   tfInput.addActionListener(new  ActionListener() {

      @Override
      public void actionPerformed(ActionEvent e) {        
         String inLand = tfInput.getText(); 

      }       
   });   
 }

我无法理解可能导致这种情况的原因。

1 个答案:

答案 0 :(得分:0)

尝试这种方式可能:

  frame.setVisible(true);
  tfInput.addActionListener(new  ActionListener() {

       @Override
       public void actionPerformed(ActionEvent e) {        
         String inLand = tfInput.getText(); 
       }       
    });   
  }
 }