Java拖曳鼠标实现画线功能的方法

时间:2022-07-03 22:06:02

本文实例主要实现Java拖曳鼠标画线的功能,为了达到画线的功能,分别用implements MouseListener与MouseMotionListener,并且由mousePressed(),mouseReleased()取得鼠标拖曳的开始与结束坐标。这是一个掌握Java鼠标事件的很好的范例。

具体实现代码如下:

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class MouseDemo extends JFrame implements MouseListener,
 MouseMotionListener {
 int flag; //flag=1代表Mouse Moved,flag=2代表Mouse Dragged
 int x = 0;
 int y = 0;
 int startx, starty, endx, endy;//起始坐标与终点坐标
 public MouseDemo() {
 Container contentPane = getContentPane();
 contentPane.addMouseListener(this);
 contentPane.addMouseMotionListener(this);
 setSize(300, 300);
 show();
 addWindowListener(new WindowAdapter() {
  public void windowClosing(WindowEvent e) {
  System.exit(0);
  }
 });
 }
 /*由mousePressed(),mouseReleased()取得鼠标拖曳的开始与结束坐标*/
 public void mousePressed(MouseEvent e) {
 startx = e.getX();
 starty = e.getY();
 }
 public void mouseReleased(MouseEvent e) {
 endx = e.getX();
 endy = e.getY();
 }
 public void mouseEntered(MouseEvent e) {
 }
 public void mouseExited(MouseEvent e) {
 }
 public void mouseClicked(MouseEvent e) {
 }
 /*mouseMoved(),mouseDragged()取得鼠标移动的每一个坐标,并调用repaint()方法*/
 public void mouseMoved(MouseEvent e) {
 flag = 1;
 x = e.getX();
 y = e.getY();
 repaint();
 }
 public void mouseDragged(MouseEvent e) {
 flag = 2;
 x = e.getX();
 y = e.getY();
 repaint();
 }
 public void update(Graphics g) {
 g.setColor(this.getBackground());
 g.fillRect(0, 0, getWidth(), getHeight()); //清除当前的窗口内容
 paint(g);
 }
 public void paint(Graphics g) {
 g.setColor(Color.black);
 if (flag == 1) {
  g.drawString("鼠标坐标:(" + x + "," + y + ")", 10, 50);
  g.drawLine(startx, starty, endx, endy);
 }
 if (flag == 2) {
  g.drawString("拖曳鼠标价坐标:(" + x + "," + y + ")", 10, 50);
  g.drawLine(startx, starty, x, y);
 }
 }
 public static void main(String[] args) {
 new MouseDemo();
 }
}

该程序在画线过程中,拖拽时会显示鼠标坐标。读者还可以根据自身需求对该程序进行修改和完善,使之更加具有实用性。