2. 编写一程序,运行效果如图所示。以KeyListener接口处理KeyEvent事件,当用户操作键盘时,输入的字符显示在上方文本框中,触发事件的名称显示在下方文本域中。文件保存为T2.java。
时间: 2024-05-15 13:18:05 浏览: 88
您好,感谢您提出的问题。基于您的要求,我给您提供如下答案:
```java
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class T2 extends JFrame implements KeyListener {
private JTextField textField;
private JTextArea textArea;
public T2() {
super("键盘监听");
setLayout(new BorderLayout());
setSize(400, 250);
textField = new JTextField();
textField.addKeyListener(this);
textArea = new JTextArea();
textArea.setEditable(false);
add(textField, BorderLayout.NORTH);
add(textArea, BorderLayout.CENTER);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setVisible(true);
}
public void keyPressed(KeyEvent e) {
String key = getKey(e);
textArea.append("按下 " + key + "\n");
}
public void keyReleased(KeyEvent e) {
String key = getKey(e);
textArea.append("释放 " + key + "\n");
}
public void keyTyped(KeyEvent e) {
char c = e.getKeyChar();
textField.setText(textField.getText() + c);
}
private String getKey(KeyEvent e) {
int keyCode = e.getKeyCode();
switch (keyCode) {
case KeyEvent.VK_ENTER:
return "Enter";
case KeyEvent.VK_SHIFT:
return "Shift";
case KeyEvent.VK_CONTROL:
return "Ctrl";
case KeyEvent.VK_ALT:
return "Alt";
default:
return String.valueOf(e.getKeyChar());
}
}
public static void main(String[] args) {
T2 t2 = new T2();
}
}
```
注意:在编写程序的过程中,请确保代码的准确性,并按照要求实现程序。如果有任何问题,请随时与我联系。
阅读全文
相关推荐


















