[java]代码库
import java.awt.*;
import java.awt.event.*;
import java.util.*;
public class MyCanvas implements KeyListener, MouseListener {
Canvas c; // 声明一个画布对象
String s = "";
public static void main(String args[]) {
Frame f = new Frame("Canvas");
MyCanvas mc = new MyCanvas();
mc.c = new Canvas();
f.add("Center", mc.c);
f.setSize(150, 150);
mc.c.addMouseListener(mc); // 注册监听器
mc.c.addKeyListener(mc); // 注册监听器
f.setVisible(true);
}
public void mouseClicked(MouseEvent ev) {
System.out.println("MouseClicked");
c.requestFocus();// 获得焦点,表示该窗口将接收用户的键盘和鼠标输入
}
public void keyTyped(KeyEvent ev) {
System.out.println("KeyTyped");
s += ev.getKeyChar(); // 获取每个输入的字符,依次添加到字符串s中
c.getGraphics().drawString(s, 0, 20); // 显示字符串s
}
public void keyPressed(KeyEvent ev) {
System.out.println("KeyPressed");
}
public void keyReleased(KeyEvent ev) {
System.out.println("KeyReleased");
}
public void mousePressed(MouseEvent ev) {
System.out.println("MousePressed");
}
public void mouseReleased(MouseEvent ev) {
System.out.println("MouseReleased");
}
public void mouseEntered(MouseEvent ev) {
System.out.println("MouseEntered");
}
public void mouseExited(MouseEvent ev) {
System.out.println("MouseExited");
}
}