Java拖曳滑鼠實現畫線功能的方法_java

來源:互聯網
上載者:User

本文執行個體主要實現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(); }}

該程式在畫線過程中,拖拽時會顯示滑鼠座標。讀者還可以根據自身需求對該程式進行修改和完善,使之更加具有實用性。

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.