Java 小例子:创建一个可拖拽图片的面板

来源:互联网 发布:网络聊天技巧知乎 编辑:程序博客网 时间:2024/06/09 17:06

今天在论坛上看到帖子希望能在 Swing 中实现像拖地图一样拖拽图片。这里是一个最简单的实现,提供了一个基本思路。

[java] view plaincopy
  1. import javax.swing.*;  
  2. import javax.swing.filechooser.FileNameExtensionFilter;  
  3. import java.awt.*;  
  4. import java.awt.event.MouseEvent;  
  5. import java.awt.event.MouseListener;  
  6. import java.awt.event.MouseMotionListener;  
  7. import java.io.File;  
  8.    
  9. /** 
  10.  * 在窗体上拖拽图片。使用方法:双击窗体空白处将会弹出打开图片对话框。打开图片后可以在窗体上拖拽图片。 
  11.  */  
  12. public class DragingFrame extends JFrame {  
  13.    
  14.     /** 
  15.      * 构造函数 
  16.      * 
  17.      * @throws HeadlessException ??? 
  18.      */  
  19.     public DragingFrame() throws HeadlessException {  
  20.         this.setDefaultCloseOperation(EXIT_ON_CLOSE);  
  21.         getContentPane().setLayout(new BorderLayout());  
  22.         getContentPane().add(new ImagePanel(), BorderLayout.CENTER);  
  23.     }  
  24.    
  25.     // 程序入口  
  26.     public static void main(String[] args) throws Exception {  
  27.         UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());  
  28.         DragingFrame frame = new DragingFrame();  
  29.         frame.setSize(400300);  
  30.         frame.setLocation(300300);  
  31.         frame.setResizable(false);  
  32.         frame.setTitle("双击打开图片,然后拖拽");  
  33.         frame.setVisible(true);  
  34.     }  
  35. }  
  36.    
  37. /** 
  38.  * 能够拖拽图片的面板 
  39.  */  
  40. class ImagePanel extends JPanel {  
  41.    
  42.     private DragStatus status = DragStatus.Ready;   // 拖拽状态  
  43.    
  44.     private Image image;                            // 要显示的图片  
  45.    
  46.     private Point imagePosition = new Point(00),  // 图片的当前位置  
  47.    
  48.             imageStartposition = new Point(00),   // 每次拖拽开始时图片的位置(也就是上次拖拽后的位置)  
  49.    
  50.             mouseStartposition;                     // 每次拖拽开始时鼠标的位置  
  51.    
  52.     ImagePanel() {  
  53.         addMouseListener(new MouseListener() {  
  54.    
  55.             // 双击鼠标时打开图片  
  56.             public void mouseClicked(MouseEvent e) {  
  57.                 if (e.getClickCount() == 2) {  
  58.                     openImage();  
  59.                 }  
  60.             }  
  61.    
  62.             // 按下鼠标时,更改状态,并且记录拖拽起始位置。  
  63.             public void mousePressed(MouseEvent e) {  
  64.                 if (status == DragStatus.Ready) {  
  65.                     status = DragStatus.Dragging;  
  66.                     mouseStartposition = e.getPoint();  
  67.                     imageStartposition.setLocation(imagePosition.getLocation());  
  68.                 }  
  69.             }  
  70.    
  71.             // 松开鼠标时更改状态  
  72.             public void mouseReleased(MouseEvent e) {  
  73.                 if (status == DragStatus.Dragging) {  
  74.                     status = DragStatus.Ready;  
  75.                 }  
  76.             }  
  77.    
  78.             public void mouseEntered(MouseEvent e) {  
  79.             }  
  80.    
  81.             public void mouseExited(MouseEvent e) {  
  82.             }  
  83.         });  
  84.    
  85.         addMouseMotionListener(new MouseMotionListener() {  
  86.    
  87.             // Java 有拖拽事件,在这个事件中移动图片位置  
  88.             public void mouseDragged(MouseEvent e) {  
  89.                 if (status == DragStatus.Dragging) {  
  90.                     moveImage(e.getPoint());  
  91.                 }  
  92.             }  
  93.    
  94.             public void mouseMoved(MouseEvent e) {  
  95.             }  
  96.         });  
  97.     }  
  98.    
  99.     /** 
  100.      * 移动图片。实际上画图工作在 paintComponent() 中进行,这里只是计算图片位置,然后调用该方法。 
  101.      * 
  102.      * @param point 当前的鼠标位置 
  103.      */  
  104.     private void moveImage(Point point) {  
  105.         // 图片的当前位置等于图片的起始位置加上鼠标位置的偏移量。  
  106.         imagePosition.setLocation(  
  107.                 imageStartposition.getX() + (point.getX() - mouseStartposition.getX()),  
  108.                 imageStartposition.getY() + (point.getY() - mouseStartposition.getY())  
  109.         );  
  110.         repaint();  
  111.     }  
  112.     
  113.     // 打开图片  
  114.     private void openImage() {  
  115.         System.out.println("Opening image...");  
  116.         File file = createFileChooser().getSelectedFile();  
  117.         if (file != null) {  
  118.             image = Toolkit.getDefaultToolkit().getImage(file.getAbsolutePath());  
  119.             if (image != null) {  
  120.                 this.repaint();  
  121.             }  
  122.         }  
  123.     }  
  124.    
  125.     // 创建打开文件对话框  
  126.     private JFileChooser createFileChooser() {  
  127.         JFileChooser chooser = new JFileChooser();  
  128.         chooser.setDialogTitle("请选择图片文件...");  
  129.         chooser.addChoosableFileFilter(new FileNameExtensionFilter("常用图片格式""jpg""jpeg""gif""png"));  
  130.         chooser.showOpenDialog(this);  
  131.         return chooser;  
  132.     }  
  133.    
  134.     @Override  
  135.     protected void paintComponent(Graphics g) {  
  136.         super.paintComponent(g);  
  137.         if (image != null) {  
  138.             g.drawImage(image, (int) imagePosition.getX(), (int) imagePosition.getY(), this);  
  139.         }  
  140.     }  
  141.    
  142.     private enum DragStatus {  
  143.    
  144.         Ready, Dragging  
  145.     }  
  146. }