JAVA中的图形用户界面示例

时间:2012-07-09 09:45:44
【文件属性】:

文件名称:JAVA中的图形用户界面示例

文件大小:1.47MB

文件格式:PPT

更新时间:2012-07-09 09:45:44

容器、组件、布局和观感、监听器 适配器类 注册方法

【例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中定义了三个私有嵌套类,两个类对鼠标事件进行处理,一个类对键盘事件进行处理。 程序的运行情况如下图所示。图中的线用鼠标随手画出,文字用键盘输入


网友评论

  • 资源可用,有一定参考价值,谢谢