我有这个代码使用一个文本字段,程序从该文本字段接收用户的输入,所以我试图将ActionListener添加到我的文本字段输入。但是,当我编译时,我收到此错误:
Quiz.java:5: error: Quiz is not abstract and does not override abstract method actionPerformed(ActionEvent) in ActionListener
public class Quiz implements ActionListener {
代码:
public class Quiz implements ActionListener {
private static Label lblInput;
private static TextField tfInput;
private static String cityIn;
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);
tfInput.addActionListener(this);
frame.setTitle("Europa");
frame.setSize(375, 150);
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
}
答案 0 :(得分:1)
您必须覆盖actionPerformed(ActionEvent e)
方法:
public class Quiz implements ActionListener {
private static Label lblInput;
private static TextField tfInput;
private static String cityIn;
public void europe() {
....
}
@Override
public void actionPerformed(ActionEvent e) {
// Your code
}
}
编辑: (第二种方式)
您可以使用自定义ActionListener
处理文本字段中的事件:
public class Quiz implements ActionListener {
private static Label lblInput;
private static TextField tfInput;
private static String cityIn;
public void europe() {
....
tfInput.addActionListener(new CustomActionListener());
...
}
@Override
public void actionPerformed(ActionEvent e) {
// Your code
}
}
class CustomActionListener implements ActionListener {
@Override
public void actionPerformed(ActionEvent e) {
// Your code
}
}