监听练习

import java.applet.*;
import java.awt.*;
import javax.swing.*;
import java.awt.event.*;


public class KeyEventFrame extends JApplet implements KeyListener{
 StringBuffer sb;//创建一个字符缓冲区,用于存放键盘的输入
 char ch;
 JLabel info;//在键盘上添加一个标签,用于显示用户的输入
 
 int x=0;
 public void init(){
  info=new JLabel();
  info.setBackground(Color.blue);
  info.setSize(100,100);
 
  add(info);
  setSize(400,300);
  addKeyListener(this);//添加键盘监听事件
 }
 public void paint(Graphics g){
  if(x==1)
   g.drawOval(30, 20, 100, 100);//画圈
  if(x==2)
   g.drawLine(30, 20, 30,100);//画线
  
 }
 public void keyTyped(KeyEvent e){
  char ch =e.getKeyChar();
  if(ch=='c'||ch=='c'){
   x=1;
   info.setText("画圈");
   repaint();
  }
  else if(ch=='1'||ch=='L'){
   x=2;
   info.setText("画线");
   repaint();
  }
  else{
   ch=e.getKeyChar();
   sb=new StringBuffer();
   sb.append(ch);
   info.setText("请输入的是:"+sb.toString());
  }
 }
 public void keyPressed(KeyEvent e){
  
 }
 public void keyReleased(KeyEvent e){
  
 }

}
 

你可能感兴趣的:(监听练习)