本文實例主要實現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(); } }
該程序在畫線過程中,拖拽時會顯示鼠標坐標。讀者還可以根據自身需求對該程序進行修改和完善,使之更加具有實用性。