📄 mouseeventdemo.java
字号:
import java.awt.*;import java.awt.event.*;public class MouseEventDemo extends Frame { private Canvas canvas; private int startX, startY, endX, endY; public MouseEventDemo() {/* A Canvas object is placed on a Frame and registers a *//* MouseListener and a MouseMotionListener. */ canvas = new Canvas(); canvas.addMouseListener(new MouseHandler()); canvas.addMouseMotionListener(new MouseMotionHandler()); add(canvas); addWindowListener(new WinAdapter()); setBounds(100, 100, 300, 200); setVisible(true); }/* Both the MouseListener and the MouseMotionListener are implemented *//* as extensions of the corresponding adapter class. The purpose of *//* the listeners is to draw a line on the Canvas when the mouse is *//* dragged. When the mouse is pressed, this indicates the starting *//* point of the line. A MouseEvent is generated and sent to the *//* mousePressed() method. The event is used to get the current *//* position of the mouse and set the starting point of the line. */ class MouseHandler extends MouseAdapter { public void mousePressed(MouseEvent event) { startX = event.getX(); startY = event.getY(); endX = startX; endY = startY; } }/* When the mouse is dragged acrosss the Canvas, MouseEvents are *//* generated and set to the mouseDragged() method. A line is drawn *//* on the Canvas that tracks the motion of the mouse. */ class MouseMotionHandler extends MouseMotionAdapter { public void mouseDragged(MouseEvent event) { startX = endX; startY = endY; endX = event.getX(); endY = event.getY(); canvas.getGraphics().drawLine(startX, startY, endX, endY); } } public static void main(String args[]) { MouseEventDemo demo = new MouseEventDemo(); }}/* This makes sure the application terminates if the window is closed */class WinAdapter extends WindowAdapter{ public void windowClosing(WindowEvent event) { System.exit(0); }}
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -