Java Swing Drop Example

xiaoxiao2021-03-06  57

I changed a document system tree from Java.sun.com and JavaWorld.com, supported drag and drop, ctrl V copy file import java.awt.Acomposite; import java.awt.component; import java.aw .Graphics2D; import java.awt.Point; import java.awt.Rectangle; import java.awt.Toolkit; import java.awt.datatransfer.DataFlavor; import java.awt.datatransfer.StringSelection; import java.awt.datatransfer.Transferable ; import java.awt.datatransfer.UnsupportedFlavorException; import java.awt.dnd.DnDConstants; import java.awt.dnd.DragGestureEvent; import java.awt.dnd.DragGestureListener; import java.awt.dnd.DragSource; import java.awt .dnd.DragSourceDragEvent; import java.awt.dnd.DragSourceDropEvent; import java.awt.dnd.DragSourceEvent; import java.awt.dnd.DragSourceListener; import java.awt.dnd.DropTarget; import java.awt.dnd.DropTargetDragEvent; import java.awt.dnd.DropTargetDropEvent; import java.awt.dnd.DropTargetEvent; import java.awt.dnd.DropTargetListener; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt. Event.keyadapter; import java.aw. event.KeyEvent; import java.awt.geom.AffineTransform; import java.awt.geom.Rectangle2D; import java.awt.image.BufferedImage; import java.io.File; import java.io.FileInputStream; import java.io. FileOutputStream; import java.io ioException; import java.util.ITerator; import java.util.list;

import javax.swing.Icon; import javax.swing.JLabel; import javax.swing.JTree; import javax.swing.Timer; import javax.swing.event.TreeExpansionEvent; import javax.swing.event.TreeExpansionListener; import javax.swing .filechooser.FileSystemView; import javax.swing.tree.DefaultMutableTreeNode; import javax.swing.tree.DefaultTreeCellRenderer; import javax.swing.tree.DefaultTreeModel; import javax.swing.tree.TreePath;

