【发布时间】:2017-04-06 22:37:30
【问题描述】:
我正在尝试创建一个 keylistener 来检测用户何时点击“enter”键,但每次编译时都会收到错误消息:
NameBox.java:6: error: NameBox is not abstract and does not override
abstract method keyPressed(KeyEvent) in KeyListener
public class NameBox extends JFrame implements KeyListener
^
在下面提供的课程中,我确信我正确地实现了正确的关键监听器,但显然我没有。如果有人能解释为什么我仍然会收到这个错误,那就太棒了!
import java.util.*;
import java.io.*;
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class NameBox extends JFrame implements KeyListener
{
String userWord = "";
JTextField userInput = new JTextField(20);
JButton submit = new JButton("Submit");
public NameBox()
{
super("Enter your name");
JPanel centerPanel = new JPanel(new FlowLayout(FlowLayout.CENTER, 15, 15));
setSize(400, 200);
setDefaultCloseOperation(EXIT_ON_CLOSE);
setLocationRelativeTo(null);
submit.addKeyListener(new KeyAdapter(){
public void keyPressed(KeyEvent evt)
{
if(evt.getKeyCode() == KeyEvent.VK_ENTER)
{
submitAction();
}
}
});
centerPanel.add(userInput);
JPanel southPanel = new JPanel(new FlowLayout(FlowLayout.CENTER, 15, 15));
southPanel.add(submit);
Box theBox = Box.createVerticalBox();
theBox.add(Box.createVerticalStrut(100));
theBox.add(centerPanel);
theBox.add(Box.createVerticalStrut(200));
theBox.add(southPanel);
add(theBox);
}
private void submitAction()
{
userWord = userInput.getText();
}
public static void main(String[] args)
{
new NameBox().setVisible(true);
}
@Override
public void keyTyped(KeyEvent e){}
@Override
public void keyReleased(KeyEvent e){}
}
【问题讨论】:
-
错误不言自明,您已承诺实现
KeyListener接口指定的合约,但未能提供实现 - 相反,出于某种奇怪的原因,您添加了一个KeyListener到按钮,而不是使用为其设计的ActionListener -
我强烈建议你看看How to use buttons,How to write an action listener,如果出于某种奇怪的原因,你仍然需要监控关键事件,How to Use Key Bindings 因为
KeyListener只是一个在...代码中绘制
标签: java swing keylistener