本文實例主要實作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代表MouseListener { 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); showMouseMotionListener(this); setSize(300, 300); show(); 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(); }}
程式在畫線過程中,拖曳時會顯示滑鼠座標。讀者也可以根據自身需求對該程式進行修改和完善,使其更具實用性。