java 面板實現圖片的拖拽,效果還不錯。代碼直接拷過去就能看到效果了。 java
package com.conmon.myTest; import java.awt.Color; import java.awt.event.MouseAdapter; import java.awt.event.MouseEvent; import java.awt.event.MouseMotionListener; import javax.swing.BorderFactory; import javax.swing.Icon; import javax.swing.ImageIcon; import javax.swing.JFrame; import javax.swing.JLabel; public class TestMoveImage { static int x,y; private static int num=0; private static Icon icon=null; public static void main(String[] args) throws Exception{ JFrame f = new JFrame(); f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); f.getContentPane().setLayout(null);//這個要設置成 null //圖片 icon = new ImageIcon("F:/1353411350203.jpg"); //注:用斜杆系統會默認幫你轉化爲反斜槓,若是要用反斜槓則要寫成:F:\\1353411350203.jpg JLabel l = new JLabel(icon); //建立具備指定圖像的 JLabel 實例。 l.setSize(icon.getIconWidth(),icon.getIconHeight());//設置面板的寬度和高度 l.setBorder(BorderFactory.createLineBorder(Color.red));//給圖片加上紅色外框 f.getContentPane().add(l); f.setSize(180,180); f.setVisible(true); l.addMouseListener(new MouseAdapter(){ public void mousePressed(MouseEvent e){ x=e.getX(); y=e.getY(); } }); l.addMouseMotionListener(new MouseMotionListener(){ public void mouseDragged(MouseEvent e) { JLabel l = (JLabel)e.getSource(); l.setLocation(l.getX()+e.getX()-x,l.getY()+e.getY()-y); } public void mouseMoved(MouseEvent e) {} }); } }