在java中拖放图像

前端之家收集整理的这篇文章主要介绍了在java中拖放图像前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我想要的是将图像从一个JPanel拖放到另一个JPanel.我能够通过使用dnd库来实现.但是我坚持下去因为我不能从我放下它的面板(从放置目标)拖动图像.这意味着droptarget也需要充当dragSource.我是怎么做到的

解决方法

也许这有助于:

http://www.java2s.com/Code/Java/Swing-JFC/DragPictureDemo2.htm

  1. /* From http://java.sun.com/docs/books/tutorial/index.html */
  2.  
  3. /*
  4. * Copyright (c) 2006 Sun Microsystems,Inc. All Rights Reserved.
  5. *
  6. * Redistribution and use in source and binary forms,with or without
  7. * modification,are permitted provided that the following conditions are met:
  8. *
  9. * -Redistribution of source code must retain the above copyright notice,this
  10. * list of conditions and the following disclaimer.
  11. *
  12. * -Redistribution in binary form must reproduce the above copyright notice,* this list of conditions and the following disclaimer in the documentation
  13. * and/or other materials provided with the distribution.
  14. *
  15. * Neither the name of Sun Microsystems,Inc. or the names of contributors may
  16. * be used to endorse or promote products derived from this software without
  17. * specific prior written permission.
  18. *
  19. * This software is provided "AS IS," without a warranty of any kind. ALL
  20. * EXPRESS OR IMPLIED CONDITIONS,REPRESENTATIONS AND WARRANTIES,INCLUDING
  21. * ANY IMPLIED WARRANTY OF MERCHANTABILITY,FITNESS FOR A PARTICULAR PURPOSE
  22. * OR NON-INFRINGEMENT,ARE HEREBY EXCLUDED. SUN MIDROSYSTEMS,INC. ("SUN")
  23. * AND ITS LICENSORS SHALL NOT BE LIABLE FOR ANY DAMAGES SUFFERED BY LICENSEE
  24. * AS A RESULT OF USING,MODIFYING OR DISTRIBUTING THIS SOFTWARE OR ITS
  25. * DERIVATIVES. IN NO EVENT WILL SUN OR ITS LICENSORS BE LIABLE FOR ANY LOST
  26. * REVENUE,PROFIT OR DATA,OR FOR DIRECT,INDIRECT,SPECIAL,CONSEQUENTIAL,* INCIDENTAL OR PUNITIVE DAMAGES,HOWEVER CAUSED AND REGARDLESS OF THE THEORY
  27. * OF LIABILITY,ARISING OUT OF THE USE OF OR INABILITY TO USE THIS SOFTWARE,* EVEN IF SUN HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES.
  28. *
  29. * You acknowledge that this software is not designed,licensed or intended
  30. * for use in the design,construction,operation or maintenance of any
  31. * nuclear facility.
  32. */
  33.  
  34. /*
  35. * DragPictureDemo2.java is a 1.4 example that requires the following files:
  36. * Picture.java DTPicture.java PictureTransferHandler.java
  37. * TransferActionListener.java images/Maya.jpg images/Anya.jpg images/Laine.jpg
  38. * images/Cosmo.jpg images/Adele.jpg images/Alexi.jpg
  39. */
  40.  
  41. import java.awt.BorderLayout;
  42. import java.awt.Color;
  43. import java.awt.Dimension;
  44. import java.awt.Graphics;
  45. import java.awt.GridLayout;
  46. import java.awt.Image;
  47. import java.awt.KeyboardFocusManager;
  48. import java.awt.datatransfer.DataFlavor;
  49. import java.awt.datatransfer.Transferable;
  50. import java.awt.datatransfer.UnsupportedFlavorException;
  51. import java.awt.event.ActionEvent;
  52. import java.awt.event.ActionListener;
  53. import java.awt.event.FocusEvent;
  54. import java.awt.event.FocusListener;
  55. import java.awt.event.InputEvent;
  56. import java.awt.event.KeyEvent;
  57. import java.awt.event.MouseEvent;
  58. import java.awt.event.MouseListener;
  59. import java.awt.event.MouseMotionListener;
  60. import java.beans.PropertyChangeEvent;
  61. import java.beans.PropertyChangeListener;
  62. import java.io.File;
  63. import java.io.IOException;
  64. import java.net.MalformedURLException;
  65.  
  66. import javax.accessibility.Accessible;
  67. import javax.swing.Action;
  68. import javax.swing.ActionMap;
  69. import javax.swing.BorderFactory;
  70. import javax.swing.ImageIcon;
  71. import javax.swing.InputMap;
  72. import javax.swing.JComponent;
  73. import javax.swing.JFrame;
  74. import javax.swing.JMenu;
  75. import javax.swing.JMenuBar;
  76. import javax.swing.JMenuItem;
  77. import javax.swing.JPanel;
  78. import javax.swing.KeyStroke;
  79. import javax.swing.TransferHandler;
  80.  
  81. //A version of DragPictureDemo that creates an
  82. //Edit menu with cut/copy/paste actions.
  83. //This demo adds a class called TransferActionDemo
  84. //that transfers the cut/copy/paste menu action
  85. //to the currently focused component.
  86. public class DragPictureDemo2 extends JPanel {
  87.  
  88. DTPicture pic1,pic2,pic3,pic4,pic5,pic6,pic7,pic8,pic9,pic10,pic11,pic12;
  89.  
  90. static String mayaString = "Maya";
  91.  
  92. static String anyaString = "Anya";
  93.  
  94. static String laineString = "Laine";
  95.  
  96. static String cosmoString = "Cosmo";
  97.  
  98. static String adeleString = "Adele";
  99.  
  100. static String alexiString = "Alexi";
  101.  
  102. PictureTransferHandler picHandler;
  103.  
  104. public DragPictureDemo2() {
  105. super(new BorderLayout());
  106. picHandler = new PictureTransferHandler();
  107. //Since we are using keyboard accelerators,we don't
  108. //need the component to install its own input map
  109. //bindings.
  110. DTPicture.setInstallInputMapBindings(false);
  111.  
  112. JPanel mugshots = new JPanel(new GridLayout(4,3));
  113. pic1 = new DTPicture(createImageIcon("images/" + mayaString + ".jpg",mayaString).getImage());
  114. pic1.setTransferHandler(picHandler);
  115. mugshots.add(pic1);
  116. pic2 = new DTPicture(createImageIcon("images/" + anyaString + ".jpg",anyaString).getImage());
  117. pic2.setTransferHandler(picHandler);
  118. mugshots.add(pic2);
  119. pic3 = new DTPicture(createImageIcon("images/" + laineString + ".jpg",laineString).getImage());
  120. pic3.setTransferHandler(picHandler);
  121. mugshots.add(pic3);
  122. pic4 = new DTPicture(createImageIcon("images/" + cosmoString + ".jpg",cosmoString).getImage());
  123. pic4.setTransferHandler(picHandler);
  124. mugshots.add(pic4);
  125. pic5 = new DTPicture(createImageIcon("images/" + adeleString + ".jpg",adeleString).getImage());
  126. pic5.setTransferHandler(picHandler);
  127. mugshots.add(pic5);
  128. pic6 = new DTPicture(createImageIcon("images/" + alexiString + ".jpg",alexiString).getImage());
  129. pic6.setTransferHandler(picHandler);
  130. mugshots.add(pic6);
  131.  
  132. //These six components with no pictures provide handy
  133. //drop targets.
  134. pic7 = new DTPicture(null);
  135. pic7.setTransferHandler(picHandler);
  136. mugshots.add(pic7);
  137. pic8 = new DTPicture(null);
  138. pic8.setTransferHandler(picHandler);
  139. mugshots.add(pic8);
  140. pic9 = new DTPicture(null);
  141. pic9.setTransferHandler(picHandler);
  142. mugshots.add(pic9);
  143. pic10 = new DTPicture(null);
  144. pic10.setTransferHandler(picHandler);
  145. mugshots.add(pic10);
  146. pic11 = new DTPicture(null);
  147. pic11.setTransferHandler(picHandler);
  148. mugshots.add(pic11);
  149. pic12 = new DTPicture(null);
  150. pic12.setTransferHandler(picHandler);
  151. mugshots.add(pic12);
  152.  
  153. setPreferredSize(new Dimension(450,630));
  154. add(mugshots,BorderLayout.CENTER);
  155. setBorder(BorderFactory.createEmptyBorder(20,20,20));
  156. }
  157.  
  158. //Create an Edit menu to support cut/copy/paste.
  159. public JMenuBar createMenuBar() {
  160. JMenuItem menuItem = null;
  161. JMenuBar menuBar = new JMenuBar();
  162. JMenu mainMenu = new JMenu("Edit");
  163. mainMenu.setMnemonic(KeyEvent.VK_E);
  164. TransferActionListener actionListener = new TransferActionListener();
  165.  
  166. menuItem = new JMenuItem("Cut");
  167. menuItem.setActionCommand((String) TransferHandler.getCutAction()
  168. .getValue(Action.NAME));
  169. menuItem.addActionListener(actionListener);
  170. menuItem.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_X,ActionEvent.CTRL_MASK));
  171. menuItem.setMnemonic(KeyEvent.VK_T);
  172. mainMenu.add(menuItem);
  173. menuItem = new JMenuItem("Copy");
  174. menuItem.setActionCommand((String) TransferHandler.getCopyAction()
  175. .getValue(Action.NAME));
  176. menuItem.addActionListener(actionListener);
  177. menuItem.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_C,ActionEvent.CTRL_MASK));
  178. menuItem.setMnemonic(KeyEvent.VK_C);
  179. mainMenu.add(menuItem);
  180. menuItem = new JMenuItem("Paste");
  181. menuItem.setActionCommand((String) TransferHandler.getPasteAction()
  182. .getValue(Action.NAME));
  183. menuItem.addActionListener(actionListener);
  184. menuItem.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_V,ActionEvent.CTRL_MASK));
  185. menuItem.setMnemonic(KeyEvent.VK_P);
  186. mainMenu.add(menuItem);
  187.  
  188. menuBar.add(mainMenu);
  189. return menuBar;
  190. }
  191.  
  192. /** Returns an ImageIcon,or null if the path was invalid. */
  193. protected static ImageIcon createImageIcon(String path,String description) {
  194. try {
  195. File imageURL = new File(path);
  196.  
  197. if (imageURL == null) {
  198. System.err.println("Resource not found: " + path);
  199. return null;
  200. } else {
  201. return new ImageIcon(imageURL.toURI().toURL(),description);
  202. }
  203. } catch( MalformedURLException e ) {
  204. e.printStackTrace();
  205. }
  206. return null;
  207. }
  208.  
  209. /**
  210. * Create the GUI and show it. For thread safety,this method should be
  211. * invoked from the event-dispatching thread.
  212. */
  213. private static void createAndShowGUI() {
  214. //Make sure we have nice window decorations.
  215. JFrame.setDefaultLookAndFeelDecorated(true);
  216.  
  217. //Create and set up the window.
  218. JFrame frame = new JFrame("DragPictureDemo2");
  219. frame.setDefaultCloSEOperation(JFrame.EXIT_ON_CLOSE);
  220.  
  221. //Create and set up the menu bar and content pane.
  222. DragPictureDemo2 demo = new DragPictureDemo2();
  223. frame.setJMenuBar(demo.createMenuBar());
  224. demo.setOpaque(true); //content panes must be opaque
  225. frame.setContentPane(demo);
  226.  
  227. //Display the window.
  228. frame.pack();
  229. frame.setVisible(true);
  230. }
  231.  
  232. public static void main(String[] args) {
  233. //Schedule a job for the event-dispatching thread:
  234. //creating and showing this application's GUI.
  235. javax.swing.SwingUtilities.invokeLater(new Runnable() {
  236. public void run() {
  237. createAndShowGUI();
  238. }
  239. });
  240. }
  241. }
  242.  
  243. /*
  244. * DTPicture.java is used by the 1.4 DragPictureDemo.java example.
  245. */
  246.  
  247. //A subclass of Picture that supports Data Transfer.
  248.  
  249. class DTPicture extends Picture implements MouseMotionListener {
  250. private MouseEvent firstMouseEvent = null;
  251.  
  252. private static boolean installInputMapBindings = true;
  253.  
  254. public DTPicture(Image image) {
  255. super(image);
  256. addMouseMotionListener(this);
  257.  
  258. //Add the cut/copy/paste key bindings to the input map.
  259. //Note that this step is redundant if you are installing
  260. //menu accelerators that cause these actions to be invoked.
  261. //DragPictureDemo does not use menu accelerators and,since
  262. //the default value of installInputMapBindings is true,//the bindings are installed. DragPictureDemo2 does use
  263. //menu accelerators and so calls setInstallInputMapBindings
  264. //with a value of false. Your program would do one or the
  265. //other,but not both.
  266. if (installInputMapBindings) {
  267. InputMap imap = this.getInputMap();
  268. imap.put(KeyStroke.getKeyStroke("ctrl X"),TransferHandler
  269. .getCutAction().getValue(Action.NAME));
  270. imap.put(KeyStroke.getKeyStroke("ctrl C"),TransferHandler
  271. .getCopyAction().getValue(Action.NAME));
  272. imap.put(KeyStroke.getKeyStroke("ctrl V"),TransferHandler
  273. .getPasteAction().getValue(Action.NAME));
  274. }
  275.  
  276. //Add the cut/copy/paste actions to the action map.
  277. //This step is necessary because the menu's action listener
  278. //looks for these actions to fire.
  279. ActionMap map = this.getActionMap();
  280. map.put(TransferHandler.getCutAction().getValue(Action.NAME),TransferHandler.getCutAction());
  281. map.put(TransferHandler.getCopyAction().getValue(Action.NAME),TransferHandler.getCopyAction());
  282. map.put(TransferHandler.getPasteAction().getValue(Action.NAME),TransferHandler.getPasteAction());
  283. }
  284.  
  285. public void setImage(Image image) {
  286. this.image = image;
  287. this.repaint();
  288. }
  289.  
  290. public void mousePressed(MouseEvent e) {
  291. //Don't bother to drag if there is no image.
  292. if (image == null)
  293. return;
  294.  
  295. firstMouseEvent = e;
  296. e.consume();
  297. }
  298.  
  299. public void mouseDragged(MouseEvent e) {
  300. //Don't bother to drag if the component displays no image.
  301. if (image == null)
  302. return;
  303.  
  304. if (firstMouseEvent != null) {
  305. e.consume();
  306.  
  307. //If they are holding down the control key,COPY rather than MOVE
  308. int ctrlMask = InputEvent.CTRL_DOWN_MASK;
  309. int action = ((e.getModifiersEx() & ctrlMask) == ctrlMask) ? TransferHandler.COPY
  310. : TransferHandler.MOVE;
  311.  
  312. int dx = Math.abs(e.getX() - firstMouseEvent.getX());
  313. int dy = Math.abs(e.getY() - firstMouseEvent.getY());
  314. //Arbitrarily define a 5-pixel shift as the
  315. //official beginning of a drag.
  316. if (dx > 5 || dy > 5) {
  317. //This is a drag,not a click.
  318. JComponent c = (JComponent) e.getSource();
  319. TransferHandler handler = c.getTransferHandler();
  320. //Tell the transfer handler to initiate the drag.
  321. handler.exportAsDrag(c,firstMouseEvent,action);
  322. firstMouseEvent = null;
  323. }
  324. }
  325. }
  326.  
  327. public void mouseReleased(MouseEvent e) {
  328. firstMouseEvent = null;
  329. }
  330.  
  331. public void mouseMoved(MouseEvent e) {
  332. }
  333.  
  334. //This method is necessary because DragPictureDemo and
  335. //DragPictureDemo2 both use this class and DragPictureDemo
  336. //needs to have the input map bindings installed for
  337. //cut/copy/paste. DragPictureDemo2 uses menu accelerators
  338. //and does not need to have the input map bindings installed.
  339. //Your program would use one approach or the other,but not
  340. //both. The default for installInputMapBindings is true.
  341. public static void setInstallInputMapBindings(boolean flag) {
  342. installInputMapBindings = flag;
  343. }
  344.  
  345. public static boolean getInstallInputMapBindingds() { //for completeness
  346. return installInputMapBindings;
  347. }
  348. }
  349.  
  350. /*
  351. * Picture.java is used by the 1.4 TrackFocusDemo.java and DragPictureDemo.java
  352. * examples.
  353. */
  354.  
  355. class Picture extends JComponent implements MouseListener,FocusListener,Accessible {
  356. Image image;
  357.  
  358. public Picture(Image image) {
  359.  
  360. this.image = image;
  361. setFocusable(true);
  362. addMouseListener(this);
  363. addFocusListener(this);
  364. }
  365.  
  366. public void mouseClicked(MouseEvent e) {
  367. //Since the user clicked on us,let's get focus!
  368. requestFocusInWindow();
  369. }
  370.  
  371. public void mouseEntered(MouseEvent e) {
  372. }
  373.  
  374. public void mouseExited(MouseEvent e) {
  375. }
  376.  
  377. public void mousePressed(MouseEvent e) {
  378. }
  379.  
  380. public void mouseReleased(MouseEvent e) {
  381. }
  382.  
  383. public void focusGained(FocusEvent e) {
  384. //Draw the component with a red border
  385. //indicating that it has focus.
  386. this.repaint();
  387. }
  388.  
  389. public void focusLost(FocusEvent e) {
  390. //Draw the component with a black border
  391. //indicating that it doesn't have focus.
  392. this.repaint();
  393. }
  394.  
  395. protected void paintComponent(Graphics graphics) {
  396. Graphics g = graphics.create();
  397.  
  398. //Draw in our entire space,even if isOpaque is false.
  399. g.setColor(Color.WHITE);
  400. g.fillRect(0,image == null ? 125 : image.getWidth(this),image == null ? 125 : image.getHeight(this));
  401.  
  402. if (image != null) {
  403. //Draw image at its natural size of 125x125.
  404. g.drawImage(image,this);
  405. }
  406.  
  407. //Add a border,red if picture currently has focus
  408. if (isFocusOwner()) {
  409. g.setColor(Color.RED);
  410. } else {
  411. g.setColor(Color.BLACK);
  412. }
  413. g.drawRect(0,image == null ? 125 : image.getHeight(this));
  414. g.dispose();
  415. }
  416. }
  417.  
  418. /*
  419. * PictureTransferHandler.java is used by the 1.4 DragPictureDemo.java example.
  420. */
  421.  
  422. class PictureTransferHandler extends TransferHandler {
  423. DataFlavor pictureFlavor = DataFlavor.imageFlavor;
  424.  
  425. DTPicture sourcePic;
  426.  
  427. boolean shouldRemove;
  428.  
  429. public boolean importData(JComponent c,Transferable t) {
  430. Image image;
  431. if (canImport(c,t.getTransferDataFlavors())) {
  432. DTPicture pic = (DTPicture) c;
  433. //Don't drop on myself.
  434. if (sourcePic == pic) {
  435. shouldRemove = false;
  436. return true;
  437. }
  438. try {
  439. image = (Image) t.getTransferData(pictureFlavor);
  440. //Set the component to the new picture.
  441. pic.setImage(image);
  442. return true;
  443. } catch (UnsupportedFlavorException ufe) {
  444. System.out.println("importData: unsupported data flavor");
  445. } catch (IOException ioe) {
  446. System.out.println("importData: I/O exception");
  447. }
  448. }
  449. return false;
  450. }
  451.  
  452. protected Transferable createTransferable(JComponent c) {
  453. sourcePic = (DTPicture) c;
  454. shouldRemove = true;
  455. return new PictureTransferable(sourcePic);
  456. }
  457.  
  458. public int getSourceActions(JComponent c) {
  459. return COPY_OR_MOVE;
  460. }
  461.  
  462. protected void exportDone(JComponent c,Transferable data,int action) {
  463. if (shouldRemove && (action == MOVE)) {
  464. sourcePic.setImage(null);
  465. }
  466. sourcePic = null;
  467. }
  468.  
  469. public boolean canImport(JComponent c,DataFlavor[] flavors) {
  470. for (int i = 0; i < flavors.length; i++) {
  471. if (pictureFlavor.equals(flavors[i])) {
  472. return true;
  473. }
  474. }
  475. return false;
  476. }
  477.  
  478. class PictureTransferable implements Transferable {
  479. private Image image;
  480.  
  481. PictureTransferable(DTPicture pic) {
  482. image = pic.image;
  483. }
  484.  
  485. public Object getTransferData(DataFlavor flavor)
  486. throws UnsupportedFlavorException {
  487. if (!isDataFlavorSupported(flavor)) {
  488. throw new UnsupportedFlavorException(flavor);
  489. }
  490. return image;
  491. }
  492.  
  493. public DataFlavor[] getTransferDataFlavors() {
  494. return new DataFlavor[] { pictureFlavor };
  495. }
  496.  
  497. public boolean isDataFlavorSupported(DataFlavor flavor) {
  498. return pictureFlavor.equals(flavor);
  499. }
  500. }
  501. }
  502.  
  503. /*
  504. * TransferActionListener.java is used by the 1.4 DragPictureDemo.java example.
  505. */
  506.  
  507. /*
  508. * A class that tracks the focused component. This is necessary to delegate the
  509. * menu cut/copy/paste commands to the right component. An instance of this
  510. * class is listening and when the user fires one of these commands,it calls
  511. * the appropriate action on the currently focused component.
  512. */
  513.  
  514. class TransferActionListener implements ActionListener,PropertyChangeListener {
  515. private JComponent focusOwner = null;
  516.  
  517. public TransferActionListener() {
  518. KeyboardFocusManager manager = KeyboardFocusManager
  519. .getCurrentKeyboardFocusManager();
  520. manager.addPropertyChangeListener("permanentFocusOwner",this);
  521. }
  522.  
  523. public void propertyChange(PropertyChangeEvent e) {
  524. Object o = e.getNewValue();
  525. if (o instanceof JComponent) {
  526. focusOwner = (JComponent) o;
  527. } else {
  528. focusOwner = null;
  529. }
  530. }
  531.  
  532. public void actionPerformed(ActionEvent e) {
  533. if (focusOwner == null)
  534. return;
  535. String action = (String) e.getActionCommand();
  536. Action a = focusOwner.getActionMap().get(action);
  537. if (a != null) {
  538. a.actionPerformed(new ActionEvent(focusOwner,ActionEvent.ACTION_PERFORMED,null));
  539. }
  540. }
  541. }

猜你在找的Java相关文章