java 圖片的拖動處理

來源:互聯網
上載者:User

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.event.*;

//圖片的拖動效果

public class DragPictureDemo extends JFrame {

   JLabel jlPic; //圖片,用於拖動

   public DragPictureDemo() {
    super("圖片的拖動效果");  //調用父類建構函式
    Icon image=new ImageIcon(this.getClass().getResource("1.jpg"));  //執行個體化表徵圖
  jlPic = new JLabel(image);  //執行個體化帶圖片的標籤
      getContentPane().add(jlPic);  //增加標籤到容器上
     
      DragPicListener listener=new DragPicListener();  //滑鼠事件處理
      jlPic.addMouseListener(listener);  //增加標籤的事件處理
      jlPic.addMouseMotionListener(listener);      
     
      setSize(300,200);  //設定視窗尺寸
      setVisible(true);  //設定視窗為可視
      setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);  //關閉視窗時退出程式
   }
  
   class DragPicListener implements MouseInputListener{  //滑鼠事件處理
      Point p=new Point(0,0); //座標點
    public void mouseMoved(MouseEvent e){}
    public void mouseDragged(MouseEvent e){
        Point newP=SwingUtilities.convertPoint(jlPic,e.getPoint(),jlPic.getParent()); //轉換座標系統
        jlPic.setLocation(jlPic.getX()+(newP.x-p.x),jlPic.getY()+(newP.y-p.y)); //設定標籤的新位置
       p=newP; //更改座標點
    }
    public void mouseReleased(MouseEvent e){}
    public void mouseEntered(MouseEvent e){}
    public void mouseExited(MouseEvent e){}
    public void mouseClicked(MouseEvent e){}
    public void mousePressed(MouseEvent e){
        p=SwingUtilities.convertPoint(jlPic,e.getPoint(),jlPic.getParent()); //得到當前座標點
    }  
   }

    public static void main(String[] args) {
  new DragPictureDemo();
   }
}

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.