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

时间:2021-05-20

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

具体实现代码如下:

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); } }); } 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) { } 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(); }}

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

声明:本页内容来源网络,仅供用户参考;我单位不保证亦不表示资料全面及准确无误,也不保证亦不表示这些资料为最新信息,如因任何原因,本网内容或者用户因倚赖本网内容造成任何损失或损害,我单位将不会负任何法律责任。如涉及版权问题,请提交至online#300.cn邮箱联系删除。

相关文章