问题 问答题

本题的功能是监听键盘键的敲击,并显示在窗口中。
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class java3 extends JFrame extends KeyListener

private String linel="",line2="";
private String line3="";
private JTextArea textArea;
public java3()

super("java3");
textArea=new JTextArea(10,15);
textArea.setText("Press any key on the keyboard...");
textArea.setEnabled(false);
addKeyListener(this);
getContentPane().add(textArea);
setSize(350,100);
show();

public void keyPressed(KeyEvent e)

line1="Key pressed:"+e.getKeyText(e.getKeyCode());
setLines2and3(e);

public void keyReleased(KeyEvent e)

linel="Key released:"+e.getKeyText(e.getKeyCode());
setLines2and3(e);

public void keyTyped(KeyEvent e)

Line1="Key typed:"+e.getKeychar();
setLines2and3(e);

private void setLines2and3(KeyEvent e)

line2="This key is"+(e.isActionKey()"":"not")+"an action key";
String temp=e.getKeyModifiersText(e.getModifiers());
line3="Modifier keys pressed:"+(temp.equals("")"none":temp);
textArea.setText(line1+"n"+line2+"\n"+line3+"n");

public static void main(String args[])

java3 app=new java3();
addWindowListener(new Windowadapterl()

public void windowClosing(WindowEvent e)

System.exit(0);

);

答案

参考答案:第1处:extends JFrame implements KeyListener
第2处:line1="Key typed:"+e.getKeyChar()
第3处:app.addWindowListener(new WindowAdapter())

解析: 第1处实现接口应用implements;第2处Java是大小写敏感的,获得键盘值应使用getKeyChar()方法;第3处窗体级监听器应注册给接收类。

单项选择题
选择题