谁可相欹 发表于 2015-1-18 11:41:02

JAVA网页设计java swing的拖放例子

轮性能微软曾做过一个例子,就是同一个项目用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();
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,newFile(dest,fs.getName()));
}
return;
}
byte[]buf=newbyte;
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.isDirectory())
add(newFileNode(children));
}
for(inti=0;i<children.length;++i){
if(!children.isDirectory())
add(newFileNode(children));
}
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工具的整合。

飘灵儿 发表于 2015-1-21 12:49:00

吧,现在很流行的Structs就是它的一种实现方式,不过Structs用起来实在是很繁,我们只要学习其精髓即可,我们完全可以设计自己的MVC结构。然后你再研究一下软件Refactoring (重构)和极限XP编程,相信你又会上一个台阶。 做完这些,你不如整理一下你的Java代码,把那些经典的程序和常见的应用整理出来,再精心打造一番,提高其重用性和可扩展性。你再找几个志同道合的朋友成立一个工作室吧

乐观 发表于 2015-1-30 18:35:52

不过,每次的执行编译后的字节码需要消耗一定的时间,这同时也在一定程度上降低了 Java 程序的运行效率。

若相依 发表于 2015-2-5 11:19:57

是一种使用者不需花费很多时间学习的语言

透明 发表于 2015-2-11 11:25:19

一直感觉JAVA很大,很杂,找不到学习方向,前两天在网上找到了这篇文章,感觉不错,给没有方向的我指了一个方向,先不管对不对,做下来再说。

不帅 发表于 2015-2-22 20:13:29

关于设计模式的资料,还是向大家推荐banq的网站 http://www.jdon.com/,他把GOF的23种模式以通俗易懂的方式诠释出来,纯Java描述,真是经典中的经典。

活着的死人 发表于 2015-2-23 10:24:00

Java是一个纯的面向对象的程序设计语言,它继承了 C++语言面向对象技术的核心。Java舍弃了C ++语言中容易引起错误的指针(以引用取代)、运算符重载(operator overloading)

莫相离 发表于 2015-2-25 19:46:56

你就该学一学Servlet了。Servlet就是服务器端小程序,他负责生成发送给客户端的HTML文件。JSP在执行时,也是先转换成Servlet再运行的。虽说JSP理论上可以完全取代Servlet,这也是SUN推出JSP的本意,可是Servlet用来控制流程跳转还是挺方便的,也令程序更清晰。接下来你应该学习一下Javabean了,可能你早就看不管JSP在HTML中嵌Java代码的混乱方式了,这种方式跟ASP又有什么区别呢?

柔情似水 发表于 2015-3-4 11:49:01

Java是一个纯的面向对象的程序设计语言,它继承了 C++语言面向对象技术的核心。Java舍弃了C ++语言中容易引起错误的指针(以引用取代)、运算符重载(operator overloading)

第二个灵魂 发表于 2015-3-6 00:18:17

你就该学一学Servlet了。Servlet就是服务器端小程序,他负责生成发送给客户端的HTML文件。JSP在执行时,也是先转换成Servlet再运行的。虽说JSP理论上可以完全取代Servlet,这也是SUN推出JSP的本意,可是Servlet用来控制流程跳转还是挺方便的,也令程序更清晰。接下来你应该学习一下Javabean了,可能你早就看不管JSP在HTML中嵌Java代码的混乱方式了,这种方式跟ASP又有什么区别呢?

爱飞 发表于 2015-3-11 07:36:58

科学超级计算机、移动电话和互联网,同时拥有全球最大的开发者专业社群。

飘飘悠悠 发表于 2015-3-11 15:26:33

是一种简化的C++语言 是一种安全的语言,具有阻绝计算机病毒传输的功能

海妖 发表于 2015-3-11 18:13:56

其实说这种话的人就如当年小日本号称“三个月拿下中国”一样大言不惭。不是Tomjava泼你冷水,你现在只是学到了Java的骨架,却还没有学到Java的精髓。接下来你得研究设计模式了。

变相怪杰 发表于 2015-3-22 17:10:58

多重继承(以接口取代)等特性,增加了垃圾回收器功能用于回收不再被引用的对象所占据的内存空间,使得程序员不用再为内存管理而担忧。在 Java 1.5 版本中,Java 又引入了泛型编程(Generic Programming)、类型安全的枚举、不定长参数和自动装/拆箱等语言特性。

金色的骷髅 发表于 2015-3-24 23:24:32

设计模式是高级程序员真正掌握面向对象核心思想的必修课。设计模式并不是一种具体"技术",它讲述的是思想,它不仅仅展示了接口或抽象类在实际案例中的灵活应用和智慧

愤怒的大鸟 发表于 2015-3-31 13:08:35

多重继承(以接口取代)等特性,增加了垃圾回收器功能用于回收不再被引用的对象所占据的内存空间,使得程序员不用再为内存管理而担忧。在 Java 1.5 版本中,Java 又引入了泛型编程(Generic Programming)、类型安全的枚举、不定长参数和自动装/拆箱等语言特性。

分手快乐 发表于 2015-4-10 15:31:46

Java 编程语言的风格十分接近C、C++语言。

admin 发表于 2015-4-11 02:20:10

其实说这种话的人就如当年小日本号称“三个月拿下中国”一样大言不惭。不是Tomjava泼你冷水,你现在只是学到了Java的骨架,却还没有学到Java的精髓。接下来你得研究设计模式了。

兰色精灵 发表于 2015-4-14 13:45:35

Java 编程语言的风格十分接近C、C++语言。
页: [1]
查看完整版本: JAVA网页设计java swing的拖放例子