|
马上注册,结交更多好友,享用更多功能,让你轻松玩转社区。
您需要 登录 才可以下载或查看,没有帐号?立即注册
x
轮性能微软曾做过一个例子,就是同一个项目用java和.net来作,结果开发周期,.net是java的一半,性能java是.net的十分之一,代码量java是.net的三倍。呵呵,这说明了什么,.net的全方位比java好。但是有的人说.net不能跨平台,这个问题我和我同学曾讨论过,都认为微软的.net很可能早都可以跨平台了,但是微软为了保护他们的操作系统,所以才没有推出跨平台的.net,只是推出了跨语言的.net,我从java.sun.com和javaworld.com上的例子悔改来的一棵文件体系树,撑持拖放,CTRL+V复制文件
importjava.awt.AlphaComposite;
importjava.awt.Component;
importjava.awt.Graphics2D;
importjava.awt.Point;
importjava.awt.Rectangle;
importjava.awt.Toolkit;
importjava.awt.datatransfer.DataFlavor;
importjava.awt.datatransfer.StringSelection;
importjava.awt.datatransfer.Transferable;
importjava.awt.datatransfer.UnsupportedFlavorException;
importjava.awt.dnd.DnDConstants;
importjava.awt.dnd.DragGestureEvent;
importjava.awt.dnd.DragGestureListener;
importjava.awt.dnd.DragSource;
importjava.awt.dnd.DragSourceDragEvent;
importjava.awt.dnd.DragSourceDropEvent;
importjava.awt.dnd.DragSourceEvent;
importjava.awt.dnd.DragSourceListener;
importjava.awt.dnd.DropTarget;
importjava.awt.dnd.DropTargetDragEvent;
importjava.awt.dnd.DropTargetDropEvent;
importjava.awt.dnd.DropTargetEvent;
importjava.awt.dnd.DropTargetListener;
importjava.awt.event.ActionEvent;
importjava.awt.event.ActionListener;
importjava.awt.event.KeyAdapter;
importjava.awt.event.KeyEvent;
importjava.awt.geom.AffineTransform;
importjava.awt.geom.Rectangle2D;
importjava.awt.image.BufferedImage;
importjava.io.File;
importjava.io.FileInputStream;
importjava.io.FileOutputStream;
importjava.io.IOException;
importjava.util.Iterator;
importjava.util.List;
importjavax.swing.Icon;
importjavax.swing.JLabel;
importjavax.swing.JTree;
importjavax.swing.Timer;
importjavax.swing.event.TreeExpansionEvent;
importjavax.swing.event.TreeExpansionListener;
importjavax.swing.filechooser.FileSystemView;
importjavax.swing.tree.DefaultMutableTreeNode;
importjavax.swing.tree.DefaultTreeCellRenderer;
importjavax.swing.tree.DefaultTreeModel;
importjavax.swing.tree.TreePath;
classDragTreeextendsJTreeimplementsDragGestureListener,
DragSourceListener,DropTargetListener{
BufferedImageghostImage;
privateRectangle2DghostRect=newRectangle2D.Float();
privatePointptOffset=newPoint();
privatePointlastPoint=newPoint();
privateTreePathlastPath;
privateTimerhoverTimer;
FileNodesourceNode;
publicDragTree(){
DragSourcedragSource=DragSource.getDefaultDragSource();
dragSource.createDefaultDragGestureRecognizer(this,//componentwhere
//dragoriginates
DnDConstants.ACTION_COPY_OR_MOVE,//actions
this);//draggesturerecognizer
setModel(createTreeModel());
addTreeExpansionListener(newTreeExpansionListener(){
publicvoidtreeCollapsed(TreeExpansionEvente){
}
publicvoidtreeExpanded(TreeExpansionEvente){
TreePathpath=e.getPath();
if(path!=null){
FileNodenode=(FileNode)path.getLastPathComponent();
if(!node.isExplored()){
DefaultTreeModelmodel=(DefaultTreeModel)getModel();
node.explore();
model.nodeStructureChanged(node);
}
}
}
});
this.setCellRenderer(newDefaultTreeCellRenderer(){
publicComponentgetTreeCellRendererComponent(JTreetree,
Objectvalue,booleanselected,booleanexpanded,
booleanleaf,introw,booleanhasFocus){
TreePathtp=tree.getPathForRow(row);
if(tp!=null){
FileNodenode=(FileNode)tp.getLastPathComponent();
Filef=node.getFile();
try{
Iconicon=FileSystemView.getFileSystemView()
.getSystemIcon(f);
this.setIcon(icon);
this.setLeafIcon(icon);
this.setOpenIcon(icon);
this.setClosedIcon(icon);
this.setDisabledIcon(icon);
}catch(Exceptione){
e.printStackTrace();
}
}
returnsuper.getTreeCellRendererComponent(tree,value,
selected,expanded,leaf,row,hasFocus);
}
});
super.setScrollsOnExpand(true);
newDropTarget(this,DnDConstants.ACTION_COPY_OR_MOVE,this);
//Setupahovertimer,sothatanodewillbeautomaticallyexpanded
//orcollapsed
//iftheuserlingersonitformorethanashorttime
hoverTimer=newTimer(1000,newActionListener(){
publicvoidactionPerformed(ActionEvente){
if(lastPath==null){
return;
}
if(getRowForPath(lastPath)==0)
return;//Donothingifwearehoveringovertherootnode
if(isExpanded(lastPath))
collapsePath(lastPath);
else
expandPath(lastPath);
}
});
hoverTimer.setRepeats(false);//Settimertoone-shotmode
this.addKeyListener(newKeyAdapter(){
publicvoidkeyPressed(KeyEvente){
intcode=e.getKeyCode();
intmodifiers=e.getModifiers();
if(code==v||code==V){
System.out.println("findv");
System.out.println("modifiers:"+modifiers+" "
+((modifiers&KeyEvent.CTRL_MASK)!=0));
}
if((modifiers&KeyEvent.CTRL_MASK)!=0
&&(code==v||code==V)){
Transferabletr=Toolkit.getDefaultToolkit()
.getSystemClipboard().getContents(null);
TreePathpath=getSelectionPath();
if(path==null){
return;
}
FileNodenode=(FileNode)path.getLastPathComponent();
if(node.isDirectory()){
System.out.println("filecp");
try{
Listlist=(List)(tr
.getTransferData(DataFlavor.javaFileListFlavor));
Iteratoriterator=list.iterator();
Fileparent=node.getFile();
while(iterator.hasNext()){
Filef=(File)iterator.next();
cp(f,newFile(parent,f.getName()));
}
node.reexplore();
}catch(Exceptionioe){
ioe.printStackTrace();
}
updateUI();
}
}
}
});
}
publicvoiddragGestureRecognized(DragGestureEvente){
//draganything...
TreePathpath=getLeadSelectionPath();
if(path==null)
return;
FileNodenode=(FileNode)path.getLastPathComponent();
sourceNode=node;
//WorkouttheoffsetofthedragpointfromtheTreePathbounding
//rectangleorigin
RectangleraPath=getPathBounds(path);
PointptDragOrigin=e.getDragOrigin();
ptOffset.setLocation(ptDragOrigin.x-raPath.x,ptDragOrigin.y
-raPath.y);
//Getthecellrenderer(whichisaJLabel)forthepathbeingdragged
introw=this.getRowForLocation(ptDragOrigin.x,ptDragOrigin.y);
JLabellbl=(JLabel)getCellRenderer().getTreeCellRendererComponent(
this,//tree
path.getLastPathComponent(),//value
false,//isSelected(dontwantacoloredbackground)
isExpanded(path),//isExpanded
getModel().isLeaf(path.getLastPathComponent()),//isLeaf
row,//row(notimportantforrendering)
false//hasFocus(dontwantafocusrectangle)
);
lbl.setSize((int)raPath.getWidth(),(int)raPath.getHeight());//<--
//The
//layout
//manager
//would
//normally
//do
//this
//Getabufferedimageoftheselectionfordraggingaghostimage
this.ghostImage=newBufferedImage((int)raPath.getWidth(),
(int)raPath.getHeight(),BufferedImage.TYPE_INT_ARGB_PRE);
Graphics2Dg2=ghostImage.createGraphics();
//AskthecellrenderertopaintitselfintotheBufferedImage
g2.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC,0.5f));
//Maketheimageghostlike
lbl.paint(g2);
g2.dispose();
//this.getGraphics().drawImage(ghostImage,e.getDragOrigin().x,
//e.getDragOrigin().y,this);
e.startDrag(null,//cursor
ghostImage,newPoint(5,5),
newStringSelection(getFilename()),//transferable
this);//dragsourcelistener
}
publicvoiddragDropEnd(DragSourceDropEvente){
ghostImage=null;
sourceNode=null;
}
publicvoiddragEnter(DragSourceDragEvente){
}
publicvoiddragExit(DragSourceEvente){
if(!DragSource.isDragImageSupported()){
repaint(ghostRect.getBounds());
}
}
publicvoiddragOver(DragSourceDragEvente){
}
publicvoiddropActionChanged(DragSourceDragEvente){
}
publicStringgetFilename(){
TreePathpath=getLeadSelectionPath();
FileNodenode=(FileNode)path.getLastPathComponent();
return((File)node.getUserObject()).getAbsolutePath();
}
privateDefaultTreeModelcreateTreeModel(){
Fileroot=FileSystemView.getFileSystemView().getRoots()[0];
FileNoderootNode=newFileNode(root);
rootNode.explore();
returnnewDefaultTreeModel(rootNode);
}
publicvoiddragEnter(DropTargetDragEventdtde){
}
publicvoiddragOver(DropTargetDragEventdtde){
Pointpt=dtde.getLocation();
if(pt.equals(lastPoint)){
return;
}
if(ghostImage!=null){
Graphics2Dg2=(Graphics2D)getGraphics();
//Ifadragimageisnotsupportedbytheplatform,thendrawmy
//owndragimage
if(!DragSource.isDragImageSupported()){
paintImmediately(ghostRect.getBounds());//Ruboutthelast
//ghostimageandcue
//line
//Andrememberwhereweareabouttodrawthenewghostimage
ghostRect.setRect(pt.x-ptOffset.x,pt.y-ptOffset.y,
ghostImage.getWidth(),ghostImage.getHeight());
g2.drawImage((ghostImage),AffineTransform
.getTranslateInstance(ghostRect.getX(),ghostRect
.getY()),null);
}
}
TreePathpath=getClosestPathForLocation(pt.x,pt.y);
if(!(path==lastPath)){
lastPath=path;
hoverTimer.restart();
}
}
publicvoiddropActionChanged(DropTargetDragEventdtde){
}
publicvoiddrop(DropTargetDropEvente){
try{
DataFlavorstringFlavor=DataFlavor.stringFlavor;
Transferabletr=e.getTransferable();
TreePathpath=this.getPathForLocation(e.getLocation().x,e
.getLocation().y);
if(path==null){
e.rejectDrop();
return;
}
FileNodenode=(FileNode)path.getLastPathComponent();
if(e.isDataFlavorSupported(DataFlavor.javaFileListFlavor)
&&node.isDirectory()){
e.acceptDrop(DnDConstants.ACTION_COPY_OR_MOVE);
System.out.println("filecp");
Listlist=(List)(e.getTransferable()
.getTransferData(DataFlavor.javaFileListFlavor));
Iteratoriterator=list.iterator();
Fileparent=node.getFile();
while(iterator.hasNext()){
Filef=(File)iterator.next();
cp(f,newFile(parent,f.getName()));
}
node.reexplore();
e.dropComplete(true);
this.updateUI();
}elseif(e.isDataFlavorSupported(stringFlavor)
&&node.isDirectory()){
Stringfilename=(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);
Filef=newFile(filename);
if(f.exists()){
f.renameTo(newFile(node.getFile(),f.getName()));
node.reexplore();
((FileNode)sourceNode.getParent()).remove(sourceNode);
e.dropComplete(true);
this.updateUI();
}else{
e.rejectDrop();
}
}else{
e.rejectDrop();
}
}else{
e.rejectDrop();
}
}catch(IOExceptionioe){
ioe.printStackTrace();
}catch(UnsupportedFlavorExceptionufe){
ufe.printStackTrace();
}finally{
ghostImage=null;
this.repaint();
}
}
privatevoidcp(Filesrc,Filedest)throwsIOException{
if(src.isDirectory()){
if(!dest.exists()){
booleanret=dest.mkdir();
if(ret==false)
return;
}
File[]fs=src.listFiles();
for(inti=0;i<fs.length;i++){
cp(fs[i],newFile(dest,fs[i].getName()));
}
return;
}
byte[]buf=newbyte[1024];
FileInputStreamin=newFileInputStream(src);
FileOutputStreamout=newFileOutputStream(dest);
intlen;
try{
while((len=in.read(buf))>0){
out.write(buf,0,len);
}
}finally{
in.close();
out.close();
}
}
publicvoiddragExit(DropTargetEventdte){
}
}
classFileNodeextendsDefaultMutableTreeNode{
privatebooleanexplored=false;
publicFileNode(Filefile){
setUserObject(file);
}
publicbooleangetAllowsChildren(){
returnisDirectory();
}
publicbooleanisLeaf(){
return!isDirectory();
}
publicFilegetFile(){
return(File)getUserObject();
}
publicbooleanisExplored(){
returnexplored;
}
publicbooleanisDirectory(){
Filefile=getFile();
returnfile.isDirectory();
}
publicStringtoString(){
Filefile=(File)getUserObject();
Stringfilename=file.toString();
intindex=filename.lastIndexOf(File.separator);
return(index!=-1&&index!=filename.length()-1)?filename
.substring(index+1):filename;
}
publicvoidexplore(){
if(!isDirectory())
return;
if(!isExplored()){
Filefile=getFile();
File[]children=file.listFiles();
for(inti=0;i<children.length;++i){
if(children[i].isDirectory())
add(newFileNode(children[i]));
}
for(inti=0;i<children.length;++i){
if(!children[i].isDirectory())
add(newFileNode(children[i]));
}
explored=true;
}
}
publicvoidreexplore(){
this.removeAllChildren();
explored=false;
explore();
}
}
利用办法示例:
importjava.awt.BorderLayout;
importjava.awt.Dimension;
importjava.awt.datatransfer.DataFlavor;
importjava.awt.datatransfer.Transferable;
importjava.awt.datatransfer.UnsupportedFlavorException;
importjava.awt.dnd.DnDConstants;
importjava.awt.dnd.DropTarget;
importjava.awt.dnd.DropTargetDragEvent;
importjava.awt.dnd.DropTargetDropEvent;
importjava.awt.dnd.DropTargetEvent;
importjava.awt.dnd.DropTargetListener;
importjava.awt.event.WindowAdapter;
importjava.awt.event.WindowEvent;
importjava.io.File;
importjava.io.FileReader;
importjava.io.IOException;
importjava.util.Iterator;
importjava.util.List;
importjavax.swing.BorderFactory;
importjavax.swing.JEditorPane;
importjavax.swing.JFrame;
importjavax.swing.JPanel;
importjavax.swing.JScrollPane;
importjavax.swing.JSplitPane;
importjavax.swing.UIManager;
importjavax.swing.WindowConstants;
importjavax.swing.filechooser.FileSystemView;
importjavax.swing.text.Document;
importjavax.swing.text.EditorKit;
publicclassTestextendsJFrameimplementsDropTargetListener{
privateJEditorPanetextPane=newJEditorPane();
publicTest(){
super("DragandDropWithSwing");
newDropTarget(textPane,DnDConstants.ACTION_COPY_OR_MOVE,this);
JSplitPanesplitPane=newJSplitPane(JSplitPane.HORIZONTAL_SPLIT,
createTreePanel(),createTextPanel());
splitPane.setDividerLocation(250);
splitPane.setOneTouchExpandable(true);
getContentPane().add(splitPane,BorderLayout.CENTER);
}
publicstaticvoidmain(Stringargs[]){
try{
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
}catch(Exceptione1){
e1.printStackTrace();
}
Testtest=newTest();
test.setBounds(300,300,850,350);
test.setVisible(true);
test.setDefaultCloseOperation(WindowConstants.DISPOSE_ON_CLOSE);
test.addWindowListener(newWindowAdapter(){
publicvoidwindowClosed(WindowEvente){
System.exit(0);
}
});
}
privateJPanelcreateTreePanel(){
JPaneltreePanel=newJPanel();
DragTreetree=newDragTree();
treePanel.setLayout(newBorderLayout());
treePanel.add(newJScrollPane(tree),BorderLayout.CENTER);
treePanel.setBorder(BorderFactory
.createTitledBorder("Dragsourceforfilenames"));
returntreePanel;
}
privateJPanelcreateTextPanel(){
JPaneltextPanel=newJPanel();
textPanel.setLayout(newBorderLayout());
textPanel.add(newJScrollPane(textPane),BorderLayout.CENTER);
textPanel.setMinimumSize(newDimension(375,0));
textPanel.setBorder(BorderFactory
.createTitledBorder("Droptargetforfilenames"));
returntextPanel;
}
privatevoidreadFile(finalStringfilename){
try{
textPane.setPage(newFile(filename).toURL());
}catch(IOExceptione){
EditorKitkit=textPane.getEditorKit();
Documentdocument=textPane.getDocument();
try{
document.remove(0,document.getLength());
kit.read(newFileReader(filename),document,0);
}catch(Exceptionex){
ex.printStackTrace();
}
}
}
publicvoiddrop(DropTargetDropEvente){
try{
DataFlavorstringFlavor=DataFlavor.stringFlavor;
Transferabletr=e.getTransferable();
if(e.isDataFlavorSupported(stringFlavor)){
Stringfilename=(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);
readFile(filename);
textPane.setCaretPosition(0);
e.dropComplete(true);
}else{
e.rejectDrop();
}
}
else{
e.rejectDrop();
}
}catch(IOExceptionioe){
ioe.printStackTrace();
}catch(UnsupportedFlavorExceptionufe){
ufe.printStackTrace();
}
}
publicvoiddragEnter(DropTargetDragEvente){
}
publicvoiddragExit(DropTargetEvente){
}
publicvoiddragOver(DropTargetDragEvente){
}
publicvoiddropActionChanged(DropTargetDragEvente){
}
}
最后就是我对java的几点希望:首先是IDE工具,有人说java已经很好了,有jbuilder,eclipse,netBeans等等,但是我认为如果java想超越.net,那么他首先要解决的就是IDE工具的整合。 |
|