Class Dragtree Extends Jtree Implements DraggeStureListener, DragsourceListener, DROPTARGETLISTENER {BuffedImage GhostiMage; Private Rectangle2d GhostRect = New Rectangle2d.float ();

PRIVATE POINT PTOFFSET = New Point ();

PRIVATE POINT LastPoint = New Point ();

PRIVATE TREEPATH LASTPATH;

Private Timer Hovertimer;

Filenode SourceNode;

Public Dragtree () {DragSource Dragsource = Dragsource.getDefaultDragsource ();

dragSource.createDefaultDragGestureRecognizer (this, // component where // drag originates DnDConstants.ACTION_COPY_OR_MOVE, // actions this); // drag gesture recognizer setModel (createTreeModel ());

AddTreeExpansionListener (New TreeexpansionListener () {public void Treecollapsed (TreeExpansionEvent E) {}

Public void TreeExpanded (TreeExpansionEvent E) {TreePath Path = E.GETPATH ​​();

IF (path! = null) {filenode node = (filenode) path.getlastpathcomponent ();

if {DefaultTreeModel model = (DefaultTreeModel) getModel (); node.explore (); model.nodeStructureChanged (node);} (node.isExplored ()!)}}}); this.setCellRenderer (new DefaultTreeCellRenderer () {

public Component getTreeCellRendererComponent (JTree tree, Object value, boolean selected, boolean expanded, boolean leaf, int row, boolean hasFocus) {TreePath tp = tree.getPathForRow (row); if (tp = null!) {FileNode node = (FileNode) Tp.getlastPathComponent (); file f = node.getfile (); try {icon = filesystemView.getFilesystemView () .Getsystemicon (f); this.setleaficon; this.setopenicon (icon); this.setopenicon This.SetClosedicon (ICON); this.SetDisabledicon (ICON);} catch (exception e) {E.PrintStackTrace ();}} Return Super.gettreecellrenderRenderComponent (Tree, Value, SelectE D, Expanded, Leaf, Row, HASFOCUS;}});

Super.setscrollsoneXpand (TRUE); New DROPTARGET (this, DNDCONSTANTS.ACTION_COPY_OR_MOVE, THIS);

// Set up a hover timer, so that a node will be automatically expanded // or collapsed // if the user lingers on it for more than a short time hoverTimer = new Timer (1000, new ActionListener () {public void actionPerformed ( ActionEvent E) {if (LastPath == NULL) {Return;}} == 0) Return; // Do Nothing if We Are HOOVERING OVER THE ROOT NODE IF (ISExpanded (LastPath) Collapsepath (LastPath) Else ExpandPath (LastPath);}}); Hovertimer.SetRepeats (false); // set timer to one-shot modethis.addKeylistener (new keyadapter () {

Public void keypressed (keyevent e) {int code = E.GetKeycode (); int shape = E.GETMODIFIERS (); if (code == 'v' || code == 'v') {system.out.println "Find V"); System.out.Println ("Modifiers:" Modifiers "/ T" ((Modifiers & Keyevent.ctrl_mask)! = 0));

IF ((Modifier & Keyevent.ctrl_mask)! = 0 && (Code == 'V' || Code == 'V')) {Transferable Tr = Toolkit.getDefaultToolkit () .GetsystemClipboard (). getContents (null);

TreePath path = getSelectionPath (); if (path == null) {return; filenode node = (filenode) path.getlastPathComponent (); if (node.isdirectory ()) {system.out.println ("File CP") TRY {List List = (List) (Tr .GetTransferData (DataFlavor.javaFileListflavor); item itrator = list.iterator (); file parent = node.getfile (); while (item.hasnext ()) {file f = (File); cp (f, new file (parent, f.getname ()));} node.reexplore ();} catch (exception ooe) {ion (Exception IoE) {IOE.PrintStackTrace ();} Upda TEUI ();}}}});

Public void DraggeStureRecognized (DraggeEvent E) {// Drag Anything ...

TreePath path = getLeadSelectionPath (); if (path == null) return; FileNode node = (FileNode) path.getLastPathComponent (); sourceNode = node; // Work out the offset of the drag point from the TreePath bounding // rectangle origin Rectangle Rapath = getPathbounds (PATH); Point Ptdragorigin = E.GETDRAGORIGIN (); ptoffset.x - rapath.x, ptdragorigin.y - rapath.y); // Get The Cell Renderer (Which is a jlabel) for the path being dragged int row = this.getRowForLocation (ptDragOrigin.x, ptDragOrigin.y);. JLabel lbl = (JLabel) getCellRenderer () getTreeCellRendererComponent (this, // tree path.getLastPathComponent (), // value false, / / isselected (DONT WANT A Colored Background ISEXPANDED (PATH), // ISExpanded getModel (). Isleaf (path.getlastpathcomponent ()), // isleaf row, // Row (NOT IMPORTANT for Rendering) False // Hasfocus (DONT WANT A FOCUS Rectangle); lbl.setsize ((int) rapath.getwidth (), (int) rapath.getHeight ()); // <- // The // Layout // Manager // Would // Normally // DO // this // Get a Buffered Image of the Selection for Dragging a ghost Image this.ghostImage = New BufferedImage ((int) rapath.Getwidth (), INT) RAPATH.GETHEIGHT (), BufferedImage.Type_INT_ARGB_PRE); Graphics2D G2 = ghostiMage.creategraphics ();

// ask the Cell Renderer to Paint Itself INTO The Bufferedimage G2.GetComposite (alphacomposite.getinstance (alphacomposite.GETITIC, 0.5F)); // make the image ghostlike lbl.paint (g2); g2.dispose (); // THIS.GRAPHICs (). DrawImage (GhostImage (GhostImage (). x, // E.GetDragorigin (). Y, this);

E.StartDrag (Null, // Cursor GhostImage, New Point (5, 5), New StringSelection (GetFileName ()), // transferable this); // Drag Source Listener}

Public void Dragdropend (DragsourceDropevent E) {ghostimage = null; SourceNode = null;}

Public void Dragenter (DragsourceDragevent E) {}

Public void Dragexit (DragSourceEvent E) {if (! Dragsource.IsDragImagesupported ()) {repaint (ghoStRect.getbounds ());}}

Public void Dragover (DragsourceDragevent E) {

}

Public void dropactionch (DragsourceDragevent E) {}

Public string getFileName () {treepath path = getleadselectionPath (); filenode node = (filenode) path.getLastPathComponent (); return node.getuserObject ()). GetabsolutePath () ()).

Private defaulttreemodel createtreemodel () {file root = filesystemView.getFileSystemView (). getroots () [0]; filenode rootnode = new filenode (root);

Rootnode.explore (); return new defaulttreemodel (rootnode);}

Public void Dragenter (DROPTARGETDRAGEVENT DTDE) {

}

Public void Dragover (DROPTARGETDRAGEVENT DTDE) {

POINT PT = DTDE.GETLOCATION (); if (pt.equals (lastpoint)) {Return;}} {graphics2d g2 = (graphics2d) getGraphics (); // if a Drag image is not supported by the platform, then draw my // own drag image if (DragSource.isDragImageSupported ()!) {paintImmediately (ghostRect.getBounds ()); // Rub out the last // ghost image and cue // line // and remember where WE area About to draw the new ghost image ghostet.setRect (pt.x - ptoffset.x, pt.y - ptoffset.y, ghostimage.getWidth (), ghostimage.getHeight (); g2.drawimage ((ghostimage), AffineTransform .GettranslateInstance (ghoStRect.getx (), ghostRect .gety ()), null);}} TreePath Path = getCloseStpathforLocation (pt.x, pt.y); if (! (Path == lastpath) { Lastpath = path; hovertimer.restart ();}} public void dropactionchanged (DROPTARGETDRAGEVENT DTDE) {

}

Public void Drop (DROPTARGETDROPEVENT E) {Try {DataFlavor StringFlavor = DataFlavor.StringFlavor; Transferable Tr = E.GETTRANSFERABLE ();

TreePath path = this.getPathforLocation (E.GetLocation (). X, e .getlocation (); if (path == null) {E.rejectDrop (); return;} filenode node = (filenode) path.getLastPathComponent (); if (e.isDataFlavorSupported (DataFlavor.javaFileListFlavor) && node.isDirectory ()) {e.acceptDrop (DnDConstants.ACTION_COPY_OR_MOVE); System.out.println ( "file cp"); List list = (List) (e .GetTransferable () .GetTransferData (DataFlavor.javaFileListflavor); item itrator ity = list.iterator (); file parent = node.getfile (); while (item.hasnext ()) {file f = (file) oretor.next ); Cp (f, new file (parent, f.getname ()));} node.reexplore (); e.dropcomplete (true); this.Updateui ();} ELS e if (e.isDataFlavorSupported (stringFlavor) && node.isDirectory ()) {String filename = (String) tr.getTransferData (stringFlavor); if (filename.endsWith ( ". txt") || filename.endsWith ( "java. ") | | Filename.endSwith (". JSP ") || filename.endswith (". Html ") || filename.endswith (". Htm ") {e.acceptdrop (DNDCONSTANTS.ACTION_COPY_OR_MOVE); file f = new File (filename); if (f.exists ()) {f.renameto (new file (node.getfile (), f.getname ()));

Node.reexplore (); ((Filenode) Source ()). Remove (SourceNode); E.DropComplete (TRUE); this.Updateui ();} else {E.rejectDrop ();}} else {e. rejectDrop ();}} else {e.rejectDrop ();}} catch (IOException ioe) {ioe.printStackTrace ();} catch (UnsupportedFlavorException ufe) {ufe.printStackTrace ();} finally {ghostImage = null; this. Repaint ();}} private void cp (file src, file dest) throws ioException {if (src.isdirectory ()) {if (! dest.exists ()) {boolean return = dest.mkdir (); if (Ret == false) return;} file [] fs = src.listfiles (); for (int i = 0; i 0) {Out.write (buf, 0, len);}} finally {in.close (); out.close () }}

Public void Dragexit (DROPTARGETEVENT DTE) {

}

Class Filenode Extends DefaultmutableTreenode {Private Boolean Explored = False;

Public Filenode (file file) {setuserObject (file);

Public Boolean getAllowsChildren () {return isDirectory ();} public boolean isleaf () {return! isDirectory ();

Public File getFile () {return (file) getUserObject ();

Public Boolean ISEXPLORED () {Return Explored;}

Public boolean isdirectory () {file file = getfile (); return file.Indirectory ();

Public string toString () {file file = (file) getUserObject (); string filename = file.toString (); int index = filename.lastIndexof (file.separator);

Return (index! = -1 && index! = filename.length () - 1)? FileName .substring (Index 1): filename;

Public void expedition () {if (! isdirectory ()) return;

IF (! iSExplored ()) {file file = getfile (); file [] children = file.listfiles ();

For (int i = 0; i

public void reexplore () {this.removeAllChildren (); explored = false; explore ();}} Example Usage: import java.awt.BorderLayout; import java.awt.Dimension; import java.awt.datatransfer.DataFlavor; import java.awt.datatransfer.Transferable; import java.awt.datatransfer.UnsupportedFlavorException; import java.awt.dnd.DnDConstants; import java.awt.dnd.DropTarget; import java.awt.dnd.DropTargetDragEvent; import java.awt.dnd .DropTargetDropEvent; import java.awt.dnd.DropTargetEvent; import java.awt.dnd.DropTargetListener; import java.awt.event.WindowAdapter; import java.awt.event.WindowEvent; import java.io.File; import java.io .FileReader; import java.io.IOException; import java.util.Iterator; import java.util.List; import javax.swing.BorderFactory; import javax.swing.JEditorPane; import javax.swing.JFrame; import javax.swing. JPANel; import javax.swing.jscrollpane; import javax.swing.jsplitpane; import javax.swing.uimanager; import javax.swing.WindowConstants; import javax.swing.filechooser.Filesystemv Iew; import javax.swing.text.document; import javax.swing.text.editorkit;

Public Class Test Extends Jframe Implements DROPTARGETLISTENER {Private JeditorPane Textpane = New JeditorPane ();

Public Test () {Super ("Drag and Drop with Swing");

New DROPTARGET (TextPane, DNDCONSTANTS.ACTION_COPY_OR_MOVE, THIS);

JSPLITPANE SPLITPANE = New Jsplitpane (jsplitpane.horizontal_split, createtreePanel (), CreateTextPanel ());

Splitpane.setdividerLocation (250); splitpane.setonetouchexpandable (TRUE);

GetContentPane (). add (splitpane, borderlayout.center);

public static void main (String args []) {try {UIManager.setLookAndFeel (UIManager.getSystemLookAndFeelClassName ());} catch (Exception e1) {e1.printStackTrace ();} Test test = new Test (); test.setBounds ( 300, 300, 850, 350); test.setVisible (true); test.setDefaultCloseOperation (WindowConstants.DISPOSE_ON_CLOSE); test.addWindowListener (new WindowAdapter () {public void windowClosed (WindowEvent e) {System.exit (0);} });

Private JPanel CreateTreePanel () {jPanel TreePanel = New jPanel (); Dragtree Tree = New Dragtree ();

treePanel.setLayout (new BorderLayout ()); treePanel.add (new JScrollPane (tree), BorderLayout.CENTER); treePanel.setBorder (BorderFactory .createTitledBorder ( "Drag source for filenames")); return treePanel;}

Private jpane createtextPanel () {jPanel textpanel = new jPanel ();

textPanel.setLayout (new BorderLayout ()); textPanel.add (new JScrollPane (textPane), BorderLayout.CENTER); textPanel.setMinimumSize (new Dimension (375, 0)); textPanel.setBorder (BorderFactory .createTitledBorder ( "Drop target for Filenames "));

Return TEXTPANEL;

private void readFile (final String filename) {try {textPane.setPage (new File (filename) .toURL ());} catch (IOException e) {EditorKit kit = textPane.getEditorKit (); Document document = textPane.getDocument () ;

Try {document.remove (0, Document.getLength ()); Kit.Read (New FileReader (FileName), Document, 0);} catch (Exception EX) {EX.PrintStackTrace ();}}} public void Drop DROPTARGETDROPEVENT E) {Try {dataflavor stringflavor = dataflavor.stringflavor; transferable tr = E.GETTRANSFERABLE ();

if (e.isDataFlavorSupported (stringFlavor)) {String filename = (String) tr.getTransferData (stringFlavor); if (filename.endsWith ( ". txt") || filename.endsWith ( ". java") || filename.endsWith (".jsp") || filename.endswith (". html") || filename.endswith (". htm")) {e.acceptddrop (DNDCONSTANTS.ACTION_COPY_OR_MOVE); ReadFile (filename); TextPane.setCaretPosition (0) ; e.dropComplete (true);} else {e.rejectDrop ();}} else {e.rejectDrop ();}} catch (IOException ioe) {ioe.printStackTrace ();} catch (UnsupportedFlavorException ufe) {ufe. PRINTSTACKTRACE ();}}

Public void Dragenter (DROPTARGETDRAGEVENT E) {}

Public void Dragexit (DROPTARGETEVENT E) {}

Public void Dragover (DROPTARGETDRAGEVENT E) {}

Public void Dropaction E) {}}

转载请注明原文地址:https://www.9cbs.com/read-85130.html

New Post(0)