欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

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

程序员文章站 2024-02-27 20:09:33
本文实例主要实现java拖曳鼠标画线的功能,为了达到画线的功能,分别用implements mouselistener与mousemotionlistener,并且由mou...

本文实例主要实现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);
  }
 });
 }
 /*由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();
 }
}

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