本文概述
- KeyListener接口的方法
- Java KeyListener示例
- Java KeyListener示例2:计算单词和字符
KeyListener接口的方法 下面给出了在KeyListener接口中找到的3种方法的签名:
public abstract void keyPressed(KeyEvent e);
public abstract void keyReleased(KeyEvent e);
public abstract void keyTyped(KeyEvent e);
Java KeyListener示例
import java.awt.*;
import java.awt.event.*;
public class KeyListenerExample extends Frame implements KeyListener{
Label l;
TextArea area;
KeyListenerExample(){l=new Label();
l.setBounds(20, 50, 100, 20);
area=new TextArea();
area.setBounds(20, 80, 300, 300);
area.addKeyListener(this);
add(l);
add(area);
setSize(400, 400);
setLayout(null);
setVisible(true);
}
public void keyPressed(KeyEvent e) {
l.setText("Key Pressed");
}
public void keyReleased(KeyEvent e) {
l.setText("Key Released");
}
public void keyTyped(KeyEvent e) {
l.setText("Key Typed");
} public static void main(String[] args) {
new KeyListenerExample();
}
}
输出:
文章图片
Java KeyListener示例2:计算单词和字符
import java.awt.*;
import java.awt.event.*;
public class KeyListenerExample extends Frame implements KeyListener{
Label l;
TextArea area;
KeyListenerExample(){l=new Label();
l.setBounds(20, 50, 200, 20);
area=new TextArea();
area.setBounds(20, 80, 300, 300);
area.addKeyListener(this);
add(l);
add(area);
setSize(400, 400);
setLayout(null);
setVisible(true);
}
public void keyPressed(KeyEvent e) {}
public void keyReleased(KeyEvent e) {
String text=area.getText();
String words[]=text.split("\\s");
l.setText("Words: "+words.length+" Characters:"+text.length());
}
public void keyTyped(KeyEvent e) {} public static void main(String[] args) {
new KeyListenerExample();
}
}
【Java KeyListener接口】输出:
文章图片
推荐阅读
- BorderLayout(LayoutManagers)
- Java JDBC教程介绍
- Java ItemListener接口
- 如何在Java中关闭AWT窗口
- Java AWT工具包
- Java AWT TextField
- Java AWT TextArea
- Java AWT滚动条
- Java AWT PopupMenu