编写一个组合鼠标事件和键盘事件的程序,该程序模拟一个电子白板,用户用鼠标在白板上画画,并通过键盘在上面写字

来源:互联网 发布:redis 显示所有数据库 编辑:程序博客网 时间:2024/04/30 09:52
//<applet code = MouseAndKeyDemo.class height = 100 width = 150>//</applet>import java.applet.Applet;import java.awt.*;import java.awt.event.*;public class MouseAndKeyDemo extends Applet{protected int lastX = 0, lastY = 0;public void init(){addMouseListener(new PositionRecorder());addMouseMotionListener(new LineDrawer());addKeyListener(new CharDrawer());setForeground(Color.blue);setBackground(Color.white);}protected void record(int x, int y){lastX = x;lastY = y;}private class PositionRecorder extends MouseAdapter{public void mouseEnter(MouseEvent e){requestFocus();record(e.getX(),e.getY());}public void mousePressed(MouseEvent e){record(e.getX(),e.getY());}}private class LineDrawer extends MouseMotionAdapter{public void mouseDragged(MouseEvent e){int x = e.getX();int y = e.getY();Graphics g = getGraphics();g.drawLine(lastX, lastY, x, y);record(x, y);}}private class CharDrawer extends KeyAdapter{public void keyTyped(KeyEvent event){String s = String.valueOf(event.getKeyChar());getGraphics().drawString(s, lastX, lastY);record(lastX + 11, lastY);}}}

原创粉丝点击