【例9.24】综合鼠标事件和键盘事件处理的程序,模拟一个电子白板,可以用鼠标在上面绘画,可用键盘在上面写字。 import javax.swing.*; import java.awt.*; import java.awt.event.*; public class MouseAndKeyDemo extends JApplet { protected int lastX = 0, lastY = 0; public void init() { setBackground(Color.white); setForeground(Color.blue); addMouseListener(new PositionRecorder()); addMouseMotionListener(new LineDrawer()); addKeyListener(new CharDrawer()); } protected void record(int x, int y) { lastX = x; lastY = y; } private class PositionRecorder extends MouseAdapter{ public void mouseEntered(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(),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); } } } 程序中,在类MouseAndKeyDemo中定义了三个私有嵌套类,两个类对鼠标事件进行处理,一个类对键盘事件进行处理。 程序的运行情况如下图所示。图中的线用鼠标随手画出,文字用键盘输入
剩余63页未读,继续阅读
- 粉丝: 2
- 资源: 15
- 我的内容管理 收起
- 我的资源 快来上传第一个资源
- 我的收益 登录查看自己的收益
- 我的积分 登录查看自己的积分
- 我的C币 登录后查看C币余额
- 我的收藏
- 我的下载
- 下载帮助
会员权益专享
最新资源
- zigbee-cluster-library-specification
- JSBSim Reference Manual
- c++校园超市商品信息管理系统课程设计说明书(含源代码) (2).pdf
- 建筑供配电系统相关课件.pptx
- 企业管理规章制度及管理模式.doc
- vb打开摄像头.doc
- 云计算-可信计算中认证协议改进方案.pdf
- [详细完整版]单片机编程4.ppt
- c语言常用算法.pdf
- c++经典程序代码大全.pdf
- 单片机数字时钟资料.doc
- 11项目管理前沿1.0.pptx
- 基于ssm的“魅力”繁峙宣传网站的设计与实现论文.doc
- 智慧交通综合解决方案.pptx
- 建筑防潮设计-PowerPointPresentati.pptx
- SPC统计过程控制程序.pptx