亲宝软件园·资讯

展开

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

人气:0
想了解Java拖曳鼠标实现画线功能的方法的相关内容吗,在本文为您仔细讲解Java拖曳鼠标实现画线功能的相关知识和一些Code实例,欢迎阅读和指正,我们先划重点:Java,拖曳,鼠标,画线,功能,下面大家一起来学习吧。

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

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

加载全部内容

相关教程
猜你喜欢
用户评论