Java實現的可選擇及拖拽圖片的面板功能【基於swing組件】,拖拽swing

來源:互聯網
上載者:User

Java實現的可選擇及拖拽圖片的面板功能【基於swing組件】,拖拽swing

本文執行個體講述了Java實現的可選擇及拖拽圖片的面板功能。分享給大家供大家參考,具體如下:

今天在論壇上看到文章希望能在 Swing 中實現像拖地圖一樣拖拽圖片。這裡是一個最簡單的實現,提供了一個基本思路。

import javax.swing.*;import javax.swing.filechooser.FileNameExtensionFilter;import java.awt.*;import java.awt.event.MouseEvent;import java.awt.event.MouseListener;import java.awt.event.MouseMotionListener;import java.io.File;/** * 在表單上拖拽圖片。使用方法:雙擊表單空白處將會彈出開啟圖片對話方塊。開啟圖片後可以在表單上拖拽圖片。 */@SuppressWarnings("serial")public class DragingFrame extends JFrame {  /**   * 建構函式   *   * @throws HeadlessException ???   */  public DragingFrame() throws HeadlessException {    this.setDefaultCloseOperation(EXIT_ON_CLOSE);    getContentPane().setLayout(new BorderLayout());    getContentPane().add(new ImagePanel(), BorderLayout.CENTER);  }  // 程式入口  public static void main(String[] args) throws Exception {    UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());    DragingFrame frame = new DragingFrame();    frame.setSize(400, 300);    frame.setLocation(300, 300);    frame.setResizable(false);    frame.setTitle("www.jb51.net 雙擊開啟圖片,然後拖拽");    frame.setVisible(true);  }}/** * 能夠拖拽圖片的面板 */@SuppressWarnings("serial")class ImagePanel extends JPanel {  private DragStatus status = DragStatus.Ready;  // 拖拽狀態  private Image image;              // 要顯示的圖片  private Point imagePosition = new Point(0, 0), // 圖片的當前位置      imageStartposition = new Point(0, 0),  // 每次拖拽開始時圖片的位置(也就是上次拖拽後的位置)      mouseStartposition;           // 每次拖拽開始時滑鼠的位置  ImagePanel() {    addMouseListener(new MouseListener() {      // 雙擊滑鼠時開啟圖片      public void mouseClicked(MouseEvent e) {        if (e.getClickCount() == 2) {          openImage();        }      }      // 按下滑鼠時,更改狀態,並且記錄拖拽起始位置。      public void mousePressed(MouseEvent e) {        if (status == DragStatus.Ready) {          status = DragStatus.Dragging;          mouseStartposition = e.getPoint();          imageStartposition.setLocation(imagePosition.getLocation());        }      }      // 鬆開滑鼠時更改狀態      public void mouseReleased(MouseEvent e) {        if (status == DragStatus.Dragging) {          status = DragStatus.Ready;        }      }      public void mouseEntered(MouseEvent e) {      }      public void mouseExited(MouseEvent e) {      }    });    addMouseMotionListener(new MouseMotionListener() {      // Java 有拖拽事件,在這個事件中移動圖片位置      public void mouseDragged(MouseEvent e) {        if (status == DragStatus.Dragging) {          moveImage(e.getPoint());        }      }      public void mouseMoved(MouseEvent e) {      }    });  }  /**   * 移動圖片。實際上畫圖工作在 paintComponent() 中進行,這裡只是計算圖片位置,然後調用該方法。   *   * @param point 當前的滑鼠位置   */  private void moveImage(Point point) {    // 圖片的當前位置等於圖片的起始位置加上滑鼠位置的位移量。    imagePosition.setLocation(        imageStartposition.getX() + (point.getX() - mouseStartposition.getX()),        imageStartposition.getY() + (point.getY() - mouseStartposition.getY())    );    repaint();  }  // 開啟圖片  private void openImage() {    System.out.println("Opening image...");    File file = createFileChooser().getSelectedFile();    if (file != null) {      image = Toolkit.getDefaultToolkit().getImage(file.getAbsolutePath());      if (image != null) {        this.repaint();      }    }  }  // 建立開啟檔案對話方塊  private JFileChooser createFileChooser() {    JFileChooser chooser = new JFileChooser();    chooser.setDialogTitle("請選擇圖片檔案...");    chooser.addChoosableFileFilter(new FileNameExtensionFilter("常用圖片格式", "jpg", "jpeg", "gif", "png"));    chooser.showOpenDialog(this);    return chooser;  }  @Override  protected void paintComponent(Graphics g) {    super.paintComponent(g);    if (image != null) {      g.drawImage(image, (int) imagePosition.getX(), (int) imagePosition.getY(), this);    }  }  private enum DragStatus {    Ready, Dragging  }}

運行效果:

聯繫我們

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