- 浏览: 484617 次
- 性别:
- 来自: 北京
文章分类
- 全部博客 (301)
- Swing技术 (1)
- Linux (1)
- Javascript (22)
- 数据结构和算法 (3)
- J2SE (36)
- workflow (5)
- 设计模式 (14)
- web service (19)
- Ajax (14)
- 中间件 & 服务器 (8)
- 多线程 (9)
- Oracle (52)
- sys & soft (10)
- JMS (3)
- sso (9)
- android (11)
- struts2 (10)
- web协议 (2)
- 分布式 (2)
- PM (2)
- OLAP (3)
- Redis (2)
- Hibernate (7)
- ibatis (2)
- SQLServer (1)
- maven (3)
- Spring (7)
- Jsp (2)
- slf4j (1)
- jQuery (15)
- 权限 (1)
- 系统集成 (1)
- 笔记 (1)
- Freemarker (2)
- 项目管理 (1)
- eclipse (3)
- GIS (1)
- NoSql (3)
- win10 (1)
- win10网络 (2)
- 底层 (3)
- 数据库 (0)
最新评论
-
kabuto_v:
请问那种图,uml图是怎么画出来的呢?是您自己手工画的,还是有 ...
FastJSON 序列化、反序列化实现 -
梦行Monxin商城系统:
电商实例、业务并发、网站并发及解决方法 -
rockethj8:
client 㓟有一个参数是可以忽略一些URL 不进行验证登录 ...
SSO 之 (单点登录)实施中遇到的几个问题 -
mengxiangfeiyan:
好啊。。。。。
Oracle删除表,删除数据以及恢复数据、利用现有表创建新表
收藏列表
- 全部 [13]
- javascript [1]
- ajax [1]
- webservice [1]
- j2se [5]
- 24 [1]
- 26 [1]
- 25 [1]
- javascript_jquery [1]
- javascript+css-web前端 [1]
标题 | 标签 | 来源 | |
WebService 之 返回xml | webservice | http://java.chinaitlab.com/net/810900.html | |
import java.io.IOException; import java.io.InputStream; import java.net.MalformedURLException; import java.net.URL; import java.net.URLConnection; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.PrintWriter; import org.w3c.dom.Document; import org.w3c.dom.DOMException; import org.xml.sax.SAXException; import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; import javax.xml.parsers.ParserConfigurationException; import javax.xml.transform.OutputKeys; import javax.xml.transform.Transformer; import javax.xml.transform.TransformerConfigurationException; import javax.xml.transform.TransformerException; import javax.xml.transform.TransformerFactory; import javax.xml.transform.dom.DOMSource; import javax.xml.transform.stream.StreamResult; /*** * @author xuechong * 6/11/2010 16:58 * DomXMLString.java * 概述:纯java方式访问远程WebService接口返回的xml格式的数据保存在本地 */ public class DomXMLString{ private static String SERVICES_HOST = "www.webxml.com.cn"; //远程WebService接口url private static String NETDATA_URL = "http://webservice.webxml.com.cn/WebServices/WeatherWS.asmx/getRegionProvince"; //访问远程WebService接口返回的xml格式的数据保存在本地的绝对路径 private static String LOCAL_PC_SAVEFILE_URL = "E:dataTest/netDataToLocalFile.xml"; private DomXMLString(){} public static void main(String[] args) throws Exception{ Document document = getProvinceCode(NETDATA_URL); helloOK(document, LOCAL_PC_SAVEFILE_URL); } /*返回一个Document对象*/ public static Document getProvinceCode(String netXMLDataURL){ Document document = null; DocumentBuilderFactory documentBF = DocumentBuilderFactory.newInstance(); documentBF.setNamespaceAware(true); try{ DocumentBuilder documentB = documentBF.newDocumentBuilder(); InputStream inputStream = getSoapInputStream(netXMLDataURL); //具体webService相关 document = documentB.parse(inputStream); inputStream.close(); }catch(DOMException e){ e.printStackTrace(); return null; }catch(ParserConfigurationException e){ e.printStackTrace(); return null; }catch (SAXException e){ e.printStackTrace(); return null; }catch(IOException e){ e.printStackTrace(); return null; } return document; } /*返回InputStream对象*/ public static InputStream getSoapInputStream(String url){ InputStream inputStream = null; try{ URL urlObj = new URL(url); URLConnection urlConn = urlObj.openConnection(); urlConn.setRequestProperty("Host", SERVICES_HOST); //具体webService相关 urlConn.connect(); inputStream = urlConn.getInputStream(); }catch(MalformedURLException e){ e.printStackTrace(); }catch(IOException e){ e.printStackTrace(); } return inputStream; } /*访问远程(WebService)xml数据后返回的xml格式字符串并生成为本地文件*/ public static void helloOK(Document document, String savaFileURL){ TransformerFactory transF = TransformerFactory.newInstance(); try{ Transformer transformer = transF.newTransformer(); DOMSource source = new DOMSource(document); transformer.setOutputProperty(OutputKeys.ENCODING, "UTF-8"); transformer.setOutputProperty(OutputKeys.INDENT, "YES"); PrintWriter pw = new PrintWriter(new FileOutputStream(savaFileURL)); StreamResult result = new StreamResult(pw); transformer.transform(source, result); System.out.println("生成xml文件成功!"); }catch(TransformerConfigurationException e){ System.out.println(e.getMessage()); }catch(IllegalArgumentException e){ System.out.println(e.getMessage()); }catch(FileNotFoundException e){ System.out.println(e.getMessage()); }catch(TransformerException e){ System.out.println(e.getMessage()); } } } |
|||
Jsp 应用之自定义标签库(taglib)及配置 | j2se | Jsp 应用之自定义标签库(taglib)及配置 | |
/* taglib的主要作用就是:对一些需要重复利用的代码段进行封装,并设置该代码段可能用到的属性,提高代码的利用率。 taglib主要有三个部分构成: 实现代码段的.java文件; 标签库描述文件.tld; web.xml的配置。 下面首先介绍标签实现文件,这里以DecorTag.java实现的标签为例: */ //DecorTag.java /* * DecorTag.java * * Created on 2007年3月17日, 上午8:25 */ package com.wlmzfx.servlet; import javax.servlet.jsp.*;//jsp类 import javax.servlet.jsp.tagext.*;//标签类库 import java.io.IOException; //这里实现一个用html表格显示一个装饰框 public class DecorTag extends TagSupport{ //这些字段用来控制外观 String align;//对齐方式 String title;//标题 String titleColor;//标题前景色 String titleAlign;//标题对齐方式 String color;//方框背景色 String borderColor;//边框颜色 String margin;//边框与内容之间的像素 String borderWidth;//边框宽度的像素值 //以下方法用来设置各种属性值,是必不可少的,在jsp页面使用标签时,属性将转化为方法调用 public void setAlign(String value){ this.align = value; } public void setTitle(String value){ this.title = value; } public void setTitleColor(String value){ this.titleColor = value; } public void setTitleAlign(String value){ this.titleAlign = value; } public void setColor(String value){ this.color = value; } public void setBorderColor(String value) { this.borderColor = value; } public void setMargin(String value){ this.margin = value; } public void setBorderWidth(String value){ this.borderWidth = value; } public void setPageContext(PageContext context){ //以超类保存页面环境对象,下面的Tag()要用到,这很重要 super.setPageContext(context); //设置属性的默认值 align = “cente”; title = null; titleColor = “White”; titleAlign = “left”; color = “lightblue”; borderColor = “black”; margin = “20″; borderWidth = “4″; } /** *此方法再遇到<decor:box>标签时调用 **/ public int doStartTag() throws JspException{ try{ //从PageContext对象获取输出流并传给setPageContext()方法 JspWriter out = pageContext.getOut(); out.print(”<div align=’”+align+”‘>”+”<table bgcolor=’”+borderColor+”‘”+”<border=’0′ cellspacing=’0′”+”cellpadding=’”+borderWidth+”‘”); if(title != null) out.print(”<tr><td align=’”+titleAlign+”‘>”+”<font face=’helvetica’ size=’+1′ “+”color=’”+titleColor+”‘><br>”+title+”</b></font></td><td>”); out.print(”<tr><td<table bgcolor=’”+color+”‘”+”border=’0′ cellspacing=’0′”+”cellpadding=’”+margin+”‘><tr><td>”); }catch(IOException e){ throw new JspException(e.getMessage()); } //返回值告诉Jsp类处理标签主题 return EVAL_BODY_INCLUDE; } //在遇到</decor:box>结束标签时调用 public int doEndTag()throws JspException{ try{ JspWriter out = pageContext.getOut(); out.println(”</td></tr></table><td><tr><table></div>”); }catch(IOException e){ throw new JspException(e.getMessage()); } //返回值指示继续处理Jsp页面 return EVAL_PAGE; } } //decor_1_0.tld(放在WEB-INF/tids/decor_1_0.tld //一般以后缀_1_0来表示tld文件的版本,实际上这也是个xml文件 <?xml version=”1.0″ encoding=”UTF-8″?> <taglib version=”2.0″ xmlns=”http://java.sun.com/xml/ns/j2ee” xmlns:xsi=”http://www.w3.org/2001/XMLSchema-instance” xsi:schemaLocation=”http://java.sun.com/xml/ns/j2ee web-jsptaglibrary_2_0.xsd”> <tlib-version>1.0</tlib-version><!–文件版本–> <short-name>decor</short-name><!–库名–> <uri>http://www.wlmzfx.com/tlds/decor_1_0.tld</uri><!–唯一标识符–> <tag><!–首先定义了标签库的一个标签–> <name>box</name><!–首先定义标签名,实现类–> <tagclass>com.wlmzfx.servlet.DecorTag</tagclass> <!–定义标签库的每一个属性–> <attribute> <name>align</name><!–属性–> <required>false</required><!–不是必须–> <rtexprvalue>true</rtexprvalue><!–应有<%= %>值–> </attribute> <attribute> <name>color</name> <required>false</required> <rtexprvalue>true</rtexprvalue> </attribute> <attribute> <name>bordercolor</name> <required>false</required> <rtexprvalue>true</rtexprvalue> </attribute> <attribute> <name>margin</name> <required>false</required> <rtexprvalue>true</rtexprvalue> </attribute> <attribute> <name>borderWidth</name> <required>false</required> <rtexprvalue>true</rtexprvalue> </attribute> <attribute> <name>title</name> <required>false</required> <rtexprvalue>true</rtexprvalue> </attribute> <attribute> <name>titleColor</name> <required>false</required> <rtexprvalue>true</rtexprvalue> </attribute> <attribute> <name>titleAlign</name> <required>false</required> <rtexprvalue>true</rtexprvalue> </attribute> </tag> <!– A validator verifies that the tags are used correctly at JSP translation time. Validator entries look like this: <validator> <validator-class>com.mycompany.TagLibValidator</validator-class> <init-param> <param-name>parameter</param-name> <param-value>value</param-value> </init-param> </validator> –> <!– A tag library can register Servlet Context event listeners in case it needs to react to such events. Listener entries look like this: <listener> <listener-class>com.mycompany.TagLibListener</listener-class> </listener> –> </taglib> 然后需要在web.xml中配置该标签,在web.xml中添加下面的内容: <taglib> <!–看到标签库唯一标识符时–> <taglib-uri>http://www.wlmzfx.com/tlds/decor_1_0.tld</taglib-uri> <!–使用标签库描述文件的本地副本–> <taglib-location>tlds/decor_1_0.tld</taglib-location> </taglib> 下面以一个例子来说明该标签库的用法: 在任何jsp页面中加入下面的代码: <!–这里仅仅定义了title,color,margin属性–> <decor:box title=”LogOut when Done” color=”red” margin=”100″> <!–这里添加表格的内容,这里可以继续使用<decor:box>标签,但是同样必须以</decor:box>结束–> 内容在这里 </decor:box> |
|||
JNDI 操作文件系统 | j2se | JNDI 操作文件系统 | |
JNDI 操作文件系统 环境: JDK1.6 Jar包准备: fscontext.jar、providerutil.jar 下载:http://www.oracle.com/technetwork/java/javasebusiness/downloads/java-archive-downloads-java-plat-419418.html#7110-jndi-1.2.1-oth-JPR JNDI 操作 File System - 小奋斗--浪子 - 小奋斗 浪子 -------------------------------------------------------------------------------------------------------------------------------------------------- 操作案例代码: package com.nice.files; import java.util.Hashtable; import javax.naming.Binding; import javax.naming.CompositeName; import javax.naming.Context; import javax.naming.InitialContext; import javax.naming.NameClassPair; import javax.naming.NameNotFoundException; import javax.naming.NamingEnumeration; import javax.naming.NamingException; import com.sun.jndi.fscontext.RefFSContext; public class FileSystemTest { public static InitialContext createContext(String fileURL) throws NamingException{ Hashtable<String,String> env = new Hashtable<String,String>(); env.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.fscontext.RefFSContextFactory"); env.put(Context.PROVIDER_URL,fileURL); return new InitialContext(env); } // 增加 public static void addDirectory(Context context,String baseName,String name) throws Exception{ RefFSContext refCtx = (RefFSContext)context.lookup(baseName); refCtx.createSubcontext(new CompositeName(name)); } // 删除 public static void deleteDirectory(Context context,String baseName,String name) throws Exception{ RefFSContext refCtx = (RefFSContext)context.lookup(baseName); refCtx.destroySubcontext(name); } // 修改 public static void modifyDirectory(Context context,String baseName,String oldName, String newName)throws Exception{ RefFSContext refCtx = (RefFSContext)context.lookup(baseName); refCtx.rename(oldName, newName); } // 查找是否存在 public static boolean findDirectory(Context context,String baseName,String name) throws NamingException{ RefFSContext refCtx = (RefFSContext)context.lookup(baseName); try{ RefFSContext subRefCtx = (RefFSContext)refCtx.lookup(name); if(subRefCtx!=null){ System.out.println("存在 : " + name); return true; } }catch(NameNotFoundException e){ } System.out.println("不存在 : " + name); return false; } // 搜索 public static void searchFile(Context context)throws Exception{ String nameInSpace = context.getNameInNamespace(); System.out.println("nameInSpace : " + nameInSpace); NamingEnumeration<NameClassPair> nEnum= context.list(nameInSpace); int total = 0; while(nEnum.hasMoreElements()){ NameClassPair pair = nEnum.nextElement(); if("javax.naming.Context".equals(pair.getClassName())){ System.out.println("目录: " + pair.getName()); }else if("java.io.File".equals(pair.getClassName())){ System.out.println("文件: " + pair.getName()); } total ++ ; } System.out.println("数量: " + total); } public static void searchBinddingFile(Context context)throws Exception{ String nameInSpace = context.getNameInNamespace(); System.out.println("nameInSpace : " + nameInSpace); NamingEnumeration<Binding> nEnum= context.listBindings(nameInSpace); int total = 0; while(nEnum.hasMoreElements()){ Binding bind = nEnum.nextElement(); if("com.sun.jndi.fscontext.RefFSContext".equals(bind.getClassName())){ System.out.println("目录: " + bind.getName()); }else if("java.io.File".equals(bind.getClassName())){ System.out.println("文件: " + bind.getName()); } total ++ ; } System.out.println("数量: " + total); } /** * @param args */ public static void main(String[] args)throws Exception { InitialContext context = createContext("file:///c:/html/"); RefFSContext refCtx = (RefFSContext)context.lookup("/images/images"); String nameInSpace = context.getNameInNamespace(); // 增加 //addDirectory(context,nameInSpace+"/images/images/","test123"); // 修改 //modifyDirectory(context,nameInSpace+"/images/images/","test","test2"); // 删除 //deleteDirectory(context,nameInSpace+"/images/images/","test"); // 查找 findDirectory(context,nameInSpace,"test"); // 搜索 searchFile(context); searchBinddingFile(context); searchFile(refCtx); searchBinddingFile(refCtx); } } |
|||
固定悬浮层 | javascript+css-web前端 | 支持各种浏览器的固定悬浮层 | |
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <title>中国站长天空-网页特效-窗口特效-支持各种浏览器的固定悬浮层</title> <meta http-equiv="content-type" content="text/html;charset=gb2312"> <!--把下面代码加到<head>与</head>之间--> <style type="text/css"> * {padding:0; margin:0;} body {height:100%; overflow:hidden; font-size:14px; line-height:2; position:relative;} html {height:100%; overflow:hidden;} .fixed {position:absolute; top:10px; left:50%; width:100px; margin-left:-490px; height:350px; background:#fc0; border:1px solid #f60; text-align:center;} .fixed2 {position:absolute; top:10px; left:50%; width:100px; margin-left:370px; height:350px; background:#fc0; border:1px solid #f60; text-align:center;} .wrapper {height:100%; overflow:auto; overflow-y:scroll;} .body {width:700px; margin:0 auto; background:#f2f2f2; padding:20px;} </style> </head> <body> <!--把下面代码加到<body>与</body>之间--> <div class="fixed">左侧固定悬浮</div> <div class="fixed2">右侧固定悬浮</div> <div class="wrapper"> <div class="body"> [专业 » 产业观察] 彩虹显IP怕成被告?TX给彩虹暗示? jarry 2008-11-17 <br /> [专业 » 产业观察] 上海东楼Kappa女:互联网的作用=炒作? jarry 2008-11-13 <br /> [专业 » 产业观察] 全球性商务人脉网络平台:XING.com jarry 2008-11-1 <br /> [专业 » 产业观察] 什么是口碑营销? jarry 2008-10-17 <br /> [专业 » 产业观察] 第二届 Open Web 大赛开幕 jarry 2008-10-16 <br /> [专业 » 产业观察] 百度有啊C2C网络交易平台即将上线 jarry 2008-10-12 <br /> [专业 » 产业观察] 首款谷歌Android手机高调上市 jarry 2008-10-10 <br /> [专业 » 产业观察] 七个获得订阅用户的黑色真理 jarry 2008-10-8 <br /> [专业 » 产业观察] 靠写博客赚钱的五个必要条件 jarry 2008-10-7 <br /> [专业 » 产业观察] Windows Live Messenger 9 Wave3 最终发布日期确定 jarry 2008-10-6 <br /> [专业 » 产业观察] 2008中国互联网大会昨日开幕 jarry 2008-9-24 <br /> [专业 » 产业观察] 有道热闻上线! jarry 2008-9-19 <br /> [专业 » 产业观察] Phpcms 2008 测试版9月1日开源免费发布 jarry 2008-9-17 <br /> [专业 » 产业观察] 电脑报介绍的adobe air应用 jarry 2008-9-10 <br /> [专业 » 产业观察] WordCamp China 2008即将召开 jarry 2008-8-28 <br /> [专业 » 产业观察] 开发硬件防火墙的主要步骤 jarry 2008-8-11 <br /> [专业 » 产业观察] 细数20个Windows 7应该拥有的功能 - Windows 7之家--iWindows7.com jarry 2008-8-6 <br /> [专业 » 产业观察] 互联网运营者和互联网评论者 jarry 2008-6-22 <br /> [专业 » 产业观察] 有趣的BlogBus暂停服务提示 jarry 2008-6-12 <br /> [专业 » 产业观察] 谁收入最高?程序员收入大比拼 jarry 2008-6-11 <br /> [专业 » 产业观察] Blog营销的特征 jarry 2008-6-10 <br /> [专业 » 产业观察] 推荐一个文内广告平台:群视 jarry 2008-6-8 <br /> [专业 » 产业观察] Google官方解释为何更换小图标 jarry 2008-6-8 <br /> [专业 » 产业观察] 二十年前的1GB jarry 2008-6-8 <br /> [专业 » 产业观察] 【pr=7,震古铄今,PR=8,天人合一】PR境界谈 jarry 2008-6-8 <br /> [专业 » 产业观察] 大网站谎言,你有没有被欺骗过 jarry 2008-6-8 <br /> [专业 » 产业观察] blog.35免费绑定域名的wp服务 jarry 2008-6-7 <br /> [专业 » 产业观察] 腾讯SNS:QQ校友开始内测 jarry 2008-6-7 <br /> [专业 » 产业观察] 衡量博客价值七个指标 jarry 2008-6-6 <br /> [专业 » 产业观察] 另类思维:百度是嫖客 我(站长)要学会做小姐 jarry 2008-6-6 <br /> [专业 » 产业观察] 中国电信承接CDMA后的运营策略 jarry 2008-6-5 <br /> [专业 » 产业观察] 微软新系统Windows 7桌面截图(16pics) jarry 2008-6-5 <br /> [专业 » 产业观察] 3G门户:无线互联网门户网站 jarry 2008-6-5 <br /> [专业 » 产业观察] Retaggr:个性化名片制作 jarry 2008-6-3 <br /> [专业 » 产业观察] Acrobat:Adobe的网络办公室 jarry 2008-6-3 <br /> [专业 » 产业观察] 影响博客互动运营的八大因素 jarry 2008-6-2 <br /> [专业 » 产业观察] 影响中国人通讯习惯的十家公司 jarry 2008-6-2 <br /> [专业 » 产业观察] 5月浏览器大战升级 FireFox 3份额提升 jarry 2008-6-2 <br /> [专业 » 产业观察] 为什么很多博客赚不到钱? jarry 2008-5-31 <br /> [专业 » 产业观察] VIA OpenBook迷你笔记本实物图 jarry 2008-5-31 <br /> [专业 » 产业观察] 人肉搜索:天使还是魔鬼? jarry 2008-5-30 <br /> [专业 » 产业观察] 360doc:个人图书馆,网页在线收藏 jarry 2008-5-30 <br /> [专业 » 产业观察] 时光网:电影、社区、你和我 jarry 2008-5-30 <br /> [专业 » 产业观察] 十大最让人恼火的软件 jarry 2008-5-27 <br /> [专业 » 产业观察] 付钱让员工辞职,Zappos 的成功秘诀 jarry 2008-5-27 <br /> [专业 » 产业观察] 三部委发布电信业重组公告 完成后发三张3G牌照 jarry 2008-5-25 <br /> [专业 » 产业观察] QQ网络硬盘网页版秘密发布 jarry 2008-5-25 <br /> [专业 » 产业观察] Google Sites开始向所有人免费开放 建立自己的个人主页 jarry 2008-5-23 <br /> [专业 » 产业观察] 10个不为人知的Google失败作品 jarry 2008-5-22 <br /> [专业 » 产业观察] C2Call:基于Web浏览器的网络电话服务 jarry 2008-5-21 <br /> [专业 » 产业观察] 微软放弃Vista 用Windows 7取而代之 jarry 2008-5-21 <br /> [专业 » 产业观察] 2008年不可错过的Web2.0产品 jarry 2008-5-21 <br /> [专业 » 产业观察] 在 Google Earth 上看新闻 jarry 2008-5-21 <br /> [专业 » 产业观察] 全国哀悼日CCTV启用wenchuan.cn域名 jarry 2008-5-20 <br /> [专业 » 产业观察] 微软抗衡谷歌计划:200亿并购Facebook jarry 2008-5-20 <br /> [专业 » 产业观察] 还有什么不能卖?-ebay 十大火星拍卖 jarry 2008-5-19 <br /> [专业 » 产业观察] 互联网营销——互联网是手段,营销才是本质 jarry 2008-5-13 <br /> [专业 » 产业观察] 中移动手机邮箱也抄袭? jarry 2007-11-2 <br /> [专业 » 产业观察] TNND,要彻底放弃MSN了。 jarry 2007-6-11 <br /> [专业 » 产业观察] 好玩的在线工具 jarry 2006-11-11 <br /> [专业 » 产业观察] 让收费网站去死吧,用google 突破!! jarry 2005-11-20 <br /> </div> </div> </body> </html> |
|||
ajax取数据库中的值以xml形式返回到jsp页面,dom读取并用表格显示 | ajax | 用AJAX异步交互返回xml文件从jsp页面中读取并用表格显示 | |
用AJAX异步交互返回xml文件从jsp页面中读取并用表格显示 用ajax的异步交互去获取用hibernate的技术得到的数据库中的值并且用xml的形式返回jsp页面,用dom元素读取并用表格的形式显示 这里需要注意的是hibernate的搭建,我在搭建hibernate的时候得到一个结论,在MyEclipse8.6和MyEclipse9.0中使用的hibernate.cfg.xml中的语句不一样。要注意!最好是用工具生成! 在用AJAX技术来实践异步交互,用七步,在写的其中,要注意该有分号的有,不该有的别有。 (1)创建xmlhttpRequest对象 因为ajax其实就是xmlhttpRequest,所以要创建xmlhttpRequest (1) (2) //创建xmlHttpRequest对象 (3) function createXMLHttpRequest() { (4) var xmlHttp; (5) try { (6) //在firefox opera等非浏览器中运行的 (7) xmlHttp = new XMLHttpRequest(); (8) (9) } catch (ex) { (10) try { (11) //在IE中运行 运行的是第二个版本 (12) xmlHttp = new ActiveXObject("MSXML2.XMLHTTP"); (13) } catch (e) { (14) // 在IE中运行第一个版本 (15) xmlHttp = new ActiveXObject("Microsoft.XMLHTTP"); (16) } (17) } (18) return xmlHttp; (19) } (2)使用的html代码 <body> <div align="center"> <h1> 员工信息 </h1> <br /> <input type="button" value="查询员工" id="btnEmp" /> <br /> <br /> <br /> <div id="list"> <table id="empList" border="1px"> </table> </div> </div> </body> (3)初始化对象并通过触发事件来请求到servlet中 //页面加载并调用匿名函数 window.onload = function() { //第一步:初始化xmlHttpRequest对象 var xmlHttp = createXMLHttpRequest(); var btnEmpNode = document.getElementById("btnEmp"); btnEmpNode.onclick = function() { xmlHttp.onreadystatechange = function() { if (xmlHttp.readyState == 4) { //通过判断返回的状态码来 验证返回的页面是否正确 if (xmlHttp.status == 200) { var xmlDoc = xmlHttp.responseXML; //第六步:客户端接受 var empNodes = xmlDoc.getElementsByTagName("emp"); var len = empNodes.length; //第七步:修改内容 for ( var i = 0; i < len; i++) { //第一种方法是从获取到的dom元素中读取出来 ,但是读取的是每一个emp下的所有的的字符,因为输出不可以换行,所以读取到jsp页面的没有table的效果 //var empTextNodes = empNodes[i].textContent; //alert(empTextNodes); //所以用到第二种方法 :先得到emp下的子标签,在通过子标签的属性得到text文本 //创建tr标签 var trNodes = document.createElement("tr"); //得到的是emp的子节点 var childrenNode = empNodes[i].children; var length = childrenNode.length; for ( var j = 0; j < length; j++) { //动态创建td节点 var tdNodes = document.createElement("td"); //获取到子节点中的的text var childvalue = childrenNode[j].firstChild.nodeValue; //创建文本,把获取大的text放到创建的文本中 var value = document.createTextNode(childvalue); //把value值放到td中 tdNodes.appendChild(value); //把td放到tr中 trNodes.appendChild(tdNodes); } //获取table的id var empListNodes = document.getElementById("empList"); //把tr插入到table中 empListNodes.appendChild(trNodes); } } } } //第二步:规定请求的参数 xmlHttp.open("GET", "./employeeServlet.do?timeStamp=" + new Date().getTime(), true); //在这里用的是get方法,不用post方法 xmlHttp.send(null); } } 在servelt中获取请求和应答分别是第四步和第五步 public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setCharacterEncoding("utf-8"); response.setContentType("text/xml;charset=utf-8"); List<Employee> entities = employeeServlet.findAll(); PrintWriter out = response.getWriter(); out.println("<?xml version=\"1.0\" encoding=\"UTF-8\"?>"); out.println("<emps>"); for (int i = 0; i < entities.size(); i++) { Employee entity = entities.get(i); out.println("<emp id='" + entity.getId() + "'>"); out.println("<name>" + entity.getHrName() + "</name>"); out.println("<sex>" + entity.getHrSex() + "</sex>"); out.println("<age>" + entity.getHrAge() + "</age>"); out.println("<birth>"+entity.getHrBirth()+"</birth>"); out.println("<salary>" + entity.getHrSalary() + "</salary>"); out.println("</emp>"); } out.println("</emps>"); out.flush(); out.close(); } |
|||
使用Jquery在一个jsp页面的一个div中异步加载子页面 | javascript_jquery | 使用Jquery在一个jsp页面的一个div中异步加载子页面 | |
1.A.html Java代码 ] <html> <head> <script type="text/javascript" src="js/jquery-1.7.1.min.js"> </script> <script type="text/javascript" src="ab.js"> </script> </head> <body> <input type="button" value="点我" id="a"> <div id="cont"></div> </body> </html> 2.ab.js Java代码 $(document).ready(function(){ alert("A页面"); $("#a").click(function() { alert('加载B页面'); $('#cont').load("B.html"); }); }); 3.B.html Java代码 <h1> this is b </h1> <input type="button" value="" id="b"> <script type="text/javascript"> $("#b").click(function() { alert("123"); }); </script> 不过不知道为什么,加载进来的B中,如果有中文会是乱码, |
|||
javascript 常用代码大全1 | javascript | javascript 常用代码大全(超级收藏,强烈推荐)(3) | |
针对javascript的几个对象的扩充函数 function checkBrowser() { this.ver=navigator.appVersion this.dom=document.getElementById?1:0 this.ie6=(this.ver.indexOf("MSIE 6")>-1 && this.dom)?1:0; this.ie5=(this.ver.indexOf("MSIE 5")>-1 && this.dom)?1:0; this.ie4=(document.all && !this.dom)?1:0; this.ns5=(this.dom && parseInt(this.ver) >= 5) ?1:0; this.ns4=(document.layers && !this.dom)?1:0; this.mac=(this.ver.indexOf('Mac') > -1) ?1:0; this.ope=(navigator.userAgent.indexOf('Opera')>-1); this.ie=(this.ie6 || this.ie5 || this.ie4) this.ns=(this.ns4 || this.ns5) this.bw=(this.ie6 || this.ie5 || this.ie4 || this.ns5 || this.ns4 || this.mac || this.ope) this.nbw=(!this.bw) return this; } /* ****************************************** 日期函数扩充 ****************************************** */ /* =========================================== //转换成大写日期(中文) =========================================== */ Date.prototype.toCase = function() { var digits= new Array('零','一','二','三','四','五','六','七','八','九','十','十一','十二'); var unit= new Array('年','月','日','点','分','秒'); var year= this.getYear() + ""; var index; var output=""; ////////得到年 for (index=0;index<year.length;index++ ) { output += digits[parseInt(year.substr(index,1))]; } output +=unit[0]; ///////得到月 output +=digits[this.getMonth()] + unit[1]; ///////得到日 switch (parseInt(this.getDate() / 10)) { case 0: output +=digits[this.getDate() % 10]; break; case 1: output +=digits[10] + ((this.getDate() % 10)>0?digits[(this.getDate() % 10)]:""); break; case 2: case 3: output +=digits[parseInt(this.getDate() / 10)] + digits[10] + ((this.getDate() % 10)>0?digits[(this.getDate() % 10)]:""); default: break; } output +=unit[2]; ///////得到时 switch (parseInt(this.getHours() / 10)) { case 0: output +=digits[this.getHours() % 10]; break; case 1: output +=digits[10] + ((this.getHours() % 10)>0?digits[(this.getHours() % 10)]:""); break; case 2: output +=digits[parseInt(this.getHours() / 10)] + digits[10] + ((this.getHours() % 10)>0?digits[(this.getHours() % 10)]:""); break; } output +=unit[3]; if(this.getMinutes()==0&&this.getSeconds()==0) { output +="整"; return output; } ///////得到分 switch (parseInt(this.getMinutes() / 10)) { case 0: output +=digits[this.getMinutes() % 10]; break; case 1: output +=digits[10] + ((this.getMinutes() % 10)>0?digits[(this.getMinutes() % 10)]:""); break; case 2: case 3: case 4: case 5: output +=digits[parseInt(this.getMinutes() / 10)] + digits[10] + ((this.getMinutes() % 10)>0?digits[(this.getMinutes() % 10)]:""); break; } output +=unit[4]; if(this.getSeconds()==0) { output +="整"; return output; } ///////得到秒 switch (parseInt(this.getSeconds() / 10)) { case 0: output +=digits[this.getSeconds() % 10]; break; case 1: output +=digits[10] + ((this.getSeconds() % 10)>0?digits[(this.getSeconds() % 10)]:""); break; case 2: case 3: case 4: case 5: output +=digits[parseInt(this.getSeconds() / 10)] + digits[10] + ((this.getSeconds() % 10)>0?digits[(this.getSeconds() % 10)]:""); break; } output +=unit[5]; return output; } /* =========================================== //转换成农历 =========================================== */ Date.prototype.toChinese = function() { //暂缺 } /* =========================================== //是否是闰年 =========================================== */ Date.prototype.isLeapYear = function() { return (0==this.getYear()%4&&((this.getYear()%100!=0)||(this.getYear()%400==0))); } /* =========================================== //获得该月的天数 =========================================== */ Date.prototype.getDayCountInMonth = function() { var mon = new Array(12); mon[0] = 31; mon[1] = 28; mon[2] = 31; mon[3] = 30; mon[4] = 31; mon[5] = 30; mon[6] = 31; mon[7] = 31; mon[8] = 30; mon[9] = 31; mon[10] = 30; mon[11] = 31; if(0==this.getYear()%4&&((this.getYear()%100!=0)||(this.getYear()%400==0))&&this.getMonth()==2) { return 29; } else { return mon[this.getMonth()]; } } /* =========================================== //日期比较 =========================================== */ Date.prototype.Compare = function(objDate) { if(typeof(objDate)!="object" && objDate.constructor != Date) { return -2; } var d = this.getTime() - objDate.getTime(); if(d>0) { return 1; } else if(d==0) { return 0; } else { return -1; } } /* =========================================== //格式化日期格式 =========================================== */ Date.prototype.Format = function(formatStr) { var str = formatStr; str=str.replace(/yyyy|YYYY/,this.getFullYear()); str=str.replace(/yy|YY/,(this.getYear() % 100)>9?(this.getYear() % 100).toString():"0" + (this.getYear() % 100)); str=str.replace(/MM/,this.getMonth()>9?this.getMonth().toString():"0" + this.getMonth()); str=str.replace(/M/g,this.getMonth()); str=str.replace(/dd|DD/,this.getDate()>9?this.getDate().toString():"0" + this.getDate()); str=str.replace(/d|D/g,this.getDate()); str=str.replace(/hh|HH/,this.getHours()>9?this.getHours().toString():"0" + this.getHours()); str=str.replace(/h|H/g,this.getHours()); str=str.replace(/mm/,this.getMinutes()>9?this.getMinutes().toString():"0" + this.getMinutes()); str=str.replace(/m/g,this.getMinutes()); str=str.replace(/ss|SS/,this.getSeconds()>9?this.getSeconds().toString():"0" + this.getSeconds()); str=str.replace(/s|S/g,this.getSeconds()); return str; } /* =========================================== //由字符串直接实例日期对象 =========================================== */ Date.prototype.instanceFromString = function(str) { return new Date("2004-10-10".replace(/-/g, "\/")); } /* =========================================== //得到日期年月日等加数字后的日期 =========================================== */ Date.prototype.dateAdd = function(interval,number) { var date = this; switch(interval) { case "y" : date.setFullYear(date.getFullYear()+number); return date; case "q" : date.setMonth(date.getMonth()+number*3); return date; case "m" : date.setMonth(date.getMonth()+number); return date; case "w" : date.setDate(date.getDate()+number*7); return date; case "d" : date.setDate(date.getDate()+number); return date; case "h" : date.setHours(date.getHours()+number); return date; case "m" : date.setMinutes(date.getMinutes()+number); return date; case "s" : date.setSeconds(date.getSeconds()+number); return date; default : date.setDate(d.getDate()+number); return date; } } /* =========================================== //计算两日期相差的日期年月日等 =========================================== */ Date.prototype.dateDiff = function(interval,objDate) { //暂缺 } /* ****************************************** 数字函数扩充 ****************************************** */ /* =========================================== //转换成中文大写数字 =========================================== */ Number.prototype.toChinese = function() { var num = this; if(!/^\d*(\.\d*)?$/.test(num)){alert("Number is wrong!"); return "Number is wrong!";} var AA = new Array("零","壹","贰","叁","肆","伍","陆","柒","捌","玖"); var BB = new Array("","拾","佰","仟","萬","億","点",""); var a = (""+ num).replace(/(^0*)/g, "").split("."), k = 0, re = ""; for(var i=a[0].length-1; i>=0; i--) { switch(k) { case 0 : re = BB[7] + re; break; case 4 : if(!new RegExp("0{4}\\d{"+ (a[0].length-i-1) +"}$").test(a[0])) re = BB[4] + re; break; case 8 : re = BB[5] + re; BB[7] = BB[5]; k = 0; break; } if(k%4 == 2 && a[0].charAt(i+2) != 0 && a[0].charAt(i+1) == 0) re = AA[0] + re; if(a[0].charAt(i) != 0) re = AA[a[0].charAt(i)] + BB[k%4] + re; k++; } if(a.length>1) //加上小数部分(如果有小数部分) { re += BB[6]; for(var i=0; i<a[1].length; i++) re += AA[a[1].charAt(i)]; } return re; } /* =========================================== //保留小数点位数 =========================================== */ Number.prototype.toFixed=function(len) { if(isNaN(len)||len==null) { len = 0; } else { if(len<0) { len = 0; } } return Math.round(this * Math.pow(10,len)) / Math.pow(10,len); } /* =========================================== //转换成大写金额 =========================================== */ Number.prototype.toMoney = function() { // Constants: var MAXIMUM_NUMBER = 99999999999.99; // Predefine the radix characters and currency symbols for output: var CN_ZERO= "零"; var CN_ONE= "壹"; var CN_TWO= "贰"; var CN_THREE= "叁"; var CN_FOUR= "肆"; var CN_FIVE= "伍"; var CN_SIX= "陆"; var CN_SEVEN= "柒"; var CN_EIGHT= "捌"; var CN_NINE= "玖"; var CN_TEN= "拾"; var CN_HUNDRED= "佰"; var CN_THOUSAND = "仟"; var CN_TEN_THOUSAND= "万"; var CN_HUNDRED_MILLION= "亿"; var CN_SYMBOL= ""; var CN_DOLLAR= "元"; var CN_TEN_CENT = "角"; var CN_CENT= "分"; var CN_INTEGER= "整"; // Variables: var integral; // Represent integral part of digit number. var decimal; // Represent decimal part of digit number. var outputCharacters; // The output result. var parts; var digits, radices, bigRadices, decimals; var zeroCount; var i, p, d; var quotient, modulus; if (this > MAXIMUM_NUMBER) { return ""; } // Process the coversion from currency digits to characters: // Separate integral and decimal parts before processing coversion: parts = (this + "").split("."); if (parts.length > 1) { integral = parts[0]; decimal = parts[1]; // Cut down redundant decimal digits that are after the second. decimal = decimal.substr(0, 2); } else { integral = parts[0]; decimal = ""; } // Prepare the characters corresponding to the digits: digits= new Array(CN_ZERO, CN_ONE, CN_TWO, CN_THREE, CN_FOUR, CN_FIVE, CN_SIX, CN_SEVEN, CN_EIGHT, CN_NINE); radices= new Array("", CN_TEN, CN_HUNDRED, CN_THOUSAND); bigRadices= new Array("", CN_TEN_THOUSAND, CN_HUNDRED_MILLION); decimals= new Array(CN_TEN_CENT, CN_CENT); // Start processing: outputCharacters = ""; // Process integral part if it is larger than 0: if (Number(integral) > 0) { zeroCount = 0; for (i = 0; i < integral.length; i++) { p = integral.length - i - 1; d = integral.substr(i, 1); quotient = p / 4; modulus = p % 4; if (d == "0") { zeroCount++; } else { if (zeroCount > 0) { outputCharacters += digits[0]; } zeroCount = 0; outputCharacters += digits[Number(d)] + radices[modulus]; } if (modulus == 0 && zeroCount < 4) { outputCharacters += bigRadices[quotient]; } } outputCharacters += CN_DOLLAR; } // Process decimal part if there is: if (decimal != "") { for (i = 0; i < decimal.length; i++) { d = decimal.substr(i, 1); if (d != "0") { outputCharacters += digits[Number(d)] + decimals[i]; } } } // Confirm and return the final output string: if (outputCharacters == "") { outputCharacters = CN_ZERO + CN_DOLLAR; } if (decimal == "") { outputCharacters += CN_INTEGER; } outputCharacters = CN_SYMBOL + outputCharacters; return outputCharacters; } Number.prototype.toImage = function() { var num = Array( "#define t_width 3\n#define t_height 5\nstatic char t_bits[] = {0xF,0x5,0x5,0x5,0xF}", "#define t_width 3\n#define t_height 5\nstatic char t_bits[] = {0x4,0x4,0x4,0x4,0x4}", "#define t_width 3\n#define t_height 5\nstatic char t_bits[] = {0xF,0x4,0xF,0x1,0xF}", "#define t_width 3\n#define t_height 5\nstatic char t_bits[] = {0xF,0x4,0xF,0x4,0xF}", "#define t_width 3\n#define t_height 5\nstatic char t_bits[] = {0x5,0x5,0xF,0x4,0x4}", "#define t_width 3\n#define t_height 5\nstatic char t_bits[] = {0xF,0x1,0xF,0x4,0xF}", "#define t_width 3\n#define t_height 5\nstatic char t_bits[] = {0xF,0x1,0xF,0x5,0xF}", "#define t_width 3\n#define t_height 5\nstatic char t_bits[] = {0xF,0x4,0x4,0x4,0x4}", "#define t_width 3\n#define t_height 5\nstatic char t_bits[] = {0xF,0x5,0xF,0x5,0xF}", "#define t_width 3\n#define t_height 5\nstatic char t_bits[] = {0xF,0x5,0xF,0x4,0xF}" ); var str = this + ""; var iIndex var result="" for(iIndex=0;iIndex<str.length;iIndex++) { result +="<img src='javascript:" & num(iIndex) & "'"> } return result; } /* ****************************************** 其他函数扩充 ****************************************** */ /* =========================================== //验证类函数 =========================================== */ function IsEmpty(obj) { obj=document.getElementsByName(obj).item(0); if(Trim(obj.value)=="") { if(obj.disabled==false && obj.readOnly==false) { obj.focus(); } return true; } else { return false; } } /* =========================================== //无模式提示对话框 =========================================== */ function modelessAlert(Msg) { window.showModelessDialog("javascript:alert(\""+escape(Msg)+"\");window.close();","","status:no;resizable:no;help:no;dialogHeight:height:30px;dialogHeight:40px;"); } /* =========================================== //页面里回车到下一控件的焦点 =========================================== */ function Enter2Tab() { var e = document.activeElement; if(e.tagName == "INPUT" && ( e.type == "text" || e.type == "password" || e.type == "checkbox" || e.type == "radio" ) || e.tagName == "SELECT") { if(window.event.keyCode == 13) { window.event.keyCode = 9; } } } ////////打开此功能请取消下行注释 //document.onkeydown = Enter2Tab; function ViewSource(url) { window.location = 'view-source:'+ url; } ///////禁止右键 document.oncontextmenu = function() { return false;} /* ****************************************** 字符串函数扩充 ****************************************** */ /* =========================================== //去除左边的空格 =========================================== */ String.prototype.LTrim = function() { return this.replace(/(^\s*)/g, ""); } String.prototype.Mid = function(start,len) { if(isNaN(start)&&start<0) { return ""; } if(isNaN(len)&&len<0) { return ""; } return this.substring(start,len); } /* =========================================== //去除右边的空格 =========================================== */ String.prototype.Rtrim = function() { return this.replace(/(\s*$)/g, ""); } /* =========================================== //去除前后空格 =========================================== */ String.prototype.Trim = function() { return this.replace(/(^\s*)|(\s*$)/g, ""); } /* =========================================== //得到左边的字符串 =========================================== */ String.prototype.Left = function(len) { if(isNaN(len)||len==null) { len = this.length; } else { if(parseInt(len)<0||parseInt(len)>this.length) { len = this.length; } } return this.substring(0,len); } /* =========================================== //得到右边的字符串 =========================================== */ String.prototype.Right = function(len) { if(isNaN(len)||len==null) { len = this.length; } else { if(parseInt(len)<0||parseInt(len)>this.length) { len = this.length; } } return this.substring(this.length-len,this.length); } /* =========================================== //得到中间的字符串,注意从0开始 =========================================== */ String.prototype.Mid = function(start,len) { if(isNaN(start)||start==null) { start = 0; } else { if(parseInt(start)<0) { start = 0; } } if(isNaN(len)||len==null) { len = this.length; } else { if(parseInt(len)<0) { len = this.length; } } return this.substring(start,start+len); } /* =========================================== //在字符串里查找另一字符串:位置从0开始 =========================================== */ String.prototype.InStr = function(str) { if(str==null) { str = ""; } return this.indexOf(str); } /* =========================================== //在字符串里反向查找另一字符串:位置0开始 =========================================== */ String.prototype.InStrRev = function(str) { if(str==null) { str = ""; } return this.lastIndexOf(str); } /* =========================================== //计算字符串打印长度 =========================================== */ String.prototype.LengthW = function() { return this.replace(/[^\x00-\xff]/g,"**").length; } /* =========================================== //是否是正确的IP地址 =========================================== */ String.prototype.isIP = function() { var reSpaceCheck = /^(\d+)\.(\d+)\.(\d+)\.(\d+)$/; if (reSpaceCheck.test(this)) { this.match(reSpaceCheck); if (RegExp.$1 <= 255 && RegExp.$1 >= 0 && RegExp.$2 <= 255 && RegExp.$2 >= 0 && RegExp.$3 <= 255 && RegExp.$3 >= 0 && RegExp.$4 <= 255 && RegExp.$4 >= 0) { return true; } else { return false; } } else { return false; } } /* =========================================== //是否是正确的长日期 =========================================== */ String.prototype.isDate = function() { var r = str.match(/^(\d{1,4})(-|\/)(\d{1,2})\2(\d{1,2}) (\d{1,2}):(\d{1,2}):(\d{1,2})$/); if(r==null) { return false; } var d = new Date(r[1], r[3]-1,r[4],r[5],r[6],r[7]); return (d.getFullYear()==r[1]&&(d.getMonth()+1)==r[3]&&d.getDate()==r[4]&&d.getHours()==r[5]&&d.getMinutes()==r[6]&&d.getSeconds()==r[7]); } /* =========================================== //是否是手机 =========================================== */ String.prototype.isMobile = function() { return /^0{0,1}13[0-9]{9}$/.test(this); } /* =========================================== //是否是邮件 =========================================== */ String.prototype.isEmail = function() { return /^\w+((-\w+)|(\.\w+))*\@[A-Za-z0-9]+((\.|-)[A-Za-z0-9]+)*\.[A-Za-z0-9]+$/.test(this); } /* =========================================== //是否是邮编(中国) =========================================== */ String.prototype.isZipCode = function() { return /^[\\d]{6}$/.test(this); } /* =========================================== //是否是有汉字 =========================================== */ String.prototype.existChinese = function() { //[\u4E00-\u9FA5]為漢字﹐[\uFE30-\uFFA0]為全角符號 return /^[\x00-\xff]*$/.test(this); } /* =========================================== //是否是合法的文件名/目录名 =========================================== */ String.prototype.isFileName = function() { return !/[\\\/\*\?\|:"<>]/g.test(this); } /* =========================================== //是否是有效链接 =========================================== */ String.Prototype.isUrl = function() { return /^http:\/\/([\w-]+\.)+[\w-]+(/[\w-./?%&=]*)?$/.test(this); } /* =========================================== //是否是有效的身份证(中国) =========================================== */ String.prototype.isIDCard = function() { var iSum=0; var info=""; var sId = this; var aCity={11:"北京",12:"天津",13:"河北",14:"山西",15:"内蒙古",21:"辽宁",22:"吉林",23:"黑龙江",31:"上海",32:"江苏",33:"浙江",34:"安徽",35:"福建",36:"江西",37:"山东",41:"河南",42:"湖北",43:"湖南",44:"广东",45:"广西",46:"海南",50:"重庆",51:"四川",52:"贵州",53:"云南",54:"西藏",61:"陕西",62:"甘肃",63:"青海",64:"宁夏",65:"新疆",71:"台湾",81:"香港",82:"澳门",91:"国外"}; if(!/^\d{17}(\d|x)$/i.test(sId)) { return false; } sId=sId.replace(/x$/i,"a"); //非法地区 if(aCity[parseInt(sId.substr(0,2))]==null) { return false; } var sBirthday=sId.substr(6,4)+"-"+Number(sId.substr(10,2))+"-"+Number(sId.substr(12,2)); var d=new Date(sBirthday.replace(/-/g,"/")) //非法生日 if(sBirthday!=(d.getFullYear()+"-"+ (d.getMonth()+1) + "-" + d.getDate())) { return false; } for(var i = 17;i>=0;i--) { iSum += (Math.pow(2,i) % 11) * parseInt(sId.charAt(17 - i),11); } if(iSum%11!=1) { return false; } return true; } /* =========================================== //是否是有效的电话号码(中国) =========================================== */ String.prototype.isPhoneCall = function() { return /(^[0-9]{3,4}\-[0-9]{3,8}$)|(^[0-9]{3,8}$)|(^\([0-9]{3,4}\)[0-9]{3,8}$)|(^0{0,1}13[0-9]{9}$)/.test(this); } /* =========================================== //是否是数字 =========================================== */ String.prototype.isNumeric = function(flag) { //验证是否是数字 if(isNaN(this)) { return false; } switch(flag) { case null://数字 case "": return true; case "+"://正数 return/(^\+?|^\d?)\d*\.?\d+$/.test(this); case "-"://负数 return/^-\d*\.?\d+$/.test(this); case "i"://整数 return/(^-?|^\+?|\d)\d+$/.test(this); case "+i"://正整数 return/(^\d+$)|(^\+?\d+$)/.test(this); case "-i"://负整数 return/^[-]\d+$/.test(this); case "f"://浮点数 return/(^-?|^\+?|^\d?)\d*\.\d+$/.test(this); case "+f"://正浮点数 return/(^\+?|^\d?)\d*\.\d+$/.test(this); case "-f"://负浮点数 return/^[-]\d*\.\d$/.test(this); default://缺省 return true; } } /* =========================================== //转换成全角 =========================================== */ String.prototype.toCase = function() { var tmp = ""; for(var i=0;i<this.length;i++) { if(this.charCodeAt(i)>0&&this.charCodeAt(i)<255) { tmp += String.fromCharCode(this.charCodeAt(i)+65248); } else { tmp += String.fromCharCode(this.charCodeAt(i)); } } return tmp } /* =========================================== //对字符串进行Html编码 =========================================== */ String.prototype.toHtmlEncode = function { var str = this; str=str.replace("&","&"); str=str.replace("<","<"); str=str.replace(">",">"); str=str.replace("'","'"); str=str.replace("\"","""); return str; } qqdao(青青岛) 精心整理的输入判断js函数 关键词:字符串判断,字符串处理,字串判断,字串处理 //'********************************************************* // ' Purpose: 判断输入是否为整数字 // ' Inputs: String // ' Returns: True, False //'********************************************************* function onlynumber(str) { var i,strlength,tempchar; str=CStr(str); if(str=="") return false; strlength=str.length; for(i=0;i<strlength;i++) { tempchar=str.substring(i,i+1); if(!(tempchar==0||tempchar==1||tempchar==2||tempchar==3||tempchar==4||tempchar==5||tempchar==6||tempchar==7||tempchar==8||tempchar==9)) { alert("只能输入数字 "); return false; } } return true; } //'********************************************************* //'********************************************************* // ' Purpose: 判断输入是否为数值(包括小数点) // ' Inputs: String // ' Returns: True, False //'********************************************************* function IsFloat(str) { var tmp; var temp; var i; tmp =str; if(str=="") return false; for(i=0;i<tmp.length;i++) {temp=tmp.substring(i,i+1); if((temp>='0'&& temp<='9')||(temp=='.')){} //check input in 0-9 and '.' else { return false;} } return true; } //'********************************************************* // ' Purpose: 判断输入是否为电话号码 // ' Inputs: String // ' Returns: True, False //'********************************************************* function isphonenumber(str) { var i,strlengh,tempchar; str=CStr(str); if(str=="") return false; strlength=str.length; for(i=0;i<strlength;i++) { tempchar=str.substring(i,i+1); if(!(tempchar==0||tempchar==1||tempchar==2||tempchar==3||tempchar==4||tempchar==5||tempchar==6||tempchar==7||tempchar==8||tempchar==9||tempchar=='-')) { alert("电话号码只能输入数字和中划线 "); return(false); } } return(true); } //'********************************************************* //'********************************************************* // ' Purpose: 判断输入是否为Email // ' Inputs: String // ' Returns: True, False //'********************************************************* function isemail(str) { var bflag=true if (str.indexOf("'")!=-1) { bflag=false } if (str.indexOf("@")==-1) { bflag=false } else if(str.charAt(0)=="@"){ bflag=false } return bflag } //'********************************************************* // ' Purpose: 判断输入是否含有为中文 // ' Inputs: String // ' Returns: True, False //'********************************************************* function IsChinese(str) { if(escape(str).indexOf("%u")!=-1) { return true; } return false; } //'********************************************************* //'********************************************************* // ' Purpose: 判断输入是否含有空格 // ' Inputs: String // ' Returns: True, False //'********************************************************* function checkblank(str) { var strlength; var k; var ch; strlength=str.length; for(k=0;k<=strlength;k++) { ch=str.substring(k,k+1); if(ch==" ") { alert("对不起 不能输入空格 "); return false; } } return true; } //'********************************************************* //'********************************************************* // ' Purpose: 去掉Str两边空格 // ' Inputs: Str // ' Returns: 去掉两边空格的Str //'********************************************************* function trim(str) { var i,strlength,t,chartemp,returnstr; str=CStr(str); strlength=str.length; t=str; for(i=0;i<strlength;i++) { chartemp=str.substring(i,i+1); if(chartemp==" ") { t=str.substring(i+1,strlength); } else { break; } } returnstr=t; strlength=t.length; for(i=strlength;i>=0;i--) { chartemp=t.substring(i,i-1); if(chartemp==" ") { returnstr=t.substring(i-1,0); } else { break; } } return (returnstr); } //'********************************************************* //'********************************************************* // ' Purpose: 将数值类型转化为String // ' Inputs: int // ' Returns: String //'********************************************************* function CStr(inp) { return(""+inp+""); } //'********************************************************* //'********************************************************* // ' Purpose: 去除不合法字符, ' " < > // ' Inputs: String // ' Returns: String //'********************************************************* function Rep(str) {var str1; str1=str; str1=replace(str1,"'","`",1,0); str1=replace(str1,'"',"`",1,0); str1=replace(str1,"<","(",1,0); str1=replace(str1,">",")",1,0); return str1; } //'********************************************************* //'********************************************************* // ' Purpose: 替代字符 // ' Inputs: 目标String,欲替代的字符,替代成为字符串,大小写是否敏感,是否整字代替 // ' Returns: String //'********************************************************* function replace(target,oldTerm,newTerm,caseSens,wordOnly) { var wk ; var ind = 0; var next = 0; wk=CStr(target); if (!caseSens) { oldTerm = oldTerm.toLowerCase(); wk = target.toLowerCase(); } while ((ind = wk.indexOf(oldTerm,next)) >= 0) { if (wordOnly) { var before = ind - 1; var after = ind + oldTerm.length; if (!(space(wk.charAt(before)) && space(wk.charAt(after)))) { next = ind + oldTerm.length; continue; } } target = target.substring(0,ind) + newTerm + target.substring(ind+oldTerm.length,target.length); wk = wk.substring(0,ind) + newTerm + wk.substring(ind+oldTerm.length,wk.length); next = ind + newTerm.length; if (next >= wk.length) { break; } } return target; } //'********************************************************* 几个判断,并强制设置焦点: //+------------------------------------ // trim 去除字符串两端的空格 String.prototype.trim=function(){return this.replace(/(^\s*)|(\s*$)/g,"")} //------------------------------------- // avoidDeadLock 避免设置焦点死循环问题 // 起死原因:以文本框为例,当一个文本框的输入不符合条件时,这时,鼠标点击另一个文本框,触发第一个文本框的离开事件 // ,产生设置焦点动作。现在产生了第二个文本框的离开事件,因此也要设置第二个文本框的焦点,造成死锁。 // 解决方案:设置一个全局对象[key],记录当前触发事件的对象,若其符合条件,则释放该key;若其仍不符合,则key还是指 // 向该对象,别的对象触发不到设置焦点的语句。 ///////////////////////////////////////// // 文本框控制函数 // ///////////////////////////////////////// var g_Obj = null;// 记住旧的控件 // hintFlag参数:0表示没有被别的函数调用,因此出现提示;1表示被调用,不出现警告信息 // focusFlag参数:指示是否要设置其焦点,分情况:0表示有的可为空;1表示有的不为空 // 避免死锁的公共部分 //+------------------------------------ function textCom(obj, hintFlag) { if (g_Obj == null) g_Obj=event.srcElement; else if ((g_Obj != null) && (hintFlag == 0) && (g_Obj != obj)) { g_Obj = null; return; } g_Obj.value = g_Obj.value.trim(); } //------------------------------------- // 文本框不为空 //+------------------------------------ function TBNotNull(obj, hintFlag) { if (g_Obj == null) g_Obj=event.srcElement; else if ((g_Obj != null) && (hintFlag == 0) && (g_Obj != obj)) { g_Obj = null; return; } g_Obj.value = g_Obj.value.trim(); if (g_Obj.value == "") { if (hintFlag == 0) { g_Obj.focus(); alert("内容不能为空!"); } return false; } else g_Obj = null; return true; } //------------------------------------- // 输入内容为数字 //+------------------------------------ function LetNumber(obj, hintFlag, focusFlag) { if (g_Obj == null) g_Obj=event.srcElement; else if ((g_Obj != null) && (hintFlag == 0) && (g_Obj != obj)) { g_Obj = null; return; } g_Obj.value = g_Obj.value.trim(); if ((g_Obj.value == "") || isNaN(g_Obj.value)) { if (hintFlag == 0) { g_Obj.value = ""; if (focusFlag == 1) g_Obj.focus(); else g_Obj = null; alert("输入的内容必须为数字!"); } return false; } else g_Obj = null; return true; } //------------------------------------- // 输入内容为整数 //+------------------------------------ function LetInteger(obj, hintFlag, focusFlag) { if (g_Obj == null) g_Obj=event.srcElement; else if ((g_Obj != null) && (hintFlag == 0) && (g_Obj != obj)) { g_Obj = null; return; } g_Obj.value = g_Obj.value.trim(); if (!/^\d*$/.test(g_Obj.value) || (g_Obj.value == "")) { if (hintFlag == 0) { g_Obj.value = ""; if (focusFlag == 1) g_Obj.focus(); else g_Obj = null; alert("输入的内容必须为整数!"); } return false; } else g_Obj = null; return true; } //------------------------------------- // 输入内容为字母 //+------------------------------------ function LetLetter(obj, hintFlag, focusFlag) { if (g_Obj == null) g_Obj=event.srcElement; else if ((g_Obj != null) && (hintFlag == 0) && (g_Obj != obj)) { g_Obj = null; return; } if (!/^[A-Za-z]*$/.test(g_Obj.value)) { if (hintFlag == 0) { alert("输入的内容必须为字母!"); g_Obj.value = ""; if (focusFlag == 1) g_Obj.focus(); else g_Obj = null; } return false; } else { g_Obj = null; } return true; } //------------------------------------- // 内容大于某值 //+------------------------------------ function LetMoreThan(obj, leftNumber, hintFlag, focusFlag) { var ifAlert;// 是否出现警告 if (g_Obj == null) g_Obj=event.srcElement; else if ((g_Obj != null) && (hintFlag == 0) && (g_Obj != obj)) { g_Obj = null; return; } g_Obj.value = g_Obj.value.trim(); if (g_Obj.value == "") ifAlert = 0; else ifAlert = 1; if ((g_Obj.value == "") || (isNaN(g_Obj.value)) || (g_Obj.value < leftNumber)) { if (hintFlag == 0) { g_Obj.value = ""; if (focusFlag == 1) g_Obj.focus(); else g_Obj = null; // 更友好的提示 if (ifAlert == 1) { if (leftNumber == 0) alert("内容必须为非负数!"); else alert("输入的内容必须" + leftNumber + "以上!"); } } return false; } else g_Obj = null; return true; } //------------------------------------- // 内容大于某值,整数 //+------------------------------------ function LetMoreThan_Int(obj, leftNumber, hintFlag, focusFlag) { var ifAlert;// 是否出现警告 if (g_Obj == null) g_Obj=event.srcElement; else if ((g_Obj != null) && (hintFlag == 0) && (g_Obj != obj)) { g_Obj = null; return; } g_Obj.value = g_Obj.value.trim(); if (g_Obj.value == "") ifAlert = 0; else ifAlert = 1; if ((g_Obj.value == "") || (isNaN(g_Obj.value) || g_Obj.value < leftNumber) || !/^\d*$/.test(g_Obj.value)) { if (hintFlag == 0) { g_Obj.value = ""; if (focusFlag == 1) g_Obj.focus(); else {g_Obj = null;} if (ifAlert == 1)// 当用户不输入的时候,不出现提示 { // 更友好的提示 if (leftNumber == 0) alert("内容必须为非负整数!"); else alert("且必须在" + leftNumber + "以上!"); } } return false; } else g_Obj = null; return true; } //------------------------------------- // 内容小于某值 //+------------------------------------ function LetLessThan(obj, rightNumber, hintFlag, focusFlag) { if (g_Obj == null) g_Obj=event.srcElement; else if ((g_Obj != null) && (hintFlag == 0) && (g_Obj != obj)) { g_Obj = null; return; } g_Obj.value = g_Obj.value.trim(); if ((g_Obj.value == "") || (isNaN(g_Obj.value) || g_Obj.value > rightNumber)) { if (hintFlag == 0) { g_Obj.value = ""; if (focusFlag == 1) g_Obj.focus(); else g_Obj = null; alert("输入的内容必须在" + rightNumber + "以下!"); } return false; } else {g_Obj = null;} return true; } //------------------------------------- // 内容介于两值中间 //+------------------------------------ function LetMid(obj, leftNumber, rightNumber, hintFlag, focusFlag) { var ifAlert;// 是否出现警告 if (g_Obj == null) g_Obj=event.srcElement; else if ((g_Obj != null) && (hintFlag == 0) && (g_Obj != obj)) { g_Obj = null; return; } g_Obj.value = g_Obj.value.trim(); if (g_Obj.value == "") ifAlert = 0; else ifAlert = 1; // 首先应该为数字 if (LetNumber(g_Obj, 1)) { if (!(LetMoreThan(obj,leftNumber,1,0) && LetLessThan(obj,rightNumber,1,0))) { if (hintFlag == 0) { g_Obj.value = ""; if (focusFlag == 1) g_Obj.focus(); else g_Obj = null; if (ifAlert == 1)// 当用户不输入的时候,不出现提示 alert("输入的内容必须介于" + leftNumber + "和" + rightNumber + "之间!"); } return false; } else {g_Obj = null;} } else { if (hintFlag == 0) { g_Obj.value = ""; if (focusFlag == 1) g_Obj.focus(); else g_Obj = null; if (ifAlert == 1) alert("输入的内容必须为数字!\n" + "且介于" + leftNumber + "和" + rightNumber + "之间!"); } return false; } return true; } //------------------------------------- ///////////////////////////////////////// // 下拉框 ///////////////////////////////////////// // 下拉框,务必选择 //+------------------------------------ function onSelLostFocus(obj) { if (g_Obj == null) { g_Obj=event.srcElement; } else if ((g_Obj!=null) && (g_Obj!=obj)) { g_Obj = null; return; } if (g_Obj.selectedIndex == 0) { g_Obj.focus(); } else { g_Obj = null; } } |
|||
socket客户端连接服务器端 | j2se | ||
/*客户端通过键盘录入用户名。 服务端对这个用户名进行校验。 如果该用户存在,在服务端显示xxx,已登陆。 并在客户端显示 xxx,欢迎光临。 如果该用户存在,在服务端显示xxx,尝试登陆。 并在客户端显示 xxx,该用户不存在。 最多就登录三次。 */ import java.io.*; import java.net.*; class LogClient { public static void main(String[] args) throws Exception { Socket s = new Socket("192.168.0.2",11011); BufferedReader bufr = new BufferedReader(new InputStreamReader(System.in)); PrintWriter out = new PrintWriter(s.getOutputStream(),true); BufferedReader bufin = new BufferedReader(new InputStreamReader(s.getInputStream())); for(int i = 0;i<3;i++) { String line = bufr.readLine(); if(line == null) break; out.println(line); String info = bufin.readLine(); System.out.println("info:"+info); if(info.contains("欢迎")) break; } bufr.close(); s.close(); } } class UserThread implements Runnable { private Socket s ; public UserThread(Socket s) { this.s = s; } public void run() { String ip = s.getInetAddress().getHostAddress(); System.out.println(ip+"...connected."); try { // BufferedReader bufr = null; for(int i = 0 ;i<3;i++) { BufferedReader in = new BufferedReader(new InputStreamReader(s.getInputStream())); String username = in.readLine(); if(username==null) break; PrintWriter out = new PrintWriter(s.getOutputStream(),true); BufferedReader bufr = new BufferedReader(new FileReader("user.txt")); boolean flag = false; String line = null; while((line= bufr.readLine())!=null) { if(line.equals(username)) { flag = true; break; } } if(flag) { System.out.println(username + "已登录。"); out.println(username + "欢迎光临!"); bufr.close(); break; } else { System.out.println(username + ",尝试登陆。"); out.println(username + ",该用户不存在。"); bufr.close(); } } s.close(); } catch (Exception e) { throw new RuntimeException(ip+"校验失败!"); } } } class LogServer { public static void main(String[] args)throws Exception { ServerSocket ss = new ServerSocket(11011); while(true) { Socket s = ss.accept(); new Thread(new UserThread(s)).start(); } } } |
|||
运用io流拷贝文件 | j2se | 运用io流拷贝文件 | |
package lixg.J2se.IO; import java.io.*; //运用io流拷贝文件 class CopyPic { public static void main(String[] args) throws IOException { long star = System.currentTimeMillis(); InputStream in = new FileInputStream("D:\\java\\workspace2eclipse\\OA_29_Lixg\\src\\lixg\\J2se\\IO\\record.gif"); OutputStream out = new FileOutputStream("D:\\java\\workspace2eclipse\\OA_29_Lixg\\src\\lixg\\J2se\\IO\\record2.gif"); byte[] b = new byte[1024]; int len = 0; while ((len = in.read(b)) != -1)// 等价于:read(b,0,b.length) { out.write(b, 0, len); } in.close(); out.close(); long end = System.currentTimeMillis(); System.out.println("时间:" + (end - star)); } } |
|||
使用java io流中的缓冲区技术拷贝一个文本文件 | j2se | 使用java io流中的缓冲区技术拷贝一个文本文件 | |
package lixg.J2se.IO; import java.io.*; class BufferedTest { public static void main(String[] args) { test3(); } public static void test3() { BufferedReader bfr = null; BufferedWriter bfw = null; try { bfr = new BufferedReader(new FileReader("D:\\java\\workspace2eclipse\\OA_29_Lixg\\src\\lixg\\J2se\\IO\\CopyMp3.java")); bfw = new BufferedWriter(new FileWriter("D:\\java\\workspace2eclipse\\OA_29_Lixg\\src\\lixg\\J2se\\IO\\CopyMp4.java")); String line = null; while ((line = bfr.readLine()) != null) { bfw.write(line); bfw.newLine(); bfw.flush(); } } catch (IOException e) { e.printStackTrace(); throw new RuntimeException("文件复制失败"); } finally { try { if (bfw != null) bfw.close(); } catch (IOException e) { throw new RuntimeException("写入资源关闭失败"); } try { if (bfr != null) bfr.close(); } catch (IOException e) { throw new RuntimeException("读取资源关闭失败"); } } } public static void test2() { BufferedReader bfr = null; try { bfr = new BufferedReader(new FileReader("Test.txt")); String line; while ((line = bfr.readLine()) != null) { System.out.println(line); } } catch (IOException e) { throw new RuntimeException("文件读入失败"); } finally { try { if (bfr != null) bfr.close(); } catch (IOException e) { throw new RuntimeException("资源关闭失败"); } } } public static void test1() { BufferedWriter bfw = null; try { bfw = new BufferedWriter(new FileWriter("Test.txt")); for (int i = 0; i < 5; i++) { bfw.write("abcde" + i); bfw.newLine(); bfw.flush(); } } catch (IOException e) { throw new RuntimeException("文件写入失败"); } finally { try { if (bfw != null) bfw.close(); } catch (IOException e) { throw new RuntimeException("资源关闭失败"); } } } } |
|||
26 | 26 | ||
/* * BasicDataDefineView.java * * Created on 2008年9月18日, 下午1:38 */ package com.itown.rcp.basicdata.view; import com.itown.rcp.basicdata.BasicDataDefine; import com.itown.rcp.basicdata.BasicDataException; import com.itown.rcp.basicdata.TreeBasicDataDefine; import com.itown.rcp.basicdata.bl.SysCompoundBasicDataBL; import com.itown.rcp.basicdata.bl.TableBasicDataBL; import com.itown.rcp.basicdata.bl.TreeBasicDataBL; import com.itown.rcp.basicdata.define.CompoundBasicDataDefine; import com.itown.rcp.basicdata.entity.SysCompound; import com.itown.rcp.basicdata.impl.BasicDataUtils; import com.itown.rcp.basicdata.service.BasicDataDefineService; import com.itown.rcp.basicdata.utils.CancelableTreeSelectionListener; import com.itown.rcp.basicdata.utils.Execution; import com.itown.rcp.basicdata.utils.SearchOperation; import com.itown.rcp.basicdata.utils.TreeUserObject; import com.itown.rcp.client.MessageBox; import com.itown.rcp.client.test.AuthenticatedTestBase; import com.itown.rcp.proxy.ServiceFactory; import com.itown.rcp.swing.binding.BindingUtils; import com.itown.rcp.swing.fsp.filter.FilterType; import com.itown.rcp.swing.fsp.filter.OrFilterItem; import com.itown.rcp.swing.fsp.filter.SimpleFilterItem; import com.itown.rcp.swing.table.TableUtils; import com.itown.rcp.swing.table.filter.FilterGroup; import com.itown.rcp.sysmgr.utils.JTreeHelper; import com.itown.rcp.sysmgr.utils.TableDataHelper; import com.itown.rcp.view.AbstractView; import java.lang.reflect.InvocationTargetException; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Map.Entry; import java.util.Vector; import java.util.logging.Level; import java.util.logging.Logger; import javax.swing.JComboBox; import javax.swing.JComponent; import javax.swing.JOptionPane; import javax.swing.JTree; import javax.swing.SwingUtilities; import javax.swing.event.DocumentEvent; import javax.swing.event.DocumentListener; import javax.swing.event.TreeSelectionEvent; import javax.swing.event.TreeSelectionListener; import javax.swing.text.JTextComponent; import javax.swing.tree.DefaultMutableTreeNode; import javax.swing.tree.DefaultTreeModel; import javax.swing.tree.TreePath; import org.apache.commons.beanutils.PropertyUtils; import org.apache.commons.collections.map.LinkedMap; import org.apache.commons.lang.StringUtils; import org.itown.rcp.Menu; import org.itown.rcp.action.Action; import org.itown.rcp.util.ListItem; import org.itown.rcp.util.MapComboBoxModel; import org.itown.rcp.view.ModalResult; import org.itown.rcp.datastore.helper.ModifiedTableData; import org.itown.rcp.datastore.helper.ModifiedTableDataUtils; import org.itown.rcp.datastore.helper.UUIDKeyGenerator; import org.jdesktop.beansbinding.Binding; import org.jdesktop.beansbinding.BindingGroup; /** * * @author ywl */ @Menu(code = "010114") public class BasicDataDefineView extends AbstractView { protected FilterGroup filterGroup; private TreeBasicDataBL treeBasicDataBL; private SysCompoundBasicDataBL compoundBasicDataBL; private TableBasicDataBL tablebl; private Map<String, JComponent> propertyBindingMappping; private Object curObject; private BindingGroup bindingGroup; private List<SysCompound> compoundItems; private BasicDataDefine basicDataDefine; private BasicDataDefineService service = ServiceFactory.getInstance().getService(BasicDataDefineService.class); public BasicDataDefineView() { initComponents(); setComponent(masterPanel); Map items = new LinkedMap(); items.put(SearchOperation.LIKE, "包含"); items.put(SearchOperation.LLIKE, "左匹配"); items.put(SearchOperation.RLIKE, "右匹配"); items.put(SearchOperation.EQUALS, "等于"); operationTree.setModel(new MapComboBoxModel(items, false)); this.compoundCategoryTree.addTreeSelectionListener(new CompoundCategoryTSL()); this.bindCompoundItems(); } @Override public void viewOpened() { DefaultMutableTreeNode root = new DefaultMutableTreeNode("基础数据"); //String[] basicDataIds = BasicDataUtils.getBasicDataDefineNames(); String[] nts = BasicDataUtils.getDefineNameAndTitles(); if (nts != null && nts.length > 0) { for (String nt : nts) { String[] n = nt.split("<>"); BasicDataDefine basicDataDefine = BasicDataUtils.getBasicDataDefine(n[0]); if (basicDataDefine != null) { DefaultMutableTreeNode basicDataNode = new DefaultMutableTreeNode(); basicDataNode.setUserObject(new TreeUserObject(n[0], n[1], basicDataDefine)); root.add(basicDataNode); } } } basicDataDefineTree.setModel(new DefaultTreeModel(root)); basicDataDefineTree.addTreeSelectionListener(new CancelableTreeSelectionListener(new Execution() { public boolean execute(TreeSelectionEvent e) { JTree tree = (JTree) e.getSource(); //判断原来的基础数据是否已保存 TreePath old = e.getOldLeadSelectionPath(); System.out.println("old : " + old); if (old != null) { DefaultMutableTreeNode oldNode = (DefaultMutableTreeNode) old.getLastPathComponent(); if (!(oldNode.getUserObject() instanceof TreeUserObject)) { return false; } TreeUserObject uo = (TreeUserObject) oldNode.getUserObject(); if (uo.getObject() != null) { BasicDataDefine basicDataDefine = (BasicDataDefine) uo.getObject(); boolean isDirty = isDirty(basicDataDefine); if (isDirty) { int result = MessageBox.confirm("基础数据:" + basicDataDefine.getName() + "有数据未保存,现在保存吗?"); if (JOptionPane.YES_OPTION == result) { try { save(); } catch (Exception ex) { MessageBox.prompt(ex.getMessage()); return true; } } else { return true; } } } } DefaultMutableTreeNode node = (DefaultMutableTreeNode) tree.getLastSelectedPathComponent(); if (node == null) { return false; } if (!(node.getUserObject() instanceof TreeUserObject)) { return false; } TreeUserObject uo = (TreeUserObject) node.getUserObject(); if (uo == null) { return false; } if (uo.getObject() == null) { return false; } BasicDataDefine bd = (BasicDataDefine) uo.getObject(); modifyBasicData(bd); return false; } })); buildTreeEidtAction(); buildCompoundEidtAction(); this.masterSplitPane.setRightComponent(this.emptyPanel); modifyCompoundCategoryButton.setIcon(new javax.swing.ImageIcon(getClass().getResource("/images/16_16/edit.gif"))); // NOI18N addCompoundCategoryButton.setIcon(new javax.swing.ImageIcon(getClass().getResource("/images/16_16/add.gif"))); // NOI18N delCompoundCategoryButton.setIcon(new javax.swing.ImageIcon(getClass().getResource("/images/16_16/delete.gif"))); // NOI18N modifyCompoundItemButton.setIcon(new javax.swing.ImageIcon(getClass().getResource("/images/16_16/edit.gif"))); // NOI18N delCompoundItemButton.setIcon(new javax.swing.ImageIcon(getClass().getResource("/images/16_16/delete.gif"))); // NOI18N addCompoundItemButton.setIcon(new javax.swing.ImageIcon(getClass().getResource("/images/16_16/add.gif"))); // NOI18N saveAllTreeButton.setIcon(new javax.swing.ImageIcon(getClass().getResource("/images/16_16/save.gif"))); // NOI18N deleteTreeButton.setIcon(new javax.swing.ImageIcon(getClass().getResource("/images/16_16/delete.gif"))); // NOI18N addChildTreeButton.setIcon(new javax.swing.ImageIcon(getClass().getResource("/images/16_16/add.gif"))); // NOI18N } @Override public boolean isDirty() { return isDirty(basicDataDefine); } private boolean isDirty(BasicDataDefine basicDataDefine) { boolean isDirty = false; if (basicDataDefine == null) { return false; } if (basicDataDefine instanceof CompoundBasicDataDefine) { //compoundBasicDataBL } else if (basicDataDefine instanceof TreeBasicDataDefine) { if (treeBasicDataBL != null) { isDirty = treeBasicDataBL.isDirty(); } } else { isDirty = TableUtils.isDirty(mainTable); } return isDirty; } private TreeBasicDataBL getTreeBasicDataBL(TreeBasicDataDefine basicDataDefine) { TreeBasicDataBL result = treeBasicDataBLMap.get(basicDataDefine); if (result == null) { result = new TreeBasicDataBL(this, basicDataDefine, basicDataTree, detailPanel); treeBasicDataBLMap.put(basicDataDefine, result); } return result; } private SysCompoundBasicDataBL getCompoundBasicDataBL(CompoundBasicDataDefine basicData) { if (this.compoundBasicDataBL == null) { compoundBasicDataBL = new SysCompoundBasicDataBL(this, basicData, compoundCategoryTree); } return this.compoundBasicDataBL; } private TableBasicDataBL getTableBasicDataBL(BasicDataDefine basicData) { TableBasicDataBL result = tableBasicDataBLMap.get(basicData); if (result == null) { result = new TableBasicDataBL(this, basicData); tableBasicDataBLMap.put(basicData, result); } return result; } private void bindData(Object object) { if (object == null) { return; } curObject = object; if (bindingGroup == null) { bindingGroup = new BindingGroup(); } bindingGroup.unbind(); //清除原有绑定 List<Binding> bindings = bindingGroup.getBindings(); if (bindings != null) { for (Binding binding : bindings) { bindingGroup.removeBinding(binding); } } //DefaultBeanBinding.getInstance().buildBinding(bindingGroup, curObject, propertyBindingMappping); BindingUtils.autoBindingByName(bindingGroup, object, this.detailPanel); bindingGroup.bind(); syncComboBoxItem(curObject); setControlStatus(); } private void setControlStatus() { JComponent codeComponent = this.propertyBindingMappping.get(treeBasicDataBL.getCodeProperty()); if (codeComponent != null) { if (treeBasicDataBL.isNewObject(curObject)) { codeComponent.setEnabled(true); if (codeComponent.isEnabled()) { codeComponent.requestFocus(); } } else { codeComponent.setEnabled(false); } } } class NameDocumentListener implements DocumentListener { JTextComponent name; JTree tree; public NameDocumentListener(JTextComponent name, JTree tree) { this.name = name; this.tree = tree; } @Override public void insertUpdate(DocumentEvent e) { updateTreeNode(); } @Override public void removeUpdate(DocumentEvent e) { updateTreeNode(); } @Override public void changedUpdate(DocumentEvent e) { updateTreeNode(); } void updateTreeNode() { String value = name.getText(); DefaultMutableTreeNode node = (DefaultMutableTreeNode) tree.getLastSelectedPathComponent(); if (node == null) { return; } TreeUserObject uo = (TreeUserObject) node.getUserObject(); uo.setValue(value); DefaultTreeModel dtm = (DefaultTreeModel) tree.getModel(); dtm.nodeChanged(node); } } class CodeDocumentListener implements DocumentListener { JTextComponent code; JTree tree; String codeProperty; String parentCodeProperty; public CodeDocumentListener(JTextComponent code, JTree tree, String codeProperty, String parentCodeProperty) { this.code = code; this.tree = tree; this.codeProperty = codeProperty; this.parentCodeProperty = parentCodeProperty; } @Override public void insertUpdate(DocumentEvent e) { syncChildParentCode(); } @Override public void removeUpdate(DocumentEvent e) { syncChildParentCode(); } @Override public void changedUpdate(DocumentEvent e) { syncChildParentCode(); } void syncChildParentCode() { String value = code.getText(); DefaultMutableTreeNode node = (DefaultMutableTreeNode) tree.getLastSelectedPathComponent(); if (node == null) { return; } TreeUserObject tuo = (TreeUserObject) node.getUserObject(); if (tuo != null && tuo.getObject() != null) { syncChildParentCode(node, value); } } private void syncChildParentCode(DefaultMutableTreeNode node, Object value) { if (node.getChildCount() > 0 && value != null) { for (int i = 0; i < node.getChildCount(); i++) { DefaultMutableTreeNode childNode = (DefaultMutableTreeNode) node.getChildAt(i); TreeUserObject tuo = (TreeUserObject) childNode.getUserObject(); if (tuo != null && tuo.getObject() != null) { try { PropertyUtils.setProperty(tuo.getObject(), parentCodeProperty, value); syncChildParentCode(childNode, PropertyUtils.getSimpleProperty(tuo.getObject(), codeProperty)); } catch (IllegalAccessException ex) { throw new BasicDataException(ex.getMessage(), ex); } catch (InvocationTargetException ex) { throw new BasicDataException(ex.getMessage(), ex); } catch (NoSuchMethodException ex) { throw new BasicDataException(ex.getMessage(), ex); } } } } } } private void syncComboBoxItem(Object entity) { if (this.propertyBindingMappping != null) { for (Entry<String, JComponent> entry : propertyBindingMappping.entrySet()) { String propertyName = entry.getKey(); JComponent comp = entry.getValue(); if (comp instanceof JComboBox) { this.setComboBoxItem((JComboBox) comp, treeBasicDataBL.getPropertyValue(entity, propertyName)); } } } } private void setComboBoxItem(JComboBox cb, Object value) { if (value == null || cb == null) { return; } int count = cb.getItemCount(); for (int i = 0; i < count; i++) { if (cb.getItemAt(i) instanceof ListItem) { ListItem item = (ListItem) cb.getItemAt(i); if (item.getCode() != null && item.getCode().equals(value)) { cb.setSelectedIndex(i); return; } } } } class BasicDataDefineTreeTSL implements TreeSelectionListener { private TreePath curPath = null; @Override public void valueChanged(TreeSelectionEvent e) { JTree tree = (JTree) e.getSource(); //判断原来的基础数据是否已保存 TreePath old = e.getOldLeadSelectionPath(); if (old != null) { DefaultMutableTreeNode oldNode = (DefaultMutableTreeNode) old.getLastPathComponent(); TreeUserObject uo = (TreeUserObject) oldNode.getUserObject(); if (uo.getObject() != null) { BasicDataDefine basicDataDefine = (BasicDataDefine) uo.getObject(); if (basicDataDefine instanceof CompoundBasicDataDefine) { //compoundBasicDataBL = this.getCompoundBasicDataBL((CompoundBasicDataDefine) basicDataDefine); } else if (basicDataDefine instanceof TreeBasicDataDefine) { if (treeBasicDataBL != null) { //MessageBox.confirm(""+treeBasicDataBL.isDirty()); } } else { //tablebl = getTableBasicDataBL(basicDataDefine); } } } DefaultMutableTreeNode node = (DefaultMutableTreeNode) tree.getLastSelectedPathComponent(); if (node == null) { return; } TreeUserObject uo = (TreeUserObject) node.getUserObject(); if (uo == null) { return; } if (uo.getObject() == null) { return; } BasicDataDefine bd = (BasicDataDefine) uo.getObject(); modifyBasicData(bd); } } // @Action(code = "001003") // public void modify() { // DefaultMutableTreeNode node = (DefaultMutableTreeNode) basicDataDefineTree.getLastSelectedPathComponent(); // if (node == null || node.isRoot() == true || !node.isLeaf() || node.getUserObject() == null || !(node.getUserObject() instanceof TreeUserObject)) { // this.showMessageDialog("请选择要修改的基础数据。"); // return; // } // //treeBasicDataEditSplitPane.setr // BasicData basicData = (BasicData) ((TreeUserObject) node.getUserObject()).getObject(); // if (basicData != null) { // this.setParam("basicData", basicData); // if (basicData instanceof TreeBasicData) { // this.showModalView(EditTreeBasicDataView.class); // } // } // } Map<BasicDataDefine, TreeBasicDataBL> treeBasicDataBLMap = new HashMap<BasicDataDefine, TreeBasicDataBL>(); //tablebl Map<BasicDataDefine, TableBasicDataBL> tableBasicDataBLMap = new HashMap<BasicDataDefine, TableBasicDataBL>(); public void modifyBasicData(BasicDataDefine basicDataDefine) { this.basicDataDefine = basicDataDefine; if (basicDataDefine == null) { throw new BasicDataException("TABLE BASIC DATA 不允许为空"); } if (basicDataDefine instanceof CompoundBasicDataDefine) { this.compoundBasicDataBL = this.getCompoundBasicDataBL((CompoundBasicDataDefine) basicDataDefine); this.masterSplitPane.setRightComponent(this.compoundSplitPane); } else if (basicDataDefine instanceof TreeBasicDataDefine) { treeBasicDataBL = getTreeBasicDataBL((TreeBasicDataDefine) basicDataDefine); treeBasicDataBL.initTree(); this.masterSplitPane.setRightComponent(this.treeBasicDataEditPane); } else { tablebl = getTableBasicDataBL(basicDataDefine); Class entityClass = basicDataDefine.getEntityClass(); tablebl.initTable(entityClass, mainTable, queryPanel); this.masterSplitPane.setRightComponent(this.tableBasicDataEditPane); } } @Action public void clear() { conditionTree.setText(null); search(); } @Action public void close() { closeView(true); } @Action public void search() { try { if (basicDataDefine instanceof TreeBasicDataDefine) { SearchOperation operationType = (SearchOperation) ((ListItem) operationTree.getSelectedItem()).getCode(); String conditionStr = conditionTree.getText(); if (StringUtils.isEmpty(conditionStr)) { basicDataTree.setModel(new DefaultTreeModel(treeBasicDataBL.initTree())); } else { basicDataTree.setModel(new DefaultTreeModel(treeBasicDataBL.searchTree(conditionStr, operationType))); } } } catch (Exception ex) { logger.log(Level.SEVERE, ex.getMessage(), ex); MessageBox.showError(ex.getMessage()); } } @Action public void reset() { conditionTextField.setText(null); query(); } @Action public void add() { Class entityClass = basicDataDefine.getEntityClass(); try { Object entity = entityClass.newInstance(); EditBasicDataTableView editView = new EditBasicDataTableView(tablebl, entity, entityClass); ModalResult modalResult = this.showModalView(editView); // if (ModalResult.OK.equals(modalResult)) { TableUtils.appendRow(mainTable, entity); } } catch (InstantiationException ex) { ex.printStackTrace(); } catch (IllegalAccessException ex) { ex.printStackTrace(); } } @Action public void delete() { Object sc = TableUtils.getSelectedRow(mainTable); if (sc != null) { int result = JOptionPane.showConfirmDialog(null, "确认删除记录吗?", "确认删除", JOptionPane.YES_NO_OPTION); if (result == JOptionPane.NO_OPTION) { return; } TableUtils.deleteRow(mainTable, sc); } else { MessageBox.showError("请选择一行记录!"); // JOptionPane.showMessageDialog( // null, // "请选择一行记录!", // "警告信息", // JOptionPane.WARNING_MESSAGE); } } @Action public void modifyTable() { Object selectedRow = TableUtils.getSelectedRow(mainTable); Class entityClass = basicDataDefine.getEntityClass(); if (selectedRow == null) { MessageBox.showError("请选择要修改的数据。"); return; } //避免选中多个,此时定位到第一个 mainTable.getSelectionModel().clearSelection(); TableUtils.setSelectedRow(mainTable, selectedRow); boolean isAdd = TableUtils.isAdded(mainTable, selectedRow); EditBasicDataTableView editView = new EditBasicDataTableView(tablebl, selectedRow, entityClass); ModalResult modalResult = showModalView(editView); if (ModalResult.OK.equals(modalResult)) { if (isAdd) { TableUtils.deleteRow(mainTable, selectedRow); } else { TableUtils.updateRow(mainTable, selectedRow); } } } @Action public boolean saveTableData() { Class entityClass = basicDataDefine.getEntityClass(); ModifiedTableData mtd = ModifiedTableDataUtils.buildModifiedTableData(mainTable); String pk = basicDataDefine.getCodePropertyName(); service.write(entityClass, mtd, pk); //清除状态 TableUtils.getObjectTableModel(mainTable).reset(); return true; } @Override @Action public boolean save() { if (basicDataDefine != null) { try { if (basicDataDefine instanceof TreeBasicDataDefine) { TreeBasicDataBL treeBL = this.getTreeBasicDataBL((TreeBasicDataDefine) basicDataDefine); treeBL.saveAll(); } else if (basicDataDefine instanceof CompoundBasicDataDefine) { this.getCompoundBasicDataBL((CompoundBasicDataDefine) basicDataDefine).saveAll(); } else { saveTableData(); } } catch (Exception ex) { MessageBox.showError("保存失败."); return false; } MessageBox.prompt("保存成功"); return true; } return true; } private OrFilterItem filterItem; @Action public void query() { String condittion = conditionTextField.getText(); String operation = (String) ((ListItem) operationComboBox.getSelectedItem()).getCode(); FilterType filterType = null; if (TableDataHelper.COMPARATE_TYPE_EQUALS.equals(operation)) { filterType = FilterType.EQUAL; } else if (TableDataHelper.COMPARATE_TYPE_LLIKE.equals(operation)) { filterType = FilterType.END_WITH; } else if (TableDataHelper.COMPARATE_TYPE_RLIKE.equals(operation)) { filterType = FilterType.START_WITH; } else { filterType = FilterType.CONTAIN; } System.out.println("filterType:" + filterType); if (filterItem != null) { TableUtils.removeFilter(mainTable, filterItem); } if (StringUtils.isNotEmpty(condittion)) { filterItem = new OrFilterItem(new SimpleFilterItem(basicDataDefine.getCodePropertyName(), filterType, condittion)); filterItem.or(new SimpleFilterItem(basicDataDefine.getNamePropertyName(), filterType, condittion)); TableUtils.setFilter(mainTable, filterItem); } // if (mainTableDataSet.isOpen()) { // mainTableDataSet.post(); // } // if (mainTableDataSet.getRow() >= 0) { // UniversalData params = new UniversalDataImpl(); // params.addObject("EntityClass").setValue(basicData.getEntityClass()); // params.addValue("condittionCode").set(condittion); // params.addValue("operationCode").set(operation); // params.addValue("CodePropertyName").set(basicData.getCodePropertyName()); // params.addValue("NamePropertyName").set(basicData.getNamePropertyName()); // read(READ_QUERY, params, mainTableDataSet); // } } /** * This method is called from within the constructor to initialize the form. * WARNING: Do NOT modify this code. The content of this method is always * regenerated by the Form Editor. */ @SuppressWarnings("unchecked") // <editor-fold defaultstate="collapsed" desc="Generated Code"> private void initComponents() { emptyPanel = new javax.swing.JPanel(); treeBasicDataEditPane = new javax.swing.JScrollPane(); splitPane1 = new javax.swing.JSplitPane(); leftPanel = new javax.swing.JPanel(); searchPanel = new javax.swing.JPanel(); jLabel1 = new javax.swing.JLabel(); operationTree = new javax.swing.JComboBox(); clearTreeButton = new javax.swing.JButton(); searchTreeButton = new javax.swing.JButton(); conditionTree = new javax.swing.JTextField(); jScrollPane2 = new javax.swing.JScrollPane(); basicDataTree = new org.itown.rcp.client.util.DnDTree(); rightPanel = new javax.swing.JPanel(); buttonPanel = new javax.swing.JPanel(); saveAllTreeButton = new javax.swing.JButton(); deleteTreeButton = new javax.swing.JButton(); addChildTreeButton = new javax.swing.JButton(); jScrollPane5 = new javax.swing.JScrollPane(); detailPanel = new javax.swing.JPanel(); compoundEditPane = new javax.swing.JScrollPane(); compoundSplitPane = new javax.swing.JSplitPane(); compoundLeftPanel = new javax.swing.JPanel(); jScrollPane3 = new javax.swing.JScrollPane(); compoundCategoryTree = new javax.swing.JTree(); jPanel2 = new javax.swing.JPanel(); modifyCompoundCategoryButton = new javax.swing.JButton(); addCompoundCategoryButton = new javax.swing.JButton(); delCompoundCategoryButton = new javax.swing.JButton(); compoundRightPanel = new javax.swing.JPanel(); jScrollPane4 = new javax.swing.JScrollPane(); compoundItemTable = new javax.swing.JTable(); jPanel1 = new javax.swing.JPanel(); modifyCompoundItemButton = new javax.swing.JButton(); delCompoundItemButton = new javax.swing.JButton(); addCompoundItemButton = new javax.swing.JButton(); tableBasicDataEditPane = new javax.swing.JScrollPane(); viewPanel = new javax.swing.JPanel(); addButton = new javax.swing.JButton(); modifyButton = new javax.swing.JButton(); deleteButton = new javax.swing.JButton(); saveButton = new javax.swing.JButton(); mainTableScrollPanel = new javax.swing.JScrollPane(); mainTable = new javax.swing.JTable(); queryPanel = new javax.swing.JPanel(); queryButton = new javax.swing.JButton(); clearButton = new javax.swing.JButton(); conditionTextField = new javax.swing.JTextField(); operationComboBox = new javax.swing.JComboBox(); conditionLabel = new javax.swing.JLabel(); masterPanel = new javax.swing.JPanel(); masterSplitPane = new javax.swing.JSplitPane(); jScrollPane1 = new javax.swing.JScrollPane(); basicDataDefineTree = new javax.swing.JTree(); javax.swing.GroupLayout emptyPanelLayout = new javax.swing.GroupLayout(emptyPanel); emptyPanel.setLayout(emptyPanelLayout); emptyPanelLayout.setHorizontalGroup( emptyPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGap(0, 100, Short.MAX_VALUE) ); emptyPanelLayout.setVerticalGroup( emptyPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGap(0, 100, Short.MAX_VALUE) ); splitPane1.setDividerLocation(260); jLabel1.setText("编码或名称:"); operationTree.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Item 1", "Item 2", "Item 3", "Item 4" })); clearTreeButton.setAction(getAction("clear")); clearTreeButton.setIcon(new javax.swing.ImageIcon(getClass().getResource("/images/16_16/congzhi.gif"))); // NOI18N clearTreeButton.setText("重置"); searchTreeButton.setAction(getAction("search")); searchTreeButton.setIcon(new javax.swing.ImageIcon(getClass().getResource("/images/16_16/search.gif"))); // NOI18N searchTreeButton.setText("查询"); searchTreeButton.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { searchTreeButtonActionPerformed(evt); } }); javax.swing.GroupLayout searchPanelLayout = new javax.swing.GroupLayout(searchPanel); searchPanel.setLayout(searchPanelLayout); searchPanelLayout.setHorizontalGroup( searchPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(searchPanelLayout.createSequentialGroup() .addContainerGap() .addGroup(searchPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING) .addGroup(javax.swing.GroupLayout.Alignment.LEADING, searchPanelLayout.createSequentialGroup() .addComponent(jLabel1) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(operationTree, 0, 71, Short.MAX_VALUE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 19, Short.MAX_VALUE) .addComponent(conditionTree, javax.swing.GroupLayout.PREFERRED_SIZE, 73, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGroup(searchPanelLayout.createSequentialGroup() .addComponent(searchTreeButton) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(clearTreeButton))) .addContainerGap()) ); searchPanelLayout.setVerticalGroup( searchPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(searchPanelLayout.createSequentialGroup() .addContainerGap() .addGroup(searchPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jLabel1) .addComponent(operationTree, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(conditionTree, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addGroup(searchPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(clearTreeButton) .addComponent(searchTreeButton)) .addContainerGap()) ); //basicDataTree.setProcessor(new UserObjectProcessor(){ // public void process(DefaultMutableTreeNode droppedNode,DefaultMutableTreeNode dropNode){ // TreeUserObject tuo = droppedNode.getUserObject(); // TreeUserObject target = dropNode.getUserObject(); // // System.out.println(""+tuo+","+target); // // } //}); jScrollPane2.setViewportView(basicDataTree); javax.swing.GroupLayout leftPanelLayout = new javax.swing.GroupLayout(leftPanel); leftPanel.setLayout(leftPanelLayout); leftPanelLayout.setHorizontalGroup( leftPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(searchPanel, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(jScrollPane2, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, 259, Short.MAX_VALUE) ); leftPanelLayout.setVerticalGroup( leftPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(leftPanelLayout.createSequentialGroup() .addComponent(searchPanel, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(jScrollPane2, javax.swing.GroupLayout.DEFAULT_SIZE, 304, Short.MAX_VALUE)) ); splitPane1.setLeftComponent(leftPanel); saveAllTreeButton.setIcon(new javax.swing.ImageIcon(getClass().getResource("/images/16_16/save.gif"))); // NOI18N saveAllTreeButton.setText("保存"); deleteTreeButton.setIcon(new javax.swing.ImageIcon(getClass().getResource("/images/16_16/delete.gif"))); // NOI18N deleteTreeButton.setText("删除"); addChildTreeButton.setIcon(new javax.swing.ImageIcon(getClass().getResource("/images/16_16/add.gif"))); // NOI18N addChildTreeButton.setText("增加子节点"); addChildTreeButton.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { addChildTreeButtonActionPerformed(evt); } }); javax.swing.GroupLayout buttonPanelLayout = new javax.swing.GroupLayout(buttonPanel); buttonPanel.setLayout(buttonPanelLayout); buttonPanelLayout.setHorizontalGroup( buttonPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, buttonPanelLayout.createSequentialGroup() .addContainerGap(113, Short.MAX_VALUE) .addComponent(addChildTreeButton) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(deleteTreeButton) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(saveAllTreeButton) .addContainerGap()) ); buttonPanelLayout.setVerticalGroup( buttonPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, buttonPanelLayout.createSequentialGroup() .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addGroup(buttonPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(saveAllTreeButton) .addComponent(deleteTreeButton) .addComponent(addChildTreeButton)) .addContainerGap()) ); javax.swing.GroupLayout detailPanelLayout = new javax.swing.GroupLayout(detailPanel); detailPanel.setLayout(detailPanelLayout); detailPanelLayout.setHorizontalGroup( detailPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGap(0, 408, Short.MAX_VALUE) ); detailPanelLayout.setVerticalGroup( detailPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGap(0, 333, Short.MAX_VALUE) ); jScrollPane5.setViewportView(detailPanel); javax.swing.GroupLayout rightPanelLayout = new javax.swing.GroupLayout(rightPanel); rightPanel.setLayout(rightPanelLayout); rightPanelLayout.setHorizontalGroup( rightPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(buttonPanel, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addGroup(rightPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jScrollPane5, javax.swing.GroupLayout.DEFAULT_SIZE, 408, Short.MAX_VALUE)) ); rightPanelLayout.setVerticalGroup( rightPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, rightPanelLayout.createSequentialGroup() .addContainerGap(339, Short.MAX_VALUE) .addComponent(buttonPanel, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGroup(rightPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(rightPanelLayout.createSequentialGroup() .addComponent(jScrollPane5) .addGap(47, 47, 47))) ); splitPane1.setRightComponent(rightPanel); treeBasicDataEditPane.setViewportView(splitPane1); compoundSplitPane.setDividerLocation(260); compoundSplitPane.setPreferredSize(new java.awt.Dimension(862, 342)); jScrollPane3.setViewportView(compoundCategoryTree); modifyCompoundCategoryButton.setIcon(new javax.swing.ImageIcon(getClass().getResource("/images/16_16/edit.gif"))); // NOI18N modifyCompoundCategoryButton.setText("修改"); addCompoundCategoryButton.setIcon(new javax.swing.ImageIcon(getClass().getResource("/images/16_16/add.gif"))); // NOI18N addCompoundCategoryButton.setText("增加"); delCompoundCategoryButton.setIcon(new javax.swing.ImageIcon(getClass().getResource("/images/16_16/delete.gif"))); // NOI18N delCompoundCategoryButton.setText("删除"); javax.swing.GroupLayout jPanel2Layout = new javax.swing.GroupLayout(jPanel2); jPanel2.setLayout(jPanel2Layout); jPanel2Layout.setHorizontalGroup( jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel2Layout.createSequentialGroup() .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(addCompoundCategoryButton) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) .addComponent(modifyCompoundCategoryButton) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(delCompoundCategoryButton) .addGap(6, 6, 6)) ); jPanel2Layout.setVerticalGroup( jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel2Layout.createSequentialGroup() .addContainerGap() .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(addCompoundCategoryButton) .addComponent(modifyCompoundCategoryButton) .addComponent(delCompoundCategoryButton)) .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)) ); javax.swing.GroupLayout compoundLeftPanelLayout = new javax.swing.GroupLayout(compoundLeftPanel); compoundLeftPanel.setLayout(compoundLeftPanelLayout); compoundLeftPanelLayout.setHorizontalGroup( compoundLeftPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jPanel2, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(jScrollPane3, javax.swing.GroupLayout.DEFAULT_SIZE, 263, Short.MAX_VALUE) ); compoundLeftPanelLayout.setVerticalGroup( compoundLeftPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, compoundLeftPanelLayout.createSequentialGroup() .addComponent(jScrollPane3, javax.swing.GroupLayout.DEFAULT_SIZE, 289, Short.MAX_VALUE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(jPanel2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) ); compoundSplitPane.setLeftComponent(compoundLeftPanel); compoundRightPanel.setPreferredSize(new java.awt.Dimension(596, 240)); compoundItemTable.setModel(new javax.swing.table.DefaultTableModel( new Object [][] { {null, null, null, null}, {null, null, null, null}, {null, null, null, null}, {null, null, null, null} }, new String [] { "Title 1", "Title 2", "Title 3", "Title 4" } )); jScrollPane4.setViewportView(compoundItemTable); modifyCompoundItemButton.setIcon(new javax.swing.ImageIcon(getClass().getResource("/images/16_16/edit.gif"))); // NOI18N modifyCompoundItemButton.setText("修改"); delCompoundItemButton.setIcon(new javax.swing.ImageIcon(getClass().getResource("/images/16_16/delete.gif"))); // NOI18N delCompoundItemButton.setText("删除"); delCompoundItemButton.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { delCompoundItemButtonActionPerformed(evt); } }); addCompoundItemButton.setIcon(new javax.swing.ImageIcon(getClass().getResource("/images/16_16/add.gif"))); // NOI18N addCompoundItemButton.setText("增加"); javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1); jPanel1.setLayout(jPanel1Layout); jPanel1Layout.setHorizontalGroup( jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel1Layout.createSequentialGroup() .addContainerGap(343, Short.MAX_VALUE) .addComponent(addCompoundItemButton) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(modifyCompoundItemButton) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(delCompoundItemButton) .addContainerGap()) ); jPanel1Layout.setVerticalGroup( jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel1Layout.createSequentialGroup() .addContainerGap() .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(delCompoundItemButton) .addComponent(modifyCompoundItemButton) .addComponent(addCompoundItemButton)) .addContainerGap(13, Short.MAX_VALUE)) ); javax.swing.GroupLayout compoundRightPanelLayout = new javax.swing.GroupLayout(compoundRightPanel); compoundRightPanel.setLayout(compoundRightPanelLayout); compoundRightPanelLayout.setHorizontalGroup( compoundRightPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(jScrollPane4, javax.swing.GroupLayout.DEFAULT_SIZE, 596, Short.MAX_VALUE) ); compoundRightPanelLayout.setVerticalGroup( compoundRightPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(compoundRightPanelLayout.createSequentialGroup() .addComponent(jScrollPane4, javax.swing.GroupLayout.DEFAULT_SIZE, 186, Short.MAX_VALUE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) ); compoundSplitPane.setRightComponent(compoundRightPanel); compoundEditPane.setViewportView(compoundSplitPane); addButton.setAction(getAction("add")); addButton.setIcon(new javax.swing.ImageIcon(getClass().getResource("/images/16_16/add.gif"))); // NOI18N addButton.setText("增加"); modifyButton.setAction(getAction("modifyTable")); modifyButton.setIcon(new javax.swing.ImageIcon(getClass().getResource("/images/16_16/edit.gif"))); // NOI18N modifyButton.setText("修改"); deleteButton.setAction(getAction("delete")); deleteButton.setIcon(new javax.swing.ImageIcon(getClass().getResource("/images/16_16/delete.gif"))); // NOI18N deleteButton.setText("删除"); saveButton.setAction(getAction("save")); saveButton.setIcon(new javax.swing.ImageIcon(getClass().getResource("/images/16_16/save.gif"))); // NOI18N saveButton.setText("保存"); mainTable.setModel(new javax.swing.table.DefaultTableModel( new Object [][] { {null, null, null, null}, {null, null, null, null}, {null, null, null, null}, {null, null, null, null} }, new String [] { "Title 1", "Title 2", "Title 3", "Title 4" } )); mainTableScrollPanel.setViewportView(mainTable); queryButton.setAction(getAction("query")); queryButton.setIcon(new javax.swing.ImageIcon(getClass().getResource("/images/16_16/search.gif"))); // NOI18N queryButton.setText("查询"); clearButton.setAction(getAction("reset")); clearButton.setIcon(new javax.swing.ImageIcon(getClass().getResource("/images/16_16/congzhi.gif"))); // NOI18N clearButton.setText("重置"); Map items = new LinkedMap(); items.put(TableDataHelper.COMPARATE_TYPE_LIKE, "包含"); items.put(TableDataHelper.COMPARATE_TYPE_LLIKE, "左匹配"); items.put(TableDataHelper.COMPARATE_TYPE_RLIKE, "右匹配"); items.put(TableDataHelper.COMPARATE_TYPE_EQUALS, "等于"); operationComboBox.setModel(new MapComboBoxModel(items,false)); conditionLabel.setText("编码或名称:"); javax.swing.GroupLayout queryPanelLayout = new javax.swing.GroupLayout(queryPanel); queryPanel.setLayout(queryPanelLayout); queryPanelLayout.setHorizontalGroup( queryPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(queryPanelLayout.createSequentialGroup() .addComponent(conditionLabel) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(operationComboBox, javax.swing.GroupLayout.PREFERRED_SIZE, 150, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) .addComponent(conditionTextField, javax.swing.GroupLayout.DEFAULT_SIZE, 373, Short.MAX_VALUE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(queryButton) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(clearButton) .addContainerGap()) ); queryPanelLayout.setVerticalGroup( queryPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(queryPanelLayout.createSequentialGroup() .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addGroup(queryPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(conditionLabel) .addComponent(operationComboBox, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(conditionTextField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(clearButton) .addComponent(queryButton))) ); javax.swing.GroupLayout viewPanelLayout = new javax.swing.GroupLayout(viewPanel); viewPanel.setLayout(viewPanelLayout); viewPanelLayout.setHorizontalGroup( viewPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, viewPanelLayout.createSequentialGroup() .addContainerGap(449, Short.MAX_VALUE) .addComponent(addButton) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(modifyButton) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(deleteButton) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(saveButton) .addContainerGap()) .addComponent(queryPanel, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addGroup(viewPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(mainTableScrollPanel, javax.swing.GroupLayout.DEFAULT_SIZE, 785, Short.MAX_VALUE)) ); viewPanelLayout.setVerticalGroup( viewPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, viewPanelLayout.createSequentialGroup() .addComponent(queryPanel, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 288, Short.MAX_VALUE) .addGroup(viewPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(saveButton) .addComponent(deleteButton) .addComponent(modifyButton) .addComponent(addButton))) .addGroup(viewPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(viewPanelLayout.createSequentialGroup() .addGap(37, 37, 37) .addComponent(mainTableScrollPanel, javax.swing.GroupLayout.DEFAULT_SIZE, 284, Short.MAX_VALUE) .addGap(27, 27, 27))) ); this.setComponent(viewPanel); tableBasicDataEditPane.setViewportView(viewPanel); masterSplitPane.setDividerLocation(300); jScrollPane1.setViewportView(basicDataDefineTree); masterSplitPane.setLeftComponent(jScrollPane1); javax.swing.GroupLayout masterPanelLayout = new javax.swing.GroupLayout(masterPanel); masterPanel.setLayout(masterPanelLayout); masterPanelLayout.setHorizontalGroup( masterPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(masterSplitPane, javax.swing.GroupLayout.DEFAULT_SIZE, 893, Short.MAX_VALUE) ); masterPanelLayout.setVerticalGroup( masterPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(masterSplitPane, javax.swing.GroupLayout.DEFAULT_SIZE, 431, Short.MAX_VALUE) ); javax.swing.GroupLayout layout = new javax.swing.GroupLayout(this); this.setLayout(layout); layout.setHorizontalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(masterPanel, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) ); layout.setVerticalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addGap(5, 5, 5) .addComponent(masterPanel, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) ); }// </editor-fold> private void addChildTreeButtonActionPerformed(java.awt.event.ActionEvent evt) { // TODO add your handling code here: } private void searchTreeButtonActionPerformed(java.awt.event.ActionEvent evt) { searchTree(); } private void delCompoundItemButtonActionPerformed(java.awt.event.ActionEvent evt) { // TODO add your handling code here: } // Variables declaration - do not modify private javax.swing.JButton addButton; private javax.swing.JButton addChildTreeButton; private javax.swing.JButton addCompoundCategoryButton; private javax.swing.JButton addCompoundItemButton; private javax.swing.JTree basicDataDefineTree; private org.itown.rcp.client.util.DnDTree basicDataTree; private javax.swing.JPanel buttonPanel; private javax.swing.JButton clearButton; private javax.swing.JButton clearTreeButton; private javax.swing.JTree compoundCategoryTree; private javax.swing.JScrollPane compoundEditPane; private javax.swing.JTable compoundItemTable; private javax.swing.JPanel compoundLeftPanel; private javax.swing.JPanel compoundRightPanel; private javax.swing.JSplitPane compoundSplitPane; private javax.swing.JLabel conditionLabel; private javax.swing.JTextField conditionTextField; private javax.swing.JTextField conditionTree; private javax.swing.JButton delCompoundCategoryButton; private javax.swing.JButton delCompoundItemButton; private javax.swing.JButton deleteButton; private javax.swing.JButton deleteTreeButton; private javax.swing.JPanel detailPanel; private javax.swing.JPanel emptyPanel; private javax.swing.JLabel jLabel1; private javax.swing.JPanel jPanel1; private javax.swing.JPanel jPanel2; private javax.swing.JScrollPane jScrollPane1; private javax.swing.JScrollPane jScrollPane2; private javax.swing.JScrollPane jScrollPane3; private javax.swing.JScrollPane jScrollPane4; private javax.swing.JScrollPane jScrollPane5; private javax.swing.JPanel leftPanel; private javax.swing.JTable mainTable; private javax.swing.JScrollPane mainTableScrollPanel; private javax.swing.JPanel masterPanel; private javax.swing.JSplitPane masterSplitPane; private javax.swing.JButton modifyButton; private javax.swing.JButton modifyCompoundCategoryButton; private javax.swing.JButton modifyCompoundItemButton; private javax.swing.JComboBox operationComboBox; private javax.swing.JComboBox operationTree; private javax.swing.JButton queryButton; private javax.swing.JPanel queryPanel; private javax.swing.JPanel rightPanel; private javax.swing.JButton saveAllTreeButton; private javax.swing.JButton saveButton; private javax.swing.JPanel searchPanel; private javax.swing.JButton searchTreeButton; private javax.swing.JSplitPane splitPane1; private javax.swing.JScrollPane tableBasicDataEditPane; private javax.swing.JScrollPane treeBasicDataEditPane; private javax.swing.JPanel viewPanel; // End of variables declaration private Logger logger = Logger.getLogger(this.getClass().getName()); @Action public void addCompoundItem() { if (this.curCategory == null) { MessageBox.showError("请选择要操作的类别。"); return; } SysCompound newItem = new SysCompound(); newItem.setCategory(curCategory.getCategory()); newItem.setParentId(curCategory.getCompoundId()); newItem.setCompoundId(UUIDKeyGenerator.newInstance().generateKey()); ModifyCompoundView modifyCompoundView = new ModifyCompoundView(newItem, ModifyCompoundView.STATUS_ADD, true); ModalResult result = this.showModalView(modifyCompoundView); if (ModalResult.OK.equals(result)) { newItem = modifyCompoundView.getCompound(); this.compoundItems.add(newItem); this.compoundBasicDataBL.addItemToCache(newItem); //this.handler.addNewObject(newSchema); int lastIndex = compoundItems.size() - 1; this.compoundItemTable.setRowSelectionInterval(lastIndex, lastIndex); } } @Action public void modifyCompoundItem() { if (this.curCategory == null) { MessageBox.showError("请选择要操作的类别。"); return; } int selectedRow = this.compoundItemTable.getSelectedRow(); if (selectedRow >= 0) { SysCompound modifySchema = (SysCompound) this.compoundItems.get(selectedRow); ModifyCompoundView modifyView = new ModifyCompoundView(modifySchema, ModifyCompoundView.STATUS_MODIFY, true); ModalResult result = this.showModalView(modifyView); if (ModalResult.OK.equals(result)) { modifySchema = modifyView.getCompound(); compoundItems.remove(modifySchema); compoundItems.add(selectedRow, modifySchema); compoundItemTable.setRowSelectionInterval(selectedRow, selectedRow); MessageBox.prompt("修改成功!"); } } else { MessageBox.showError("请选择要修改的数据。"); } } @Action public void delCompoundItem() { int selectedRow = this.compoundItemTable.getSelectedRow(); if (selectedRow >= 0) { int isOk = this.showConfirmDialog("您确认要删除这条记录吗?"); if (1 == isOk) { try { SysCompound compound = (SysCompound) compoundItems.get(selectedRow); delCompound(compound); compoundBasicDataBL.removeCompoundFromCache(compound); compoundItems.remove(selectedRow); if (selectedRow < compoundItems.size()) { compoundItemTable.getSelectionModel().setSelectionInterval(selectedRow, selectedRow); } else if ((selectedRow - 1) >= 0) { selectedRow--; compoundItemTable.getSelectionModel().setSelectionInterval(selectedRow, selectedRow); } MessageBox.prompt("删除成功!"); } catch (Exception ex) { MessageBox.showError(ex.getMessage()); } } } else { MessageBox.prompt("请选择要删除的列。"); } } /** * 删除数据 * * @param obj * @param deleteChildren */ public void delCompound(Object obj) { // UniversalData params = new UniversalDataImpl(); // params.addObject("entity").setValue(obj); // params.addValue("deleteChildren").set(true); // params.addValue("codeProperty").set("compoundId"); // params.addValue("parentCodeProperty").set("parentId"); // invoke("basicdataService", "deleteBasicData", params); service.removeEntity(obj, "compoundId", "parentId", true); } @Action public void delCompoundCategory() { DefaultMutableTreeNode node = (DefaultMutableTreeNode) this.compoundCategoryTree.getLastSelectedPathComponent(); if (node == null) { MessageBox.showError("请选择要删除的类别"); return; } if (node.isRoot() == true) { MessageBox.showError("不能删除根节点"); return; } int isOk = this.showConfirmDialog("您确认要删除当前类别吗?"); if (1 == isOk) { try { TreeUserObject uo = (TreeUserObject) node.getUserObject(); SysCompound delSchema = (SysCompound) uo.getObject(); this.delCompound(delSchema); JTreeHelper.removeNode(compoundCategoryTree, node); MessageBox.prompt("类别" + delSchema.getName() + "已删除。"); } catch (Exception ex) { logger.log(Level.SEVERE, ex.getMessage(), ex); MessageBox.showError("类别删除失败:" + ex.getMessage()); } } } @Action public void modifyCompoundCategory() { if (this.curCategory == null) { MessageBox.showError("请选择要操作的类别。"); return; } DefaultMutableTreeNode node = (DefaultMutableTreeNode) this.compoundCategoryTree.getLastSelectedPathComponent(); SysCompound modifyCategory = curCategory; ModifyCompoundView modifyView = new ModifyCompoundView(modifyCategory, ModifyCompoundView.STATUS_MODIFY, false); ModalResult result = this.showModalView(modifyView); if (ModalResult.OK.equals(result)) { curCategory = modifyView.getCompound(); ((TreeUserObject) node.getUserObject()).setValue(curCategory.getName()); DefaultTreeModel model = (DefaultTreeModel) compoundCategoryTree.getModel(); model.nodeChanged(node); MessageBox.prompt("修改成功!"); } } @Action public void addCompoundCategory() { ModifyCompoundView midifyCompoundView = new ModifyCompoundView(null, ModifyCompoundView.STATUS_ADD, false); ModalResult modalResult = this.showModalView(midifyCompoundView); if (ModalResult.OK.equals(modalResult)) { SysCompound newCategory = midifyCompoundView.getCompound(); DefaultTreeModel model = (DefaultTreeModel) this.compoundCategoryTree.getModel(); |
|||
25 | 25 | ||
package com.itown.rcp.basicdata.view; import com.itown.rcp.basicdata.view.BDLookupTextUI; import com.itown.rcp.swing.lookup.Lookupable; import com.itown.rcp.swing.lookup.TextFieldUI; import java.util.HashMap; import java.util.Map; import javax.swing.JButton; import javax.swing.plaf.TextUI; import javax.swing.text.JTextComponent; /** * * @author yingwl */ public class BasicDataTextFieldUI implements TextFieldUI { public void buildUI(JButton button, JTextComponent textField, Lookupable lookupable) { if (textField != null && lookupable != null) { if (BasicDataLookupDialog.class.equals(lookupable.getClass())) { String entityName = getEntityName(lookupable); textField.setUI((TextUI) BDLookupTextUI.createUI(textField, entityName)); } } } private static String getEntityName(final Lookupable lookupable) { String basicDataId = lookupable.getParams(); int location = basicDataId.indexOf("{"); String entityName = basicDataId.substring(0, location); return entityName; } /** * 解析参数,格式如: SysCompany{code:companyCode,name:companyName} * 解析后存放到entityName及propsMap */ private static Map parseParams(String params) { Map propsMap = new HashMap(); int location = params.indexOf("{"); String others = params.substring(location); others = others.substring(1, others.lastIndexOf("}")); String[] arrays = others.split(","); for (int i = 0; i < arrays.length; i++) { propsMap.put(arrays[i].substring(0, arrays[i].indexOf(":")).trim(), arrays[i].substring(arrays[i].indexOf(":") + 1).trim()); } return propsMap; } } |
|||
24 | 24 | ||
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ /* * BasicDataLookupDialog.java * * Created on 2010-3-4, 13:42:39 */ package com.itown.rcp.basicdata.view; import com.itown.rcp.basicdata.BasicData; import com.itown.rcp.basicdata.BasicDataDefine; import com.itown.rcp.basicdata.BasicDataException; import com.itown.rcp.basicdata.TreeBasicDataDefine; import com.itown.rcp.basicdata.impl.BasicDataFactory; import com.itown.rcp.basicdata.impl.BasicDataUtils; import com.itown.rcp.client.ShortcutManager; import com.itown.rcp.client.test.AuthenticatedTestBase; import com.itown.rcp.swing.fsp.filter.FilterItem; import com.itown.rcp.swing.lookup.Lookupable; import com.itown.rcp.swing.table.TableConfig; import com.itown.rcp.swing.tree.CheckNode; import java.awt.Component; import java.awt.Dimension; import java.awt.HeadlessException; import java.awt.Toolkit; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.KeyEvent; import java.awt.event.KeyListener; import java.awt.event.MouseAdapter; import java.awt.event.MouseEvent; import java.util.Collections; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.WeakHashMap; import java.util.logging.Level; import java.util.logging.Logger; import javax.swing.AbstractAction; import javax.swing.ActionMap; import javax.swing.InputMap; import javax.swing.JComponent; import javax.swing.JOptionPane; import javax.swing.JRootPane; import javax.swing.JTable; import javax.swing.JTree; import javax.swing.KeyStroke; import javax.swing.SwingUtilities; import javax.swing.UIManager; import javax.swing.tree.DefaultMutableTreeNode; import javax.swing.tree.TreeModel; import javax.swing.tree.TreePath; import org.apache.commons.beanutils.BeanUtils; /** * * @author yingwl */ public class BasicDataLookupDialog extends javax.swing.JDialog implements Lookupable { private BasicDataLookupContentPane lookupContent; private Object selectedValue; private boolean onlySelectLeafNode = false; /** * 解析参数,格式如: SysCompany{code:companyCode,name:companyName} * 解析后存放到entityName及propsMap */ private String entityName; private Map propsMap = new HashMap(); private boolean isInit; private boolean multiSelected = false; private boolean dgInSelection = false; private BasicDataDefine basicDataDefine; //树形基础数据的根节点 private String[] rootCodes; private TableConfig tableConfig; public String[] getRootCodes() { return rootCodes; } public void setRootCodes(String[] rootCodes) { this.rootCodes = rootCodes; if (rootCodes != null) { this.isInit = false; } } public TableConfig getTableConfig() { return tableConfig; } public void setTableConfig(TableConfig tableConfig) { this.tableConfig = tableConfig; if (tableConfig != null) { this.isInit = false; } } /** * 显示查询对话框时的名称与代码的查询值 */ private QueryCondition condition; ShortcutManager.ShortcutListener f6action = new ShortcutManager.ShortcutListener() { public void handle() { codeTextField.requestFocus(); } }; ShortcutManager.ShortcutListener f7action = new ShortcutManager.ShortcutListener() { public void handle() { nameTextField.requestFocus(); } }; ShortcutManager.ShortcutListener f8action = new ShortcutManager.ShortcutListener() { public void handle() { Component com = lookupContent.getComponent(); if (com instanceof JTable) { JTable table = (JTable) com; if (table.getRowCount() > 0) { //table.getSelectionModel().setSelectionInterval(0, 0); } table.requestFocus(); } } }; public BasicDataLookupDialog() { super((java.awt.Frame) null, true); initComponents(); this.setTitle("基础数据查询"); // createRootPane(); //设置图标 } @Override protected JRootPane createRootPane() { ActionListener actionListener_Esc = new ActionListener() { public void actionPerformed(ActionEvent actionEvent) { dispose(); } }; JRootPane rootPane1 = new JRootPane(); rootPane1.registerKeyboardAction(actionListener_Esc, KeyStroke.getKeyStroke(KeyEvent.VK_ESCAPE, 0), JComponent.WHEN_IN_FOCUSED_WINDOW); return rootPane1; } public BasicDataLookupDialog(boolean multiSelected) { this(); this.multiSelected = multiSelected; } /** * This method is called from within the constructor to initialize the form. * WARNING: Do NOT modify this code. The content of this method is always * regenerated by the Form Editor. */ @SuppressWarnings("unchecked") // <editor-fold defaultstate="collapsed" desc="Generated Code"> private void initComponents() { contentPane = new javax.swing.JPanel(); queryPanel = new javax.swing.JPanel(); jLabel1 = new javax.swing.JLabel(); codeTextField = new javax.swing.JTextField(); jLabel2 = new javax.swing.JLabel(); nameTextField = new javax.swing.JTextField(); queryButton = new javax.swing.JButton(); resetButton = new javax.swing.JButton(); buttonPanel = new javax.swing.JPanel(); okButton = new javax.swing.JButton(); cancelButton = new javax.swing.JButton(); setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE); contentPane.setLayout(new java.awt.BorderLayout()); jLabel1.setText("代码:"); queryPanel.add(jLabel1); codeTextField.setName("code"); // NOI18N codeTextField.setPreferredSize(new java.awt.Dimension(80, 21)); codeTextField.addKeyListener(new java.awt.event.KeyAdapter() { public void keyReleased(java.awt.event.KeyEvent evt) { codeTextFieldKeyReleased(evt); } }); queryPanel.add(codeTextField); jLabel2.setText("名称:"); queryPanel.add(jLabel2); nameTextField.setName("name"); // NOI18N nameTextField.setPreferredSize(new java.awt.Dimension(80, 21)); nameTextField.addKeyListener(new java.awt.event.KeyAdapter() { public void keyReleased(java.awt.event.KeyEvent evt) { nameTextFieldKeyReleased(evt); } }); queryPanel.add(nameTextField); queryButton.setIcon(new javax.swing.ImageIcon(getClass().getResource("/images/16_16/search.gif"))); // NOI18N queryButton.setText("查询"); queryButton.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { queryButtonActionPerformed(evt); } }); queryPanel.add(queryButton); resetButton.setIcon(new javax.swing.ImageIcon(getClass().getResource("/images/16_16/congzhi.gif"))); // NOI18N resetButton.setText("重置"); resetButton.setName("resetButton"); // NOI18N resetButton.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { resetButtonActionPerformed(evt); } }); queryPanel.add(resetButton); okButton.setIcon(new javax.swing.ImageIcon(getClass().getResource("/images/16_16/ok.gif"))); // NOI18N okButton.setText("确定"); okButton.setName("okButton"); // NOI18N okButton.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { okButtonActionPerformed(evt); } }); buttonPanel.add(okButton); cancelButton.setIcon(new javax.swing.ImageIcon(getClass().getResource("/images/16_16/cencel.gif"))); // NOI18N cancelButton.setText("取消"); cancelButton.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { cancelButtonActionPerformed(evt); } }); buttonPanel.add(cancelButton); javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane()); getContentPane().setLayout(layout); layout.setHorizontalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(queryPanel, javax.swing.GroupLayout.DEFAULT_SIZE, 427, Short.MAX_VALUE) .addComponent(buttonPanel, javax.swing.GroupLayout.DEFAULT_SIZE, 427, Short.MAX_VALUE) .addComponent(contentPane, javax.swing.GroupLayout.DEFAULT_SIZE, 427, Short.MAX_VALUE) ); layout.setVerticalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addComponent(queryPanel, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(contentPane, javax.swing.GroupLayout.DEFAULT_SIZE, 230, Short.MAX_VALUE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) .addComponent(buttonPanel, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) ); pack(); }// </editor-fold> private void queryTable() { JTable queryTable = (JTable) lookupContent.getComponent(); int rows = queryTable.getRowCount(); if (rows == 1) { ok(); } } private void codeTextFieldKeyReleased(java.awt.event.KeyEvent evt) { if (KeyEvent.VK_ENTER == evt.getKeyCode()) { doQuery(); } } private void nameTextFieldKeyReleased(java.awt.event.KeyEvent evt) { if (KeyEvent.VK_ENTER == evt.getKeyCode()) { doQuery(); } } private void doQuery() { if (basicDataDefine instanceof TreeBasicDataDefine) {//tree this.queryButton.doClick(); //是否有查询结果,如果只有一条记录,则执行ok(); JTree tree = (JTree) lookupContent.getComponent(); DefaultMutableTreeNode root = (DefaultMutableTreeNode) tree.getModel().getRoot(); if (root.getChildCount() == 1) { DefaultMutableTreeNode child = (DefaultMutableTreeNode) root.getFirstChild(); if (child.getChildCount() == 0) { tree.setSelectionPath(new TreePath(child.getPath())); if (child instanceof CheckNode){ CheckNode cnode = (CheckNode) child; cnode.setSelected(true, tree); } ok(); } } } else { queryTable(); this.queryButton.doClick(); } } private void queryButtonActionPerformed(java.awt.event.ActionEvent evt) { this.lookupContent.query(codeTextField, nameTextField); } private void resetButtonActionPerformed(java.awt.event.ActionEvent evt) { codeTextField.setText(""); nameTextField.setText(""); lookupContent.query(codeTextField, nameTextField); } private void okButtonActionPerformed(java.awt.event.ActionEvent evt) { removeAction(); ok(); } private void cancelButtonActionPerformed(java.awt.event.ActionEvent evt) { okButtonClicked = false; removeAction(); this.dispose(); } private void removeAction() { // ShortcutManager.getInstance().removeShortcutListener(f6action); // ShortcutManager.getInstance().removeShortcutListener(f7action); // ShortcutManager.getInstance().removeShortcutListener(f8action); } public void ok() throws HeadlessException { if (lookupContent.getSelectedObjects() != null) { okButtonClicked = true; this.dispose(); } else { JOptionPane.showMessageDialog(this, "请选择一条记录。"); } } public boolean isMultiSelected() { return multiSelected; } public void setMultiSelected(boolean multiSelected) { this.multiSelected = multiSelected; } public boolean isOnlySelectLeafNode() { return onlySelectLeafNode; } public void setOnlySelectLeafNode(boolean onlySelectLeafNode) { if (this.lookupContent != null && lookupContent instanceof TreeBasicDataLookupPane) { TreeBasicDataLookupPane treePane = (TreeBasicDataLookupPane) lookupContent; treePane.setOnlySelectLeafNode(onlySelectLeafNode); } this.onlySelectLeafNode = onlySelectLeafNode; } /** * @param args the command line arguments */ public static void main(String args[]) { java.awt.EventQueue.invokeLater(new Runnable() { public void run() { AuthenticatedTestBase testBase = new AuthenticatedTestBase("root", "root"); BasicDataLookupDialog dialog = new BasicDataLookupDialog(); dialog.addWindowListener(new java.awt.event.WindowAdapter() { public void windowClosing(java.awt.event.WindowEvent e) { System.exit(0); } }); dialog.setParams("SysCompany{code:companyCode,name:companyName}"); Object result = dialog.getResult(null); System.out.println(result); } }); } private String propertyName = null; @Override public void setPropertyName(String propertyName) { this.propertyName = propertyName; } @Override public void setSelectedValue(JTable table, Object value) { this.selectedValue = value; } public BasicDataDefine getBasicDataDefine() { return basicDataDefine; } public void setBasicDataDefine(BasicDataDefine basicDataDefine) { this.basicDataDefine = basicDataDefine; } @Override public boolean validate(Object value) { return true; } private String getKey(String text) { return entityName + text; } private Object getEntityFromCache(String text) { return entityCache.get(text); } private static Map entityCache = Collections.synchronizedMap(new WeakHashMap()); private Object findEntity( String text) { String key = getKey(text); Object result = getEntityFromCache(key); if (result != null) { return result; } synchronized (key) { BasicData basicData = BasicDataFactory.getInstance().getBasicData(entityName); result = basicData.getEntity(text); putEntityToCache(key, result); } return result; } private void putEntityToCache(String text, Object result) { entityCache.put(text, result); } public String getTitle(Object value) { Object name = ""; if (value == null) { return ""; } String codeValue = value.toString(); Object entity = this.findEntity(codeValue); if (entity == null) { return codeValue; } String nameProperty = BasicDataUtils.getBasicDataDefine(entityName).getNamePropertyName(); try { return codeValue + "[" + BeanUtils.getSimpleProperty(entity, nameProperty) + "]"; } catch (Exception ex) { throw new BasicDataException("基础数据:" + name + "获取名称失败", ex); } } private String params; @Override public void setParams(String params) { this.params = params.trim(); parseParams(getParams()); } public String getPropertyName() { return propertyName; } public String getParams() { return params; } public String getBasicDataId() { return entityName; } private boolean okButtonClicked = false; public synchronized Object getResult(JTable table) { Object result = null; this.init(); this.setVisible(true); if (okButtonClicked) { result = lookupContent.getSelectedObjects(); } return result; } public synchronized List getReturnEntities() { List result = null; this.init(); this.setVisible(true); if (okButtonClicked) { result = lookupContent.getSelectedEntities(); } return result; } private FilterItem customizerFilter; public FilterItem getCustomizerFilter() { return customizerFilter; } public QueryCondition getCondition() { return condition; } public void setCondition(QueryCondition condition) { this.condition = condition; if (condition != null) { codeTextField.setText(condition.getCode() == null ? "" : condition.getCode()); nameTextField.setText(condition.getName() == null ? "" : condition.getName()); } else { codeTextField.setText(""); nameTextField.setText(""); } this.isInit = false; } public void setCustomizerFilter(FilterItem customizerFilter) { this.customizerFilter = customizerFilter; this.isInit = false; } public boolean isDgInSelection() { return dgInSelection; } public void setDgInSelection(boolean dgInSelection) { this.dgInSelection = dgInSelection; } public String getEntityName() { return entityName; } private synchronized void init() { if (!isInit) { if (lookupContent == null) { if (basicDataDefine instanceof TreeBasicDataDefine) {//tree lookupContent = new TreeBasicDataLookupPane((TreeBasicDataDefine) basicDataDefine, propsMap, this.getCustomizerFilter(), this.multiSelected, this.condition, dgInSelection, rootCodes, this.onlySelectLeafNode); JTree tree = (JTree) lookupContent.getComponent();; tree.addKeyListener(new KeyListener() { public void keyTyped(KeyEvent e) { System.out.println("-----------1----------------------"); } public void keyPressed(KeyEvent e) { System.out.println("-----------2----------------------"); } public void keyReleased(KeyEvent evt) { if (KeyEvent.VK_ENTER == evt.getKeyCode()) { System.out.println("-----------3----------------------"); ok(); } } }); // tree.getBasicDataTree().addMouseListener(new OKMouseListener()); } else { lookupContent = new ListBasicDataLookupPane(basicDataDefine, propsMap, getCustomizerFilter(), multiSelected, this.codeTextField, this.nameTextField); } contentPane.add((Component) lookupContent); ActionMap am = (ActionMap) UIManager.get("Table.actionMap"); if (am != null) { am.put("selectNextRowCell", new AbstractAction() { public void actionPerformed(ActionEvent e) { ok(); } }); } ActionMap actionMap = lookupContent.getActionMap(); InputMap inputMap = lookupContent.getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW); actionMap.put(KeyEvent.VK_F6, new AbstractAction() { public void actionPerformed(ActionEvent e) { codeTextField.requestFocus(); } }); actionMap.put(KeyEvent.VK_F7, new AbstractAction() { public void actionPerformed(ActionEvent e) { nameTextField.requestFocus(); } }); actionMap.put(KeyEvent.VK_F8, new AbstractAction() { public void actionPerformed(ActionEvent e) { Component com = lookupContent.getComponent(); if (com instanceof JTable) { JTable table = (JTable) com; if (table.getRowCount() > 0) { //table.getSelectionModel().setSelectionInterval(0, 0); } table.requestFocus(); } else if (com instanceof JTree) { JTree tree = (JTree) com; TreeModel model = tree.getModel(); DefaultMutableTreeNode root = (DefaultMutableTreeNode) model.getRoot(); if (root.getChildCount() > 0) { DefaultMutableTreeNode firstNode = (DefaultMutableTreeNode) root.getFirstChild(); tree.setSelectionPath(new TreePath(firstNode.getPath())); } tree.requestFocus(); } } }); KeyStroke keyStroke = KeyStroke.getKeyStroke(KeyEvent.VK_F6, 0, true); inputMap.put(keyStroke, KeyEvent.VK_F6); KeyStroke keyStroke7 = KeyStroke.getKeyStroke(KeyEvent.VK_F7, 0, true); inputMap.put(keyStroke7, KeyEvent.VK_F7); KeyStroke keyStroke8 = KeyStroke.getKeyStroke(KeyEvent.VK_F8, 0, true); inputMap.put(keyStroke8, KeyEvent.VK_F8); lookupContent.getComponent().addMouseListener(new OKMouseListener()); this.pack(); isInit = true; } if (!isInit) { if (basicDataDefine == null) { throw new BasicDataException("没有找到基础数据定义:" + entityName); } if (lookupContent instanceof TreeBasicDataLookupPane) { TreeBasicDataLookupPane treePane = (TreeBasicDataLookupPane) lookupContent; treePane.init((TreeBasicDataDefine) basicDataDefine, propsMap, this.getCustomizerFilter(), this.multiSelected, this.condition, dgInSelection, rootCodes); } else if (lookupContent instanceof ListBasicDataLookupPane) { ListBasicDataLookupPane listPane = (ListBasicDataLookupPane) lookupContent; listPane.init(basicDataDefine, propsMap, getCustomizerFilter(), multiSelected, this.codeTextField, this.nameTextField, tableConfig); } } isInit = true; } try { Thread.currentThread().sleep(100); } catch (InterruptedException ex) { Logger.getLogger(BasicDataLookupDialog.class.getName()).log(Level.SEVERE, null, ex); } lookupContent.locate(selectedValue); Toolkit kit = Toolkit.getDefaultToolkit(); // 定义工具包 Dimension screenSize = kit.getScreenSize(); // 获取屏幕的尺寸 int screenWidth = screenSize.width / 2; // 获取屏幕的宽 int screenHeight = screenSize.height / 2; // 获取屏幕的高 int height = this.getHeight(); int width = this.getWidth(); setLocation(screenWidth - width / 2, screenHeight - height / 2); } class OKMouseListener extends MouseAdapter { @Override public void mouseClicked(MouseEvent e) { System.out.println("mouse event : " + e.getClickCount()); if (e.getClickCount() > 1) { ok(); } } } private void parseParams(String params) { int location = params.indexOf("{"); entityName = params.substring(0, location); String others = params.substring(location); others = others.substring(1, others.lastIndexOf("}")); String[] arrays = others.split(","); basicDataDefine = BasicDataUtils.getBasicDataDefine(entityName); for (int i = 0; i < arrays.length; i++) { propsMap.put(arrays[i].substring(0, arrays[i].indexOf(":")).trim(), arrays[i].substring(arrays[i].indexOf(":") + 1).trim()); } } public Map getPropsMap() { return propsMap; } public static class QueryCondition { private String code; private String name; public QueryCondition() { } public QueryCondition(String code, String name) { this.code = code; this.name = name; } public String getCode() { return code; } public void setCode(String code) { this.code = code; } public String getName() { return name; } public void setName(String name) { this.name = name; } } // Variables declaration - do not modify private javax.swing.JPanel buttonPanel; private javax.swing.JButton cancelButton; private javax.swing.JTextField codeTextField; private javax.swing.JPanel contentPane; private javax.swing.JLabel jLabel1; private javax.swing.JLabel jLabel2; private javax.swing.JTextField nameTextField; private javax.swing.JButton okButton; private javax.swing.JButton queryButton; private javax.swing.JPanel queryPanel; private javax.swing.JButton resetButton; // End of variables declaration } |