RCP开发,有关视图关闭的问题怎么让Word里的视图整体变小视图关闭后,它

1842人阅读
JAVA(40)
EclipseRCP/SWT/JFace(65)
&&&&&&& 今天在中国Eclipse社区中看到有人问RCP中如何捕获视图关闭事件,由于在项目中客户也没这方面的需求,所以也没去研究过,今天看到,就试着自己搞了一下,刚开始的时候试着去重写dispose()方法,可是不管怎么样,一点视图上的X,视图就关闭了!后来看了看trukey的回复,让视图实现ISaveablePart2接口,然后实现里面的相关方法就可以搞定了!
&&&&public&int&promptToSaveOnClose()&...{&&&&&&&&//&TODO&Auto-generated&method&stub&&&&&&&&if(true)...{&&&&&&&&&&&&MessageDialog.openInformation(null,&&提示&,&&您不能关闭次视图!&);&&&&&&&&&&&&return&2;&&&&&&&&}else...{&&&&&&&&&&&&return&0;&&&&&&&&}&&&&}&&&&public&void&doSave(IProgressMonitor&monitor)&...{&&&&&&&&//&TODO&Auto-generated&method&stub&&&&&&&&&&&&}&&&&public&void&doSaveAs()&...{&&&&&&&&//&TODO&Auto-generated&method&stub&&&&&&&&&&&&}&&&&&&&&public&boolean&isDirty()&...{&&&&&&&&//&TODO&Auto-generated&method&stub&&&&&&&&return&true;&&&&}&&&&public&boolean&isSaveAsAllowed()&...{&&&&&&&&//&TODO&Auto-generated&method&stub&&&&&&&&return&false;&&&&}&&&&public&boolean&isSaveOnCloseNeeded()&...{&&&&&&&&//&TODO&Auto-generated&method&stub&&&&&&&&return&true;&&&&}
其中isDirty() 和isSaveOnCloseNeeded() 这两个方法一定要返回true。具体的可以去看看ISaveablePart2和ISaveablePart两个接口的源码。
&&相关文章推荐
* 以上用户言论只代表其个人观点,不代表CSDN网站的观点或立场
访问:125112次
积分:1710
积分:1710
排名:千里之外
原创:34篇
转载:44篇
评论:42条
(3)(16)(11)(34)(10)(4)Eclipse+RCP应用系统开发_甜梦文库
Eclipse+RCP应用系统开发
Eclipse RCP 应用系统开发经济管理学院 信息管理教研室 陈冈 Eclipse RCP应用系统开发领先的、高水 准的开发技术, 尽在Eclipse RCP! Eclipse RCP应用系统开发有一种声音如是说!北大青鸟 APTECH J2EE 高级讲师邬继成: 结合 2006 年 11 月底去西安招聘的经历, 我发现许多学校并没有开设 Java、.Net 的课 程,而是以 C/C++ 居多。我不是说 C/C++ 不 重要,但也不能忽视一个事实:Java 和 .Net 相关的职位,比 C/C++ 的职位要多得多。是 不是人才,市场说了算。例如我们公司,主要 是 J2EE 技术为主,但这次招的人中,基本上 没有人会用 Java。不可否认,很多公司期望毕 业生“一来就能干活”,更多不会 JAVA 的毕 业生被拒之门外。 Eclipse RCP应用系统开发 大学教育里,除了素质教育外,如何进行有针 对性的“谋生技能教育”,是一个很现实的问题。 当然,咱们的毕业生同学们,不可能等到大学教育 改革完成再就业。 其实,大多数公司做的事,都不是造神六,没 有那么复杂的科学原理和技术。即使是神六这样的 尖端科技,也是要讲究简单的。霍金在《时间简史》 中说:“插入任何一个数学公式都会使作品的销量 减半。”诺贝尔们如是说,咱们 IT 的从业者,又凭 什么说不是呢?其实,许多当前流行的技术,从 “应用”的角度来看,都是很简单的,甚至可以称 之为“快餐技术”。初学者不需要知道太多底层的 原理――至少现在不需要。他们关心的是:如何尽 快学会使用一种技术,并找到一份工作。 Eclipse RCP应用系统开发引言之1:信息技术发展之语言、IDE篇掌握一些编程语言可让您在职场竞争中收 放自如,而扎实的技巧将会让您炙手可热。1 开发语言 1.1问天下几多英雄?PHP基本描述:一种开源,工作在服务器端,跨平台, 使用HTML脚本的语言,因为可置入HTML页面,因此尤 其适用于网页制作。 学习理由:使用十分广泛。借助缓存高速调用脚本, 并使用编译代码插件来增强效果是今后趋势所在。使用 C或COBOL创建Web应用程序是不可行的。 相关工作指数:1152 Eclipse RCP应用系统开发? JavaScript基本描述:请不要与Java混淆, JavaScript是一种面对对象的脚本变成语言, 它运行在客户端的Web浏览器上。它比Java更 简洁,拥有简化的命令,易用的代码,并且无 需进行编译。 使用理由:它可置入HTML,被用于大量的 网页来验证表格,建立cookie,侦测浏览器 以及提高设计。由于其易于学习与使用广泛, 已被视为重要的学习背景。 相关工作指数:4406 Eclipse RCP应用系统开发? Pascal基本描述:原本是世界上流行的一 种适合于教学的语言。培养编程思想和 思路。 使用理由:Borland公司的Delphi开 发平台的语言。由于其易于学习,还有 Delphi的广泛使用,已被视为重要的学 习语言。 相关工作指数:5406 Eclipse RCP应用系统开发?Perl 相关描述:Perl是一种开源跨平台、 运行在服务器端的解释语言,在CGI程序 中被大量用于处理文字。 学习理由:Perl在处理大量文字方 面的能力使得其非常流行,且广泛用于写 入多任务的网络服务器程序。Duquaine 说:“如果您正在从事网络应用程序的工 作,那么学习某种脚本语言(如Perl或 PHP)是十分有必要的。” 相关工作指数:4810 Eclipse RCP应用系统开发?C 基本描述:一种标准化的通用编程语言, 它是最普及的语言之一,也是多种其它语言 (如C++)的基础。 学习理由:Duquaine说:“学习C是相当 重要的。在学习了C后,跳跃到Java或C#就变 得十分容易,因为许多语法是通用的。另外, 许多C语言的语法也被用于脚本语言。” 相关工作指数:6164(包括所有衍生工 作) Eclipse RCP应用系统开发?Python基本描述:一种动态面对对象的 翻译开源语言。使用动态存储管理。 学习理由:Python是一种高度 可读的抽象语言,许多开发人员认为 其非常有趣,它的语法简单,因此被 Google与学术界大量运用。 相关工作指数:811 Eclipse RCP应用系统开发? VB.Net(Visual Basic .Net)基本描述:一种面向对象的语言, 在微软.Net框架中使用。 学习理由:最具争议的是 VB.Net目前是否为最流行的且是几 种必须掌握的语言之一。Huckaby说: “VB.Net目前是被广泛优先采用语 言之一的。” 相关工作指数:6506 Eclipse RCP应用系统开发?新生代迭起,群雄逐鹿,天下纷争(同步 JavaScript 与 XML) 基本描述:虽然从技术上来说,这并非一种编程语 言,但是AJAX使用XHTML或HTML,JavaScript以及 XML来建立互动网络应用程序。 学习理由:自从Google企图将AJAX应用到地图上, 对AJAX知识的需求不断膨胀。圣地亚哥的软件工程公司 Interknowlogycom的CEO Huckaby说:“对AJAX知识需 求相当大,因为它很难掌握。”微软最近声称将发布一 个名为Atlas的工具来帮助AJAX更容易被实施。 Huckaby说:“如果微软的Atlas工具获得成功,它将 会给普通工作者带来极大的复杂性和困扰。” 相关工作指数:1106?AJAX Eclipse RCP应用系统开发? Rubyand Ruby on Rails 基本描述:Ruby是一种动态的面向 对象的开源语言。Rails上的Ruby则是 一种使用Ruby编写的开源网络程序框架, 该框架与MVC(模型-查看-控制)结构 十分类似。 学习理由:由于简便性,有效性以及 让电脑完成任务的能力,近年来,该语言 的使用量已经迅速增长。另外的好处是非 常容易学习。 相关工作指数:2105 Eclipse RCP应用系统开发? Java基本描述:一种面向对象的变成语言, 由James Gosling和其Sun Microsystems的同事共同开发。 学习理由:被许多开发人员所拥戴, 被成为“美丽的”语言。它适用于没 有.net编程经验的人员。Duquaine说: “如果您不是微软产品的使用者,那么学 习Java必不可少。” 相关工作指数:14408 Eclipse RCP应用系统开发? C#基本描述:一种通用编辑,面向对象 的编程语言,由微软作为其.net计划的 一部分开发而成,包含C和C++。 学习理由:是.Net框架的基础部分。 Duquaine说:“如果您大量使用 Microsoft的产品,那么学习C#是十分 有必要的。” 相关工作指数:5111 Eclipse RCP应用系统开发1.2基于成本、学习性、健壮性选择 1.3留给我们的思考?人不可能两次踏进同一条河流。?理论是灰色的,现实是彩色的。 ?翻车的往往是跑得快的。 Eclipse RCP应用系统开发引言之2:DE概述一、浪花淘尽英雄1.Visual Basic 夕阳无限好,只是近黄昏! 2.Delphi 没落的奇迹!3.PowerBuilder 廉颇老矣,尚能饭否? 4. Visual C++ 经典还能延续多久? Eclipse RCP应用系统开发5. JBuilder 变革迫在眉睫?! 二、想说爱你不容易 传统IDE开发工具:PB、VB、Delphi、VC等。 ? 高度集成的环境 ? 难以实现模块化设计 ? 难以动态化构建系统 ? 模块的组织繁杂 ? 模块难以复用和扩展 ? 系统复杂度高 Eclipse RCP应用系统开发三、长江后浪推前浪1. Visual Studio 在竞争中催生? 2. Developer Workbench 别具一格?另类? 3. NetBeans 与Eclipse难分伯仲? 4. Eclipse 一统江湖任我行? 5. JDeveloper 挑战Eclipse? Eclipse RCP应用系统开发引言之3:新面孔、新特色新IDE特点: ? 以先进架构为基础 ? 支持混合开发 ? 容易集成第三方工具 ? 易用、扩展性强 ? 广泛支持 Eclipse RCP应用系统开发参考书目1.Addison.Wesley.Eclipse.Rich.Clien t.Platform.Designing.Coding.and.P ackaging.Java.Applications.Oct.20 05 2.Addison.Wesley.Eclipse.Building.C ommercial.Quality.Plug.ins.2nd.Edi tion.Mar.2006 Eclipse RCP应用系统开发 3.陈冈. Eclispe RCP应用系统开发方法与实战. 电子工业 出版社. 互动出版网:http://www. Eclipse RCP应用系统开发第1章 什么是Eclispe RCP?1.1Eclipse简介 目前Eclipse受到空前关注,国内外许多软件公 司纷纷开始采用Eclipse作为开发平台。那么,什么 是Eclipse? Eclipse能给我们带来什么? 1.1.1 Eclipse的起源和发展? ??Eclipse的前身是IBM的Visual Age。 1998年11月IBM成立了一个项目开发小组,开始开发一个开 发工具,2000年新一代开发工具诞生,这就是大家所熟悉的 Eclipse。 IBM 于2001年12月向世界宣布了两件事:第一件事是捐赠 价值4千万美元的Eclipse源码给开源社区;另外一件事是成 立由成员公司组成的 Eclipse 协会(Eclipse Consortium) Eclipse RCP应用系统开发Eclipse受到广泛关注,蜂拥而至的用户使 得其下载服务器一度阻塞,给业界带来了久 违的震撼! IBM趁热打铁,在EclipseCon 2004上宣布 成立一个独立的非盈利性的基金会,由该基 金会负责管理和指导Eclipse开发,目前其成 员多达近百家知名公司,其中包括Borland、 Rational Software、Red Hat、Sybase、 Google和Oracle等业界巨头。Eclipse目前成 熟稳定的版本是3.3,正在开发的版本是3.4, 现在已经成为业内主要的非微软软件工具平 台。 Eclipse RCP应用系统开发1.1.2 Eclipse的优势? ? ? ?? ?目 前 全 球 有 上 百 万 人 在 使 用 Eclipse 进 行 开 发 。 为 什 么 Eclipse拥有如此众多的拥趸?这与Eclipse集众多特性于一身有 很大关系。 Eclipse 是开放源代码的软件。 Eclipse是真正地可扩展并可配置的。 Eclipse支持众多的开发 语言而不仅仅是Java。 Eclipse提供了对多重平台特性的支持。 基 于 业 界 领 先 的 OSGi 规 范 。 OSGi 规 范 最 早 由 Sun Microsystems、IBM、爱立信等于1999年推出,其服务平台包 括:服务网关、汽车、移动电话、工业自动化、建筑物自动化、 PDA网格计算、娱乐(如iPronto)和 IDE等。 Eclipse美轮美奂的人机界面受到广泛赞誉。 Eclipse由业界领先者推出,具有强大的行业力量。 Eclipse RCP应用系统开发1.2 Eclipse RCP1.2.1 Eclipse RCP平台 RCP是基于Eclipse项目的一个开发富客户端应用 的框架,目的在于为开发人员提供一种功能强大的、 快速的、可扩展的应用平台。 1.2.2 什么是RCP RCP是Rich Client Platform的缩写。Rich Client 大概在20世纪90年代初期开始使用,其经典的开发 工具有Visual Basic和Delphi。类似于VB、Delphi这 样的可视化开发环境使得开发富客户端程序变得简单 而有趣味,相信这是很多人的体会。但是,狼来了! Eclipse RCP应用系统开发1.2.3 Eclipse RCP的优势Eclipse RCP具有以下优点: ? 组件化。 ? 便利性。RCP可以在嵌入式设备、掌上电脑上运行。 Eclipse也可以说是“RCP everywhere”。 ? 智能安装和升级。可以通过HTTP、Web站点、复 制等多种方式进行在线安装和更新。 ? 可扩展性。 ? 本地观感及使用体验。 ? 连线与脱线操作。Eclipse RCP横空出世,有望扭转Java在桌面 应用的颓势,而不仅仅是4千万美元的问题! Eclipse RCP应用系统开发1.2.4 Eclipse RCP的应用国外已经有大量应用Eclipse RCP开发的项目,比 较著名有: ? 美国国家航空航天管理局(NASA)的火星探测计划项 目。 ? 新版的IBM Workplace开发平台。 ? 新版的JBuilder。 ? 新版的Flash9。 ? 宝马轿车的控制系统。 国内RCP应用也逐渐发展和壮大起来,越来越多 的项目开始采用Eclipse RCP开发,如电信、金融、医 药、电力系统等行业已经开始应用Eclipse RCP开发的 桌面系统了。可以预见,Eclipse RCP具有非常广阔的 发展前景。 Eclipse RCP应用系统开发 国外一个开源的Eclipse RCP软件。该软件是一 个在线股票交易系统,能够进行股价的实时查看、 历史数据浏览、数据分析等功能。 Eclipse RCP应用系统开发 国外一个商业Eclipse RCP软件。该软件主要应用于医 学领域,帮助小儿科医生进行日常工作的更新管理。 Eclipse RCP应用系统开发本课程将要实现的一个系统 本课程主要内容Eclipse RCP应用系统开发?实现示例系统基本框架。 ?配置Eclipse RCP环境。 ?SWT/Jface简介 ?Hibernate数据持久化 ?用户登录 ?系统托盘处理。 ?气泡式提示文本。 ?自定制安装程序。 更多精彩内容,敬请关注电子工业出版社 《Eclipse RCP应用系统开发方法与实战》一书! Eclipse RCP应用系统开发本课程主要涉及的软件1。JDK1.5.0。 2。Eclipse 3.2.1。 3。Derby10.2数据库。 4。 SQLExplorer2.2。 5。NSIS2.24。 6。Hibernate3.2 。 全部为免费软件! Eclipse RCP应用系统开发第 2章 安装与配置开发环境2.1 安装JDK最新版本为JDK6。考虑到普遍性,这里使用JDK5。其 下载地址为:/javase/downloads/index_jdk5.jsp Eclipse RCP应用系统开发2.2 Eclipse的下载安装 可以到Eclipse官方网站下载:http://www.eclipse.org/。 也可以直接在浏览器地址栏输入: http://download.eclipse.org/eclipse/downloads查看全部 Eclipse版本。 Eclipse RCP应用系统开发2.3 配置本地Apache Derby数据库引擎 2.3.1 Apache Derby简介1997年美国Cloudscape公司推出了Cloudscape。 ? 1999年Informix收购了Cloudscape公司。 ? 2001年,Informix又被IBM收购,IBM将Cloudscape 作为其多达70多种产品中内嵌的数据库引擎。 ? 2004 年 , IBM 将 Cloudscape 数 据 库 软 件 捐 赠 给 Apache基金会。?随着Sun公司的加入,以及IBM的强大投入,这进 一步强化了Apache Derby数据库的光明前景。 Eclipse RCP应用系统开发2.3.2 Apache Derby的特色?占用内存少、多用户、标准驱动的关系数据库系统。 ?基于商业数据库内核。 ?零管理。 ?可嵌入也可独立。 ?容易学习使用。 Eclipse RCP应用系统开发2.3.3 Apache Derby的安装配置 1.Apache Derby的下载 下载地址为http://db.apache.org/derby。其最新版本为10.2。 Eclipse RCP应用系统开发如果作为单独的数据库服务器使用,需要下载db-derby-10.2.1.6-bin.zip。 若需要在Eclipse里面与Derby打交道,则需要下载 derby_core_plugin_10.2.1.452058.zip和derby_ui_plugin_1.1.0.zip。 Eclipse RCP应用系统开发2.Apache Derby的配置 ? 创建文件夹c:\eclipse_plugins(文件夹名任 意),创建子文件夹derby_plugin\eclipse。 ? 将derby_core_plugin_10.2.1.452058.zip解压 后得到的plugins文件夹拷贝到 derby_plugin\eclipse里面。 ? 将derby_ui_plugin_1.1.0.zip解压后得到的 plugins文件夹下面的全部内容拷贝到 derby_plugin\eclipse\plugins下面。 Eclipse RCP应用系统开发? 在Eclipse安装目录下创建一个文件夹links,在该文件夹中创建一个纯文本文件 derby_plugin.link(文件名任意),用记事本 打开,输入内容: path=c:\\eclipse_plugins\\derby_plugin Eclipse RCP应用系统开发 Eclipse RCP应用系统开发3. 创建数据库使用命令行工具ij,输入connect 'jdbc:derby://localhost:1527/testDB;create=true';注意不要忘了最后的分号。 上述命令将创建数据库testDB。 Eclipse RCP应用系统开发2.4 使用SQL Explorer插件1.SQL Explorer简介 在开源社区中,SQL Explorer插件享有很 高的知名度,使用者很多。 SQL Explorer官方下载网站为: http://eclipsesql.sourceforge.net/, 目前最新版本3.0只能在Eclipse3.2以后版 本中使用。 Eclipse RCP应用系统开发 Eclipse RCP应用系统开发2.SQL Explorer的安装 ? 在c:\eclipse_plugins下创建文件夹 SQLExplorer\eclipse 解压下载得到的 sqlexplorer_plugin_3.0.0..zip文件,将解压 后得到的sqlexplorer_plugin_3.0.0.文件夹下 面的features和plugins文件夹拷贝到 c:\eclipse_plugins\SQLExplorer\eclipse下面。 ? 然后在c:\eclipse\links文件夹下面新建文本文件 SQLExplorer.link,输入 path=c:\\eclipse_plugins\\SQLExplorer即可。? Eclipse RCP应用系统开发 3.创建数据库连接 ? 加入JDBC驱动程序。选择Eclipse菜单【Window】 →【Preferences…】,弹出“Preferences”对话框。 展开“SQL Explorer”,选择“JDBC Drivers”。 Eclipse RCP应用系统开发? 配置JDBC驱动信息。单击【Add】按钮,弹出“Create New Driver”对话框。在Name文本 框中输入“Apache Derby”,在Example URL 文本框中输入 “jdbc:derby://localhost:1527/&databaseNam e&”,Driver Class Name下拉列表框中输入 “org.apache.derby.jdbc.ClientDriver”。单 击“Extra Class Path”页框,再单击【Add】 按钮,依次添加derby.jar、derbyclient.jar和 derbynet.jar这三个文件。 ? 新建连接即可。 Eclipse RCP应用系统开发4. 创建Users数据表CREATE TABLE USERS ( ID INT GENERATED ALWAYS AS IDENTITY (START WITH 1, INCREMENT BY 1), USERNAME VARCHAR(8) NOT NULL, PASSWORD VARCHAR(8) NOT NULL, USERTAG CHAR(1) WITH DEFAULT '0', LATESTLOGTIME TIMESTAMP WITH DEFAULT CURRENT_TIMESTAMP, PRIMARY KEY(ID) ); Eclipse RCP应用系统开发第 3章 构造系统主程序? 创建RCP项目。? 定制开发平台和目标平台。? 定制窗口属性。 ? 添加菜单和工具栏。 ? 实现主界面透视图、视图。 ? 实现系统托盘。 ? 定时自动显示托盘气泡提示文本。 ? 品牌化应用程序。 Eclipse RCP应用系统开发 3.1 新建RCP项目 3.1.1 创建经费测算项目 Eclipse RCP应用系统开发3.1.2 项目的组织结构 Eclipse RCP应用系统开发1. src src文件夹存放了项目的源程序,那么编译后的class文件在哪儿?项目组 织结构中并没有列出,实际保存在bin文件夹下。 2. JRE System Library 该文件夹存放系统类库文件。 3. Plug-in Dependences 该文件夹存放插件依赖类库文件。可以展开看看,当前项目需要哪 些插件才能正常运行。 4. MANIFEST.MF MANIFEST.MF文件对当前插件(项目)进行描述,并可定义与其他 插件的关系,也就是插件的元数据。该文件一般不需要修改。 5. build.properties build.properties用来配置插件的编译信息,即定义与项目打包时(构建)相 关的属性定义。 6. plugin.xml 定义插件的扩展点(Extension point)。 Eclipse RCP应用系统开发3.1.3 RCP基本框架一个基本的RCP应用程序已经搭建起来,探究一下RCP的基本 框架对于理解RCP大有好处。从前面可以看出,Eclipse已经 自 动 生 成 了 Application.java 、 ApplicationActionBarAdvisor.java 、 ApplicationWorkbenchAdvisor.java 、 ApplicationWorkbenchWindowAdvisor.java 、 Perspective.java这5个类文件。有必要对这5个文件进行分析, 以便更深刻地理解RCP的基本框架。在分析之前,先来简单 理解一下几个基本概念。 1. 基本概念 1) Display应用程序一般只需要一个Display对象,该对象实际上代表了底层图形系统 的实现。应用程序主窗口打开之后,才可以通过一个被称作Shell的对象 获得。Display对象的获得方法: Display display = new Display(); 或者:Display display=Display.getCurrent();。 Eclipse RCP应用系统开发2) Shell 每一个窗口都有一个Shell对象。Shell对象代表了 与用户交互的窗口框架,并处理与窗口关联的 诸如移动、改变大小等常见行为。Shell对象的 获得方法: Display display=Display.getCurrent(); Shell shell = new Shell(display); 或 者 : Shell shell=Display.getCurrent().getActiveShell(); Eclipse RCP应用系统开发3) Workbench Workbench是工作台,通俗地说就是代表用户 界面的UI元素。工作台上有各种窗口、图标、 按钮和控件。获得工作台对象的方法: IWorkbench wb=PlatformUI.getWorkbench(); 工作台对象有两个方法也许有用: wb.restart()。关闭应用程序并立即重新启动。 wb.close()。正常关闭应用程序。 Eclipse RCP应用系统开发4) Advisor Advisor是建议者。Eclipse提供了3种类型的 Advisor: WorkbenchAdvisor。应用程序级别,Eclipse3.0开 始引入的全新类。每一个应用程序只有一个 Workbench,WorkbenchAdvisor 负责该工作台生命 周期的管理,例如启动、关闭工作。 WorkbenchWindowAdvisor。窗口级别。每一个窗 口都有一个WorkbenchWindowAdvisor 实例。 WorkbenchWindowAdvisor 负责具体窗口生命周期的 管理。 ActionBarAdvisor。窗口级别。每一个窗口都有一 个ActionBarAdvisor实例。 ActionBarAdvisor负责管 理窗口的菜单栏、状态栏、工具栏的外观和行为。 Eclipse RCP应用系统开发5)View和Editor 在Eclipse RCP应用程序中,用户主要 是通过视图(View)和编辑器(Editor) 与程序交互。 Eclipse RCP应用系统开发6) Perspective Perspective 透视图, RCP应用程 序是通过透视图对窗口内容进行安排 和布局的,应用程序都有一个默认的 透视图,。 默认情况下,初始布局包含了一个 可视的编辑区。当然,该编辑区也可 以关闭。 Eclipse RCP应用系统开发2. 类文件分析 1) Application.java Application是RCP应用程序的入口。Application主要代码如下: Application.java import … public class Application implements IPlatformRunnable { public Object run(Object args) throws Exception { Display display = PlatformUI.createDisplay(); try { int returnCode = PlatformUI.createAndRunWorkbench(display, new ApplicationWorkbenchAdvisor()); if (returnCode == PlatformUI.RETURN_RESTART) { return IPlatformRunnable.EXIT_RESTART; } return IPlatformRunnable.EXIT_OK; } finally { display.dispose(); } }} Eclipse RCP应用系统开发2) ApplicationWorkbenchAdvisor.java ApplicationWorkbenchAdvisor类负责应用 程序生命周期管理。开发人员可以在该类中 实现程序启动或者关闭时的某种处理。该类 的具体实现只是给用户一个初始的视图界面 而已,还需要配合WorkbenchWindowAdvisor、 ActionBarAdvisor才能构成一个较为完整的用 户界面。 Eclipse RCP应用系统开发cn.edu.jfcs.app/ ApplicationWorkbenchAdvisor.java import … public class ApplicationWorkbenchAdvisor extends WorkbenchAdvisor { private static final String PERSPECTIVE_ID = &cn.edu.jfcs.perspective&; public WorkbenchWindowAdvisor createWorkbenchWindowAdvisor(IWorkbenchWindowConfigurer configurer) { return new ApplicationWorkbenchWindowAdvisor(configurer); } public void initialize(IWorkbenchConfigurer configurer) { super.initialize(configurer); configurer.setSaveAndRestore(true); } public String getInitialWindowPerspectiveId() { return PERSPECTIVE_ID; } } Eclipse RCP应用系统开发3) ApplicationWorkbenchWindowAdvisor.java ApplicationWorkbenchWindowAdvisor类负责 应用程序窗口生命周期的管理。 每一个应用程序都需要一个 WorkbenchWindowAdvisor来控制窗口界面的UI 元素。开发人员可以控制窗口创建时的大小、标 题、位置等等,也可以添加创建、打开、还原或 关闭工作台窗口时调用的方法 Eclipse RCP应用系统开发cn.edu.jfcs.app/ ApplicationWorkbenchWindowAdvisor.java import … public class ApplicationWorkbenchWindowAdvisor extends WorkbenchWindowAdvisor { public ApplicationWorkbenchWindowAdvisor(IWorkbenchWindowConfigurer configurer) { super(configurer); } public ActionBarAdvisor createActionBarAdvisor(IActionBarConfigurer configurer) { return new ApplicationActionBarAdvisor(configurer); } public void preWindowOpen() { IWorkbenchWindowConfigurer configurer = getWindowConfigurer(); configurer.setInitialSize(new Point(700, 550)); configurer.setShowCoolBar(false); configurer.setShowStatusLine(false); configurer.setTitle(&jfcs&); }} Eclipse RCP应用系统开发4) ApplicationActionBarAdvisor.java ApplicationActionBarAdvisor.java类 负责定义窗口的行为,该类扩展自 ActionBarAdvisor。具体的说,该类用于构建菜 单栏、工具栏和状态行。ActionBarAdvisor自然 是负责菜单栏、工具栏和状态行的创建和注册。 Eclipse RCP应用系统开发cn.edu.jfcs.app/ ApplicationActionBarAdvisor.java import … public class ApplicationActionBarAdvisor extends ActionBarAdvisor { private IWorkbenchAction introA public ApplicationActionBarAdvisor(IActionBarConfigurer configurer) { super(configurer); } protected void makeActions(IWorkbenchWindow window) { introAction = ActionFactory.INTRO.create(window); register(introAction); } protected void fillMenuBar(IMenuManager menuBar) { MenuManager helpMenu = new MenuManager(&&Help&, IWorkbenchActionConstants.M_HELP); menuBar.add(helpMenu); helpMenu.add(introAction); } } Eclipse RCP应用系统开发 5) Perspective.java Perspective类主要负责界面布局的安排。Perspective.java 代码如下: cn.edu.jfcs.app/ Perspective.java import … public class Perspective implements IPerspectiveFactory { public void createInitialLayout(IPageLayout layout) { String editorArea = layout.getEditorArea(); layout.setEditorAreaVisible(false); layout.setFixed(true); // 以后加入各种视图 } } Eclipse RCP应用系统开发3.1.4 定制应用程序窗口属性1. 闪屏画面 应用程序主界面显示之前往往可能要做一些 初始化处理工作,也就是启动时间可能稍微长 一些,如果没有任何提示,用户可能感到困惑, 闪屏画面能够较好地解决这个问题。准备一幅 24bit色BMP格式的图片,图片大小不要超过 500x300。将自己的图片拷贝到项目下面替换掉 原来的splash.bmp即可。 Eclipse RCP应用系统开发2. 不保存窗口状态 首 先 , 将 ApplicationWorkbenchAdvisor.java 的 initialize()方法中: configurer.setSaveAndRestore(true); 修改为:configurer.setSaveAndRestore(false);。 前文说过,设置为true,应用程序须得每次退 出时保存窗口状态,此处并不需要且对性能 有轻微影响,所以设置为false。 Eclipse RCP应用系统开发3. 定制窗口式样 在ApplicationWorkbenchWindowAdvisor.java的preWindowOpen() 方法中定制窗口式样 : public void preWindowOpen() { IWorkbenchWindowConfigurer configurer = getWindowConfigurer(); //窗口设定为800x600 configurer.setInitialSize(new Point(800, 600)); configurer.setShowCoolBar(false); //暂时不显示工具栏 configurer.setShowStatusLine(true); //显示状态栏 //窗口只显示最小化、关闭按钮 configurer.setShellStyle(SWT.MIN | SWT.CLOSE); //设置窗口标题 configurer.setTitle(&高校经费测算系统&); } Eclipse RCP应用系统开发处理自定义常量:新建一个包cn.edu.jfcs.sys,在 该包下新建接口IAppConstants.java,该接口代 码类似于以下形式: package cn.edu.jfcs. public interface IAppConstants { public static final String APPLICATION_TITLE=&高校经费测算系统&; }为什么这样处理? Eclipse RCP应用系统开发4. 窗口自动居中 cn.edu.jfcs.app/ ApplicationWorkbenchWindowAdvisor.javapublic void postWindowOpen() { //设置窗口自动居中 Shell shell = getWindowConfigurer().getWindow().getShell(); Rectangle screenSize = Display.getDefault().getClientArea(); Rectangle frameSize = shell.getBounds(); shell.setLocation((screenSize.width - frameSize.width) / 2,(screenSize.height - frameSize.height) / 2); } Eclipse RCP应用系统开发5. 设置视图标题栏的弧线形外观 打 开 ApplicationWorkbenchAdvisor.java 文 件 , 修 改 initialize()方法代码如下:cn.edu.jfcs.app/ ApplicationWorkbenchAdvisor.javapublic void initialize(IWorkbenchConfigurer configurer) { super.initialize(configurer); configurer.setSaveAndRestore(false);PlatformUI.getPreferenceStore().setValue(IWorkbenchPreferenceCon stants.SHOW_TRADITIONAL_STYLE_TABS, false);} Eclipse RCP应用系统开发3.2 定制开发平台和目标平台 目标平台是应用程序运行的基 础平台,开发平台是开发RCP的 基本环境(IDE)。 Eclipse RCP应用系统开发3.3 添加菜单和工具栏 3.3.1 Action简介 Action就是动作,也就是单击菜单。 方法一: private IWorkbenchAction exitA exitAction = ActionFactory.QUIT.create(window); 方法二:开发者自定义的Action,需要扩展Action类, 例如: import org.eclipse.jface.action.A public class AboutSystem extends Action { public AboutSystem() {…… } public void run() { …… }} Eclipse RCP应用系统开发3.3.2 创建系统Action 首 先 在 项 目 下 创 建 文 件 夹 icons , Eclipse中icons文件夹用于保存项目各 种图片文件,请不要更换文件夹名称。 根据需要创建Action。 那么,图片文件如何处理? Eclipse RCP应用系统开发可以新建一个专门存放图片文件名的接口文件: package cn.edu.jfcs. public interface IImageKey { public static final String ICONSPATH=&icons/&; public static final String WELCOME=ICONSPATH+&welcome.gif&; public static final String ABOUT_SYSTEM=ICONSPATH+&aboutSystem.gif&; public static final String DATA_BAK=ICONSPATH+&dataBak.gif&; } Eclipse RCP应用系统开发3.3.3 创建系统菜单 创建菜单首先需要 makeActions(IWorkbenchWindow)方法创建好相 应的菜单动作,然后由fillMenuBar()方法完成菜 单项的创建。下面是创建菜单的代码: Eclipse RCP应用系统开发public class ApplicationActionBarAdvisor extends ActionBarAdvisor { // 基础数据菜单:公共参数设置、教学单位情况 private Action publicData, teachUnitData,calcDataMenu, graphicsD public ApplicationActionBarAdvisor(IActionBarConfigurer configurer) {super(configurer);} // 生成Action对象 protected void makeActions(IWorkbenchWindow window) { publicData = new PublicData(); register(publicData); teachUnitData = new TeachUnitData(); register(teachUnitData); } // 生成Action对象 protected void fillMenuBar(IMenuManager menuBar) { MenuManager baseDataMenu = new MenuManager(&基础数据[&B]&, &baseDataMenu&); baseDataMenu.add(publicData); baseDataMenu.add(teachUnitData); MenuManager calcDataMenu = new MenuManager(&测算数据[&C]&, &calcDataMenu&); menuBar.add(calcDataMenu); calcDataMenu.add(graphicsData); }} Eclipse RCP应用系统开发3.3.4 创建系统工具栏 工具栏管理器负责工具栏的分类管理,下面是创建工具栏的代码: cn.edu.jfcs.app/ ApplicationActionBarAdvisor.javaprotected void fillCoolBar(ICoolBarManager coolBar) {IToolBarManager toolBar = new ToolBarManager(SWT.FLAT | SWT.SHADOW_OUT);coolBar.add(toolBar); toolBar.add(publicData); toolBar.add(teachUnitData); toolBar.add(new Separator()); toolBar.add(historyData); toolBar.add(graphicsData); …… } Eclipse RCP应用系统开发3.4 添加主界面视图(1) 创建包cn.edu.jfcs.ui; (2) 双击plugin.xml,切换到Extensions 页。单击【Add…】按钮,弹出“New Extension”对话框。选中Extension Points列 表中的org.eclipse.ui.views,单击【Finish】 按钮; Eclipse RCP应用系统开发(3) 在org.eclipse.ui.views上单击鼠标右 键,选择【New】→【View】; (4) 创建教学单位视图。在id后输入 cn.edu.jfcs.ui.teachunitname,name后输入 “教学单位”,class后输入 cn.edu.jfcs.ui.TeachUnitName,icon选择 icons/teachUnitNameView.gif,allowMultiple 选择false(不允许打开该视图的多个实例), 然后保存,如图所示; Eclipse RCP应用系统开发 Eclipse RCP应用系统开发(5) 生成TeachUnitName.java。单 击图中的class链接,弹出“New Java Class”对话框,直接单击【Finish】按钮 即可自动创建 cn.edu.wuse.jfcs.ui.TeachUnitName类 文件。 各视图的ID号如何处理较好? Eclipse RCP应用系统开发3.5 配置透视图修改cn.edu.jfcs.app包的 Perspective.java,完整代码如下:cn.edu.jfcs.app/ Perspective.javapackage cn.edu.jfcs. import org.eclipse.ui.IPageL import org.eclipse.ui.IPerspectiveF import cn.edu.jfcs.sys.IAppC public class Perspective implements IPerspectiveFactory { public void createInitialLayout(IPageLayout layout) { String editorArea = layout.getEditorArea(); layout.setEditorAreaVisible(false); layout.setFixed(true); // 加入教学单位视图 Eclipse RCP应用系统开发layout.addStandaloneView(IAppConstants.TEACH_UNIT_ NAME_VIEW_ID, true, IPageLayout.LEFT, 0.26f, editorArea); layout.getViewLayout(IAppConstants.TEACH_UNIT_NAM E_VIEW_ID).setCloseable(false); layout.getViewLayout(IAppConstants.TEACH_UNIT_NAM E_VIEW_ID).setMoveable(false); // 加入经费概览视图 layout.addStandaloneView(IAppConstants.PIE_DIAGRAM _VIEW_ID, true, IPageLayout.BOTTOM, 0.72f, IAppConstants.TEACH_UNIT_NAME_VIEW_ID); layout.getViewLayout(IAppConstants.PIE_DIAGRAM_VIE W_ID).setCloseable(false); layout.getViewLayout(IAppConstants.PIE_DIAGRAM_VIE W_ID).setMoveable(false); Eclipse RCP应用系统开发 // 加入教学单位课程明细视图 layout.addView(IAppConstants.TEACH_UNIT_CL ASS_VIEW_ID, IPageLayout.RIGHT,0.74f, editorArea); layout.getViewLayout(IAppConstants.TEACH_UNI T_CLASS_VIEW_ID).setCloseable(false); layout.getViewLayout(IAppConstants.TEACH_UNI T_CLASS_VIEW_ID).setMoveable(false); }} Eclipse RCP应用系统开发3.6 实现系统托盘将程序最小化到Windows托盘,是一项有 趣而且实用的工作。程序启动后自动最小化 到Windows托盘,如图5-15所示。即使用户 关闭程序,用户也可以随时通过托盘打开程 序,非常方便。 Eclipse RCP应用系统开发3.6.1 托盘对象简介 实现程序托盘首先需要获得Windows托盘对象, 托盘对象可以通过Display对象的getSystemTray() 方法取得,其代码如下:Tray tray = window.getShell().getDisplay().getSystemTray();注意:托盘对象的创建应该是在能够获得Display 对象之后而程序窗口又没有打开之前,即 ApplicationWorkbenchWindowAdvisor 的 postWindowOpen()方法中。 Eclipse RCP应用系统开发然后,向托盘对象中添加托盘项目 TrayItem,并设置托盘项目的文字、图标。托 盘项目及其图标应该在程序退出时销毁以释 放资源。托盘项目创建方法如下: TrayItem trayItem = new TrayItem(tray, SWT.NONE); trayItem.setImage(trayImage); trayItem.setToolTipText(&文字说明&); Eclipse RCP应用系统开发最后,需要添加托盘项目的事件监听处 理,主要有两种:一种是用户单击托盘图标 时需要打开程序,其监听事件为:trayItem.addListener(SWT.Selection, new Listener() { public void handleEvent(Event event) { //恢复程序界面 } }); Eclipse RCP应用系统开发另外一种是用户右键单击托盘图标时需要弹出菜 单,其监听事件为:trayItem.addListener(SWT.MenuDetect, new Listener() { public void handleEvent(Event event) {//处理代码} });最后还有一个问题,当用户关闭程序时不能 关闭托盘图标。这需要覆写 ApplicationWorkbenchWindowAdvisor的 preWindowShellClose()方法。 Eclipse RCP应用系统开发3.6.2 系统托盘的具体实现(1) 创建管理托盘的类HookSysTray cn.edu.jfcs.sys / HookSysTray.java import … public class HookSysTray { private TrayItem trayI private Image trayI public HookSysTray() {} public void createSysTray(final IWorkbenchWindow window) { trayItem = initTrayItem(window); if (trayItem != null) { trayPopupMenu(window); trayMinimize(window); } } Eclipse RCP应用系统开发//最小化程序窗口 public void windowMinimized(final Shell shell) { shell.setMinimized(true); shell.setVisible(false); } // 最小化程序到托盘 private void trayMinimize(final IWorkbenchWindow window) { window.getShell().addShellListener(new ShellAdapter() { public void shellIconified(ShellEvent e) { window.getShell().setVisible(false); } }); trayItem.addListener(SWT.Selection, new Listener() { public void handleEvent(Event event) { Shell shell = window.getShell(); if (!shell.isVisible()) { shell.setVisible(true); window.getShell().setMinimized(false); } } }); } Eclipse RCP应用系统开发// 托盘弹出菜单 private void trayPopupMenu(final IWorkbenchWindow window) { trayItem.addListener(SWT.MenuDetect, new Listener() { public void handleEvent(Event event) { MenuManager trayMenu = new MenuManager(); Menu menu trayMenu.createContextMenu(window.getShell()); fillTrayItem(trayMenu, window); menu.setVisible(true); } }); }= Eclipse RCP应用系统开发// 构造托盘菜单项 private void fillTrayItem(IMenuManager trayItem, final IWorkbenchWindow window) { Action exitSystem = new Action(&退出系统[&E]&, AbstractUIPlugin.imageDescriptorFromPlugin(IAppConstants.APPLICATION_ID, IImageKey.EXIT_SYSTEM)) { public void run() { PlatformUI.getWorkbench().close(); } }; trayItem.add(new Logoff()); trayItem.add(exitSystem);} Eclipse RCP应用系统开发// 初始化托盘项目的文字和图标 private TrayItem initTrayItem(IWorkbenchWindow window) { final Tray tray = window.getShell().getDisplay().getSystemTray(); if (tray == null) trayItem = new TrayItem(tray, SWT.NONE); trayImage = AbstractUIPlugin.imageDescriptorFromPlugin( IAppConstants.APPLICATION_ID, IImageKey .WINDOW_IMAGE) .createImage(); trayItem.setImage(trayImage); return trayI } public void Dispose() { if (trayItem != null) trayItem.dispose(); if (trayImage != null) trayImage.dispose(); }} Eclipse RCP应用系统开发(2) 修改ApplicationWorkbenchWindowAdvisor类 ? 首先定义一个HookSysTray 对象: private HookSysTray hookSysT ? 添加用于创建hookSysTray对象的createSystemTray()方法: private void createSystemTray() { hookSysTray = new HookSysTray();hookSysTray.createSysTray(getWindowConfigurer().getWindo w()); } Eclipse RCP应用系统开发??修改postWindowOpen()方法,在该方法中调用createSystemTray()创建系 统托盘: public void postWindowOpen() { ... createSystemTray(); } 覆写preWindowShellClose()方法,防止关闭程序时关闭托盘: public boolean preWindowShellClose() { hookSysTray.windowMinimized(getWindowConfigurer().getWindow(). getShell()); } 退出时释放资源: public void dispose() { hookSysTray.Dispose(); }? Eclipse RCP应用系统开发3.7 品牌化应用程序添加启动画面、设置窗口图标、指定EXE 文件图标、定制欢迎画面、添加启动进 度条等等。 3.7.1 新建产品配置 产品配置用于定义和管理Eclipse RCP产 品的多个方面特征。 Eclipse RCP应用系统开发3.7.2 定制EXE文件 默 认 情 况 下 生 成 的 EXE 文 件 名 为 eclipse.exe,这自然不理想。现在将默 认生成的文件名EXE修改为jfcs.exe。单 击“Launcher”页,在Launcher Name 后的文本框中输入“jfcs”即可。 修改默认生成的EXE文件的图标: Resource Hacker, /resourcehacker。 Eclipse RCP应用系统开发3.7.3设置启动进度条和窗口图标 在闪屏画面中出现进度提示是非 常友好的应用程序启动方式。 Eclipse RCP应用系统开发第 4章 SWT/JFace简介一个RCP系统注定需要丰富的图形用户界面以方便用 户操作 。 4.1 SWT/JFace概述 SWT:Standard Widget Toolkit主要用于在Java上开发 图形用户界面。 ? 受到广泛赞誉。 ? 一个美观、能够快速响应的人机界面,有利于提升 软件品质,对于一个软件系统来说非常重要! ? Sun公司的AWT/Swing饱受业界批评。 ? JFace是根植于SWT之上的一个更易用、功能更强大 的图形包。 Eclipse RCP应用系统开发4.2 创建Java项目 Eclipse RCP应用系统开发 Eclipse RCP应用系统开发?提示:有一个商业版本的功能强大 的可视化SWT/JFace开发工具 SWTDesigner,可以到其官方网站 下载 试用版本。 Eclipse RCP应用系统开发4.3 创建SWT/JFace应用程序 4.3.1创建SWT应用程序 在rcpbook.swtjface.sample包下(除非特别 指明,后面的示例默认都创建在该包下,不 再说明)创建应用程序HelloWorld,代码如 下: Eclipse RCP应用系统开发package rcpbook.swtjface. import org.eclipse.swt.widgets.D import org.eclipse.swt.widgets.S public class HelloWorld { public static void main(String[] args) { final Display display = Display.getDefault(); final Shell shell = new Shell(); shell.setSize(500, 375); shell.setText(&Hello World!&); shell.open(); while (!shell.isDisposed()) { if (!display.readAndDispatch()) display.sleep(); } display.dispose(); } } Eclipse RCP应用系统开发4.3.2 创建JFace应用程序 JFace应用程序与SWT应用程序是有差别的。新建类HelloWorld2,代码如下:package rcpbook.swtjface. import org.eclipse.jface.window.ApplicationW import org.eclipse.swt.widgets.D import org.eclipse.swt.widgets.Spublic class HelloWorld2 extends ApplicationWindow { public HelloWorld2() { super(null);} public static void main(String args[]) { try { HelloWorld2 window = new HelloWorld2(); window.setBlockOnOpen(true); window.open(); Display.getCurrent().dispose(); } catch (Exception e) {e.printStackTrace();} } protected void configureShell(Shell parent) { parent.setText(&Hello World!&); parent.setSize(500, 375); }} Eclipse RCP应用系统开发4.4常用组件 4.4.1 标签(Label) 标签Label是非常简单的组件,用来显示信息,其构造函数为: Label(Composite parent, int style) 下面是创建标签的示例: new Label(shell, SWT.NONE).setText(&姓名&); Label label = new Label(shell, SWT.BORDER); Label.setText(&籍贯&); //创建一条竖线 Label separator=new Label(shell, SWT.SEPARATOR); separator.setSize(2,shell.getSize().y); 代码中的shell自然是放置标签的容器,因为组件是需要装在容 器里面的,由容器负责组件在界面的布局安排。 Eclipse RCP应用系统开发 4.4.2 文本框(Text) 文本框Text用于输入数据,其构造函数为: Text(Composite parent, int style) 下面是创建文本框的示例: new Label(shell, SWT.NONE).setText(&用户名&); new Text(shell, SWT.BORDER).setTextLimit(10); new Label(shell, SWT.NONE).setText(&密\b码&); Text pwd=new Text(shell, SWT.BORDER); pwd.setTextLimit(10); pwd.setEchoChar('*'); Eclipse RCP应用系统开发4.4.3 按钮(Button) 按 钮 Button 的 构 造 函 数 为 : Button(Composite parent, int style)。例如: new Button(shell, SWT.PUSH).setText(&退出&); new Button(shell, SWT.CHECK).setText(&足球 &); new Button(shell, SWT.CHECK).setText(&电影 &); final Button button = new Button(shell, SWT.NONE); button.setText(&查询&); Eclipse RCP应用系统开发4.4.4 组合框(Combo) 组合框Combo的构造函数为:Combo(Composite parent, int style)。例如: String[] city = { &湖北武汉&, &湖南长沙&, &江西南 昌&, &江苏南京&, &浙江杭州&, &河南郑州&, & 广东广州&, &广西南宁& }; Combo combo = new Combo(shell, SWT.DROP_DOWN | SWT.READ_ONLY); combo.setItems(city); Eclipse RCP应用系统开发 4.4.5 列表框(List) 列表框List的构造函数为:List(Composite parent, int style)。例如: String[] city = { &湖北武汉&, &湖南长沙&, &江西南昌&, & 江苏南京&, &浙江杭州&, &河南郑州&, &广东广州&, &广西南宁& }; List list = new List(shell, SWT.BORDER | SWT.MULTI | SWT.V_SCROLL); for (int i = 0, n = city. i & i++) { list.add(city[i]); } list.select(0); Eclipse RCP应用系统开发4.4.6 综合示例 下面是一个综合了上述组件的示例程序CommonControlSample.java: package rcpbook.swtjface. import org.eclipse.swt.SWT; import org.eclipse.swt.layout.GridL import org.eclipse.swt.widgets.*; public class CommonControlSample { public static void main(String[] args) { final Display display = Display.getDefault(); final Shell shell = new Shell(); shell.setSize(300, 240); shell.setText(&常用组件&); shell.setLayout(new GridLayout(4, false)); createContents(shell); shell.open(); while (!shell.isDisposed()) { if (!display.readAndDispatch()) display.sleep(); } display.dispose(); } Eclipse RCP应用系统开发private static void createContents(Shell shell) { new Label(shell, SWT.NONE).setText(&用户名&); new Text(shell, SWT.BORDER).setTextLimit(10); new Label(shell, SWT.NONE).setText(&密\b码&); Text pwd = new Text(shell, SWT.BORDER); pwd.setTextLimit(10); pwd.setEchoChar('*'); new Button(shell, SWT.PUSH).setText(&退出&); new Button(shell, SWT.CHECK).setText(&足球&); new Button(shell, SWT.CHECK).setText(&电影&); final Button button = new Button(shell, SWT.NONE);button.setText(&测试按钮&); String[] city = { &湖北武汉&, &湖南长沙&, &江西南昌&, &江苏南京&, &浙江杭州&, &河南郑州&,& 广东广州&, &广西南宁& }; List list = new List(shell, SWT.BORDER | SWT.MULTI | SWT.V_SCROLL); for (int i = 0, n = city. i & i++) { list.add(city[i]); } list.select(0); Combo combo = new Combo(shell, SWT.DROP_DOWN | SWT.READ_ONLY); combo.setItems(city);}} Eclipse RCP应用系统开发 Eclipse RCP应用系统开发4.5常用布局管理器 4.5.1 FillLayout 填充式布局管理器,即组件的大小会尽可能充满整个容器。其 构造函数有两个:public FillLayout()和public FillLayout(int type) 。例如: shell.setLayout(new FillLayout()); 下面是一个示例程序: package rcpbook.swtjface. import org.eclipse.swt.SWT; import org.eclipse.swt.layout.FillL import org.eclipse.swt.widgets.B import org.eclipse.swt.widgets.D import org.eclipse.swt.widgets.S public class FillLayoutSample { Eclipse RCP应用系统开发public static void main(String[] args) { final Display display = Display.getDefault(); final Shell shell = new Shell(); shell.setSize(240, 180); shell.setText(&FillLayout布局&); shell.setLayout(new FillLayout()); new Button(shell, SWT.NONE).setText(&按钮1&); new Button(shell, SWT.NONE).setText(&按钮2&); shell.open(); while (!shell.isDisposed()) { if (!display.readAndDispatch()) display.sleep(); } display.dispose(); }} Eclipse RCP应用系统开发 Eclipse RCP应用系统开发4.5.2 RowLayout 将组件放置在单行或单列,不过不强制全部组件布局 成相同的大小。另外,它还可以自动折行显示,并 可设置边界距离和组件间距。其构造函数有两个: public RowLayout()和public RowLayout(int type) 。 例如: shell.setLayout(new RowLayout()); 下面是一个设置了顶部距离和组件间距的示例: package rcpbook.swtjface. import org.eclipse.swt.SWT; import org.eclipse.swt.layout.RowL import org.eclipse.swt.widgets.*; Eclipse RCP应用系统开发 public class RowLayoutSample { public static void main(String[] args) { final Display display = Display.getDefault(); final Shell shell = new Shell(); shell.setSize(240, 180); shell.setText(&RowLayout布局&); RowLayout rowLayout = new RowLayout(); rowLayout.marginTop = 20; rowLayout.spacing = 10; shell.setLayout(rowLayout); Eclipse RCP应用系统开发new Button(shell, SWT.NONE).setText(&按钮1&); new Button(shell, SWT.NONE).setText(&按钮2&); new Button(shell, SWT.NONE).setText(&按钮3&); new Button(shell, SWT.NONE).setText(&按钮4&); new Button(shell, SWT.NONE).setText(&按钮5&); shell.open(); while (!shell.isDisposed()) { if (!display.readAndDispatch()) display.sleep(); } display.dispose();} } Eclipse RCP应用系统开发 Eclipse RCP应用系统开发 4.5.3 GridLayout网格式布局管理器。一般配合使用其专用的布局数据类 GridData。 GridLayout 的 构 造 函 数 有 2 个 : public GridLayout () 和 public GridLayout (int numColumns, boolean makeColumnsEqualWidth),numColumns指表格列数, makeColumnsEqualWidth指定列宽是否相等。下面是一 个应用GridLayout的示例程序: package rcpbook.swtjface. import org.eclipse.swt.SWT; import org.eclipse.swt.layout.*; import org.eclipse.swt.widgets.*; Eclipse RCP应用系统开发public class GridlayoutSample { public static void main(String[] args) { final Display display = Display.getDefault(); final Shell shell = new Shell(); shell.setSize(240, 180); shell.setText(&GridLayout布局&);GridLayout layout = new GridLayout(); layout.numColumns = 3; layout.marginTop = 10; layout.marginBottom = 10; layout.marginRight = 10; layout.horizontalSpacing = 10; layout.makeColumnsEqualWidth = shell.setLayout(layout); GridData gridData = new GridData(GridData.FILL_HORIZONTAL); gridData.widthHint = 60; gridData.heightHint = 100; gridData.verticalSpan = 2; Eclipse RCP应用系统开发Button button1 = new Button(shell, SWT.NONE); button1.setText(&按钮1&); button1.setLayoutData(gridData); gridData = new GridData(GridData.FILL_BOTH); Button button2 = new Button(shell, SWT.NONE); button2.setText(&按钮2&); button2.setLayoutData(gridData); gridData = new GridData(GridData.FILL_BOTH); Button button3 = new Button(shell, SWT.NONE); button3.setText(&按钮3&); button3.setLayoutData(gridData); gridData = new GridData(GridData.FILL_BOTH); Button button4 = new Button(shell, SWT.NONE); button4.setText(&按钮4&); button4.setLayoutData(gridData); Button button5 = new Button(shell, SWT.NONE); button5.setText(&按钮5&); button5.setLayoutData(gridData); Eclipse RCP应用系统开发shell.open(); while (!shell.isDisposed()) { if (!display.readAndDispatch()) display.sleep(); } display.dispose(); }} Eclipse RCP应用系统开发 Eclipse RCP应用系统开发综合示例package rcpbook.swtjface. import org.eclipse.swt.SWT; import org.eclipse.swt.layout.*; import org.eclipse.swt.widgets.*; public class FormLayoutSample { public static void main(String[] args) { final Display display = Display.getDefault(); final Shell shell = new Shell(); shell.setSize(240, 200); shell.setText(&FormLayout布局&); FormLayout layout = new FormLayout(); layout.marginTop = 5; layout.marginLeft = 5; layout.marginRight = 5; shell.setLayout(layout); Eclipse RCP应用系统开发 Button button1 = new Button(shell, SWT.PUSH); button1.setText(&按钮1&); FormData formData = new FormData(); formData.height = 40; formData.right = new FormAttachment(100, -100); formData.left = new FormAttachment(0, 10); formData.top = new FormAttachment(1, 10, 0); button1.setLayoutData(formData); Eclipse RCP应用系统开发Button button2 = new Button(shell, SWT.PUSH); button2.setText(&按钮2&); formData = new FormData(); formData.height = 60; formData.width = 90; button2.setLayoutData(formData); formData.top = new FormAttachment(button1, 5, SWT.BOTTOM); formData.left = new FormAttachment(button1, -10, SWT.RIGHT); Eclipse RCP应用系统开发shell.open(); while (!shell.isDisposed()) { if (!display.readAndDispatch()) display.sleep(); } display.dispose(); }} Eclipse RCP应用系统开发 Eclipse RCP应用系统开发4.6 其他常用组件4.6.1 菜单(Menu) 菜单Menu是一种比较常见的组件,其构造函数有4个: ? public Menu (Control parent),构造一个弹出式菜单, 并自动使用SWT.POP_UP式样。 ? public Menu (Decorations parent, int style),构造一个 指定式样的菜单。 ? public Menu (Menu parentMenu),构建一个父菜单 parentMenu的下拉式子菜单,并自动使用 SWT.DROP_DOWN式样。 ? public Menu (MenuItem parentItem),构建一个指定 父菜单项的下拉式子菜单。 Eclipse RCP应用系统开发菜单的式样主要有: ? SWT.BAR,用于主菜单。 ? SWT.DROP_DOWN,用于子菜单。 ? SWT.POP_UP,用于右键菜单。菜单需要有菜单项MenuItem。MenuItem类扩展自 Item类,其构造函数有2个: ? public MenuItem (Menu parent, int style),根据指 定式样style生成指定菜单parent的菜单项。 ? public MenuItem (Menu parent, int style, int index), 根据指定式样style生成指定菜单parent的菜单项, 其中index为大于或等于0的菜单项相对于其他菜单 项的索引值。 Eclipse RCP应用系统开发创建菜单的具体步骤可以简述如下: (1) 创建菜单栏。例如:Menu menu = new Menu(shell, SWT.BAR)。 (2) 创建菜单栏的顶级菜单项。例如: MenuItem fileItem = new MenuItem(menu, SWT.CASCADE); fileItem.setText(&文件(&F)&); MenuItem editItem = new MenuItem(menu, SWT.CASCADE); editItem.setText(&编辑(&E)&); MenuItem helpItem = new MenuItem(menu, SWT.CASCADE); helpItem.setText(&帮助(&H)&); (3) 创建菜单项对应的下拉菜单。例如: Menu helpMenu = new Menu(menu); helpItem.setMenu(helpMenu); (4) 为下拉菜单添加具体的菜单项。例如: MenuItem welcome = new MenuItem(helpMenu, SWT.NONE); welcome.setText(&欢迎使用&); new MenuItem(helpMenu, SWT.SEPARATOR); MenuItem intro = new MenuItem(helpMenu, SWT.NONE); intro.setText(&系统说明&); (5) 使用shell.setMenuBar(menu)语句指定窗口需要显示的菜单栏。 Eclipse RCP应用系统开发 4.6.2 工具栏(ToolBar)、动态工具栏(CoolBar)1.工具栏(ToolBar) 工具栏ToolBar扩展自Composite类,其构造函数 为public ToolBar (Composite parent, int style), 即在指定容器parent中创建指定式样style的工 具栏。工具栏的式样主要有: ? SWT.FLAT,具体的工具栏项采用平面式样。 ? SWT.RIGHT,工具栏右对齐排列。 ? SWT.HORIZONTAL,水平方向的工具栏。 ? SWT.VERTICAL,垂直方向的工具栏。 ? SWT.SHADOW_OUT,带外阴影的工具栏。 Eclipse RCP应用系统开发与菜单类似,工具栏需要创建具体的工具栏项ToolItem。 ToolItem扩展自Item类,其构造函数有2个:public ToolItem (ToolBar parent, int style)根据指定式样 style创建parent工具栏的工具栏项,而构造函数 public ToolItem (ToolBar parent, int style, int index) 只是需要额外指定了工具栏项的索引值。工具栏项 ToolItem主要式样如下: ? SWT.CHECK,这种工具栏项单击时会凹下去,再单 击则会凸起来。 ? SWT.PUSH,普通按钮。 ? SWT.RADIO,一组RADIO类型按钮,任一时刻只有 一个下陷,其他则弹起。 ? SWT.DROP_DOWN,旁边带下拉箭头的按钮。 ? SWT.SEPARATOR,工具栏项之间的分隔线。 Eclipse RCP应用系统开发下面是一个工具栏示例: ToolBar toolBar = new ToolBar(shell, SWT.FLAT|SWT.HORIZONTAL|SWT.SHADOW_ OUT); ToolItem item = new ToolItem(toolBar, SWT.PUSH); item.setText(&关于系统&); Eclipse RCP应用系统开发2. 动态工具栏(CoolBar) CoolBar允许用户通过拖放操作改变工具栏项目的排放位置,因此 被称之为动态工具栏。CoolBar需要结合CoolItem使用。其构造 函数为public CoolBar(Composite parent, int style),而 CoolItem扩展自Item类,其构造函数有2个:public CoolItem (CoolBar parent, int style)和public CoolItem (CoolBar parent, int style, int index),其含义类似于ToolItem。下面是一个 CoolBar示例: CoolBar coolbar = new CoolBar(shell, SWT.NONE); CoolItem coolItem = new CoolItem(coolbar, SWT.NONE); Button button = new Button(coolbar, SWT.PUSH); button.setText(&数据备份&); button.setImage(new Image(shell.getDisplay(),&images/databak.gif&)); coolItem.setControl(button); Eclipse RCP应用系统开发4.6.3 CLabel CLabel是一种定制标签(Custom Label),与 Label最大的不同是可以同时显示图像和文本, 例如: CLabel cl = new CLabel(shell, SWT.CENTER | SWT.SHADOW_IN); cl.setText(&系统开发:王二麻子&); Image image = new Image(display, Sample1.class.getResourceAsStream(&images/au thor.gif&)); cl.setImage(image); Eclipse RCP应用系统开发 4.6.4 CCombo 一种定制组合框。 CCombo构造函数为public CCombo (Composite parent, int style),例如: String[] city = { &湖北武汉&, &湖南长沙&, &江西南昌&, & 江苏南京&, &浙江杭州&, &河南郑州&,&广东广州&, &广西 南宁& }; new CCombo(shell,SWT.FLAT|SWT.READ_ONLY).setItems( city); Eclipse RCP应用系统开发4.6.5 滚动条(Slider) 其构造函数为Slider (Composite parent, int style), 下面是一个滚动条示例: Slider slider = new Slider(shell, SWT.HORIZONTAL); slider.setMinimum(0); slider.setMaximum(100); slider.setIncrement(2); slider.setSelection(50); Eclipse RCP应用系统开发4.6.6 分组框(Group) 用于将同类性质的事物组合在一起。分组框的 构造函数为public Group (Composite parent, int style)。下面是一个分组框的简单例子: Group group1 = new Group(shell, SWT.SHADOW_IN); group1.setText(&个人爱好&); new Button(group1, SWT.CHECK).setText(& 足球&); new Button(group1, SWT.CHECK).setText(& 电影&); Eclipse RCP应用系统开发4.6.7 进度条 ProgressBar扩展自Control 类,其构造函数为public ProgressBar (Composite parent, int style),style主要式样如下: n SWT.SMOOTH,平滑式样的进度条。 n SWT.HORIZONTAL,水平方向的进度条。 n SWT.VERTICAL,垂直方向的进度条。 请看下面的示例: final ProgressBar progressbar = new ProgressBar(shell, SWT.HORIZONTAL| SWT.SMOOTH); progressbar.setMinimum(0); progressbar.setMaximum(100); Eclipse RCP应用系统开发 Eclipse RCP应用系统开发4.6.8表格Table 一种容器,其构造函数为public Table (Composite parent, int style),主要的式样如下: ? SWT.SINGLE,默认式样,每次只能选择表格 的一行。 ? SWT.MULTI,允许选择表格的多行。 ? SWT.CHECK,表格每一行前面带有检查框。 ? SWT.FULL_SELECTION,高亮显示选择行的 全部列。 ? SWT.HIDE_SELECTION,当当前窗口不是活 动窗口时,当前选择的行将不再高亮显示。 Eclipse RCP应用系统开发下面是一个简单程序: private static void createContents(Shell shell) { Table table = new Table(shell, SWT.CHECK | SWT.HIDE_SELECTION); table.setHeaderVisible(true); table.setLinesVisible(true); table.setRedraw(false); TableColumn tableColumn1 = new TableColumn(table, SWT.NONE); tableColumn1.setText(&学号&); tableColumn1.setWidth(80); TableColumn tableColumn2 = new TableColumn(table, SWT.NONE); tableColumn2.setText(&姓名&); tableColumn2.setWidth(80); TableColumn tableColumn3 = new TableColumn(table, SWT.NONE); tableColumn3.setText(&专业&); tableColumn3.setWidth(80); for (int i = 0; i & 6; i++) { TableItem item = new TableItem(table, SWT.NONE); item.setText(0, i + &_column1&); item.setText(1, (i + 1) + &_column2&); item.setText(2, (i + 2) + &_column3&); } table.setRedraw(true); } Eclipse RCP应用系统开发 Eclipse RCP应用系统开发4.6.9树Tree Tree是一种表格型树,构造函数为public Tree(Composite parent, int style),主要的式样有SWT.SINGLE、SWT.MULTI、 SWT.CHECK。与Table类似, Tree需要TreeItem配合使用以 生成记录数据。TreeItem扩展自Item类,其构造函数主要有4个: ? public TreeItem (Tree parent, int style),以指定式样style生成 指定树parent的结点项。 ? public TreeItem (Tree parent, int style, int index),以指定式样 style生成指定树parent的结点项,并指定其索引值。 ? public TreeItem (TreeItem parentItem, int style) ,以指定式样 style生成树结点项parentItem的子结点。 ? public TreeItem (TreeItem parentItem, int style, int index) ,以 指定式样style生成树结点项parentItem的子结点,并指定其索 引值。 Eclipse RCP应用系统开发private static void createContents(Shell shell) { Tree tree = new Tree(shell, SWT.NONE); tree.setHeaderVisible(true); tree.setLinesVisible(true); tree.setRedraw(false); String[] provinces = { &湖北省&, &广东省&, &江苏省&, &浙江省& }; String[][] city = { { &武汉&, &宜昌&, &黄冈& }, { &广州&, &深圳&, &佛山&, &梅州 & }, { &南京&, &常州& }, { &杭州&, &绍兴&, &嘉兴& } }; for (int i = 0; i & provinces. i++) { TreeItem parent = new TreeItem(tree, SWT.NONE); parent.setText(provinces[i]); for (int j = 0; j & city[i]. j++) { TreeItem child = new TreeItem(parent, SWT.NONE); child.setText(city[i][j]); } tree.setRedraw(true); } } Eclipse RCP应用系统开发 Eclipse RCP应用系统开发4.7对话框类 Eclipse提供了很多对话框,主要对话框如下: 1. 信息提示框 信息提示框有两种:MessageBox和MessageDialog。 (1) MessageBox MessageBox 扩展自SWT的Dialog抽象类,其构造函数为: ? public MessageBox (Shell parent),在指定父容器parent上创建一个对话框,采用 默认的SWT.OK | SWT.ICON_INFORMATION | SWT.APPLICATION_MODAL式样。 ? public MessageBox (Shell parent, int style),以指定式样style在父容器parent上创 建一个对话框。常见的图标式样有:SWT.ICON_ERROR、 SWT.ICON_INFORMATION、SWT.ICON_QUESTION、SWT.ICON_WARNING、 SWT.ICON_WORKING。常用的按钮式样有:SWT.OK、SWT.CANCEL、 SWT.YES 、SWT.NO、SWT.RETRY、SWT.ABORT、SWT.IGNORE。 下面是一个示例: MessageBox messageBox = new MessageBox(shell,SWT.YES|SWT.NO|SWT.ICON_QUESTION); messageBox.setMessage(&确认删除当前记录?&); messageBox.setText(&提示&); messageBox.open(); Eclipse RCP应用系统开发(2) MessageDialog MessageDialog扩展自JFace的抽象类IconAndMessageDialog,其构造函 数为: public MessageDialog(Shell parentShell, String dialogTitle,Image dialogTitleImage, String dialogMessage, int dialogImageType, String[] dialogButtonLabels, int defaultIndex); 不过,实际中更通常的做法是直接调用MessageDialog类提供的静态方法, 主要有以下5个: ? public static boolean openConfirm(Shell parent, String title, String message),显示一个带有OK、Cancel按钮的确认对话框。 ? public static void openError(Shell parent, String title, String message), 显示一个带有OK按钮的出错提示对话框。 ? public static void openInformation(Shell parent, String title,String message),显示一个带有OK按钮的信息提示对话框。 ? public static boolean openQuestion(Shell parent, String title,String message),显示一个带有Yes、No按钮的提问对话框。 ? public static void openWarning(Shell parent, String title, String message),显示一个带有OK按钮的警告对话框。 Eclipse RCP应用系统开发 Eclipse RCP应用系统开发 2. 字体选择对话框 字体选择对话框FontDialog 扩展自SWT的Dialog类。 下面是一个示例,运行效果如图所示: FontDialog fontDialog= new FontDialog(shell); FontData fontData = fontDialog.open(); if (fontData != null) { Font font = new Font(shell.getDisplay(), fontData); ……// 使用所选择的字体对象 font.dispose();// 使用完毕释放 } Eclipse RCP应用系统开发 Eclipse RCP应用系统开发3. 颜色选择对话框 颜色选择对话框ColorDialog同样扩展自SWT的Dialog 类,其构造函数有public ColorDialog (Shell parent) 和public ColorDialog (Shell parent, int style)。下面 代码的运行效果如图4-25所示: ColorDialog colorDialog = new ColorDialog(shell); RGB rgb = colorDialog.open(); if (rgb != null) { Color color = new Color(shell.getDisplay(), rgb); ……// 使用所选择的颜色 color.dispose();// 使用完毕释放 } Eclipse RCP应用系统开发 Eclipse RCP应用系统开发4. 目录选择对话框 目录选择对话框DirectoryDialog扩展自SWT的Dialog类,其构造 函数有public DirectoryDialog (Shell parent)和public DirectoryDialog (Shell parent, int style)。下面是一个简单示例, 运行效果如图所示: DirectoryDialog directoryDialog = new DirectoryDialog(shell); // 对话框标题 directoryDialog.setText(&系统数据备份&); // 对话框提示文字 directoryDialog.setMessage(&请选择备份目标文件夹:&); final String detsFolder = directoryDialog.open(); if (detsFolder == null) Eclipse RCP应用系统开发 Eclipse RCP应用系统开发5. 文件选择对话框 文件选择对话框FileDialog扩展自SWT的Dialog类,其构造函 数有public FileDialog (Shell parent)和public FileDialog (Shell parent, int style)。下面的示例默认显示“我的文档” 文件夹下的doc类型文件以供用户选择,选中对应文件后, 将自动调用Word打开该文件,运行效果如图所示: FileDialog fileDialog = new FileDialog(shell, SWT.OPEN); fileDialog.setFilterExtensions(new String[] {&*.doc&, &*.xls&, &*.ppt&, &*.*&}); fileDialog.setFilterPath(&%userprofile%/My Documents&); String fileName = fileDialog.open(); if (fileName != null) { Program.launch(fileName); } Eclipse RCP应用系统开发 Eclipse RCP应用系统开发6. 输入值对话框 InputDialog对话框用于接收用户输入的数据,该类扩 展自JFace的抽象类Dialog,其构造函数为: public InputDialog(Shell parentShell, String dialogTitle,String dialogMessage, String initialValue, IInputValidator validator) 构造函数的各参数含义为:parentShell指顶层Shell对 象,dialogTitle表示对话框标题栏文字, dialogMessage指对话框上的提示信息, initialValue指初始的输入值,validator表示输入数 据校验器。 Eclipse RCP应用系统开发下面是一个简单示例,其运行效果如图所示: InputDialog inputDialog = new InputDialog(shell, &数据输入&, &请输入邮政 编码:&, &000000&, new IInputValidator() { public String isValid(String newText) { if (newText.length() != 6) { return &邮政编码长度有 误!&; } } }); if (inputDialog.open() == Window.OK) MessageDialog.openInformation(shell, &提示&, &您输入的邮政 编码为:& + inputDialog.getValue()); else MessageDialog.openInformation(shell, &提示&, &您取消了数据 输入!&); Eclipse RCP应用系统开发 Eclipse RCP应用系统开发7.进度条对话框 对于需要较长时间的操作来说,应该向用户显 示一个进度条对话框以提示用户程序正在操 作(而非停止响应)以及操作进度,这有利 于提升用户的耐心,也提高了软件的友好性。 进度条对话框ProgressMonitorDialog扩展自 JFace的抽象类IconAndMessageDialog并实 现了IRunnableContext接口,其构造函数为 public ProgressMonitorDialog(Shell parent Eclipse RCP应用系统开发下面是示例代码: Button progress = new Button(shell, SWT.NONE); progress.setText(&显示进度条&); progress.addSelectionListener(new SelectionAdapter() { public void widgetSelected(SelectionEvent event) { try { new ProgressMonitorDialog(shell).run(true, false, new IRunnableWithProgress() { public void run(IProgressMonitor monitor) throws InvocationTargetException,InterruptedException { monitor.beginTask(&开始执行。。。&, 100); for (int i = 0; i & 100; i++) { monitor.subTask(&正在进行第& + i + &步。。。&); monitor.worked(1); Thread.sleep(100); } monitor.done(); } }); } catch (Exception e) { e.printStackTrace();} } Eclipse RCP应用系统开发 Eclipse RCP应用系统开发上面的代码看起来比较复杂 ,其实可以按照以下模板写 ProgressMonitorDialog: ProgressMonitorDialog pmd = new ProgressMonitorDialog(null); IRunnableWithProgress rwp = new IRunnableWithProgress() { public void run(IProgressMonitor monitor) throws InvocationTargetException, InterruptedException { //需要长时间进行的操作处理 } }; try {171 pmd.run(true, false, rwp); } catch (Exception e) { e.printStackTrace(); } Eclipse RCP应用系统开发第5章 Hibernate数据持久化5.1 Hibernate简介 Hibernate是一个开源的对象关系映射框架,负责Java对象和关系数据 之间的映射,是Java应用和关系数据库之间的桥梁。Hibernate对JDBC进行 了轻量级的对象封装,其内部封装了通过JDBC访问数据库的操作,并向上 层应用提供了面向对象的数据访问API。Hibernate可以应用在任何使用 JDBC的场合,既可以在Java的客户端程序使用,也可以在Servlet/JSP等 Web应用中使用,担当数据持久化的重任。这样一来,开发人员不用再写 繁琐的SQL语句,Hibernate自动帮我们生成,也不用考虑如何从数据库中 取出或保存数据,Hibernate包办了。一句话,与数据库打交道变得轻松了! Hibernate是一个出生于民间的草根英雄。不像有些数据库持久化技术, 背后有大公司支撑。Hibernate只是一个热爱Java的程序员Gavin King于2001 年催生的,而且更新速度很快。2003年6月,Hibernate 2发布,并被 javaworld评选为2003年度最佳java数据存取工具。2005年3月,Hibernate 3发布,更是受到了空前关注。现在,Hibernate已经成为著名开源组织 JBoss的子项目之一。 Eclipse RCP应用系统开发Hibernate的优势在哪儿? ?轻量级封装。 ?开发效率高。 ?开发者活跃。 ?开源和免费。 ?分布式、可扩展。 Eclipse RCP应用系统开发5.2 Hibernate工作流程Java应用程序 实体类Business ServiceHibernate Hibernate APIXML映射文件Hibernate配置数据库服务器数据表 Eclipse RCP应用系统开发5.3 Hibernate下载安装Hibernate官方下载网址为http://www.hibernate.org/,如图 所示,目前最新版本为3.2.1。该网站同时提供了一些辅助工具 和相关文档资料。 Eclipse RCP应用系统开发. 5.4 Hibernate查询语言SQL (1) from子句 from子句返回类的实例。格式:from 类名。 (2) select子句 select子句返回类的指定对象或属性。格式:select 对象/属性 from类名。 (3) where子句 where子句返回指定范围的实例。格式:where &条件& (4) order by子句 order by子句将查询返回的列表按照指定属性进行排序,asc为升序,desc为降序。格式: order by 属性asc/desc。例如:from Student where zy=’电子商务’ order by cet4 desc。 (5) group by子句 group by 子 句 , 将 查 询 返 回 的 列 表 按 照 指 定 属 性 进 行 分 组 。 例 如 : select Student.xh,Student.xm,Student.nl, Student.zy from Student student group by zy。 (6) Query查询 Query用于执行查询并返回结果。例如: String hql=&from Users where username=:user and password=:pwd&; Query query=session.createQuery(hql); query.setString(&user&,&tom&); query.setString(&pwd&,&007&); List list=query.list(); 程序说明:hql查询语句需要传递两个参数user、pwd,示例中向其分别传递了tom和007作为 参数值。查询结果封装到List集合中。 Eclipse RCP应用系统开发5.5 Hibernate配置文件hibernate.cfg.xml下面是一个比较常见的hibernate.cfg.xml配置文件的内容: &?xml version=&1.0& encoding=&utf-8&?& &!DOCTYPE hibernate-configuration PUBLIC &-//Hibernate/Hibernate Configuration DTD//EN& &http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd&& &hibernate-configuration& &session-factory& &!-- local connection properties --& &property name=&hibernate.connection.url&&jdbc:mysql://localhost/booktest&/property& &property name=&hibernate.connection.driver_class&&com.mysql.jdbc.Driver&/property& &property name=&hibernate.connection.username&&tom&/property& &property name=&hibernate.connection.password&&rcp&/property& &!-- dialect for MySQL --& &property name=&dialect&&org.hibernate.dialect.MySQLDialect&/property& &property name=&hibernate.show_sql&&true&/property& &property name=&hibernate.transaction.factory_class&& org.hibernate.transaction.JDBCTransactionFactory &/property& &mapping resource=&test/model/Student.hbm.xml& /& &/session-factory& &/hibernate-configuration& Eclipse RCP应用系统开发5.6 ConfigurationConfiguration类负责管理Hibernate配置信息,其实例 代表了应用程序中Java类到数据库的映射集合。通 过Configuration的实例,Hibernate将构造一个 SessionFactory实例并绑定基于hibernate.cfg.xml的 配置信息。 如果使用默认配置文件hibernate.cfg.xml,则可以这 样获得Configuration的实例: Configuration config=new Configuration().configure(); 如果希望使用特定的配置文件,例如 hibernate_derby.cfg.xml,则可以这样: Configuration config=new Configuration().configure(&hibernate_mysql.cfg.xml &); Eclipse RCP应用系统开发5.7Session和SessionFactoryHibernate之所以能够将实体对象和数据库连接,离不 开非常重要的Session对象。Session是Hibernate持 久化的基础,应用程序通过Session与数据库交互。 需要注意的是,Session与JSP中的session有很大 差别,没有任何关系。 SessionFactory负责创建Session实例,下面是创建 Session的示例代码: Configuration config=new Configuration().configure(); SessionFactory sf =config.buildSessionFactory(); Session session=sf.openSession(); 然后就可以调用session的各种方法完成数据库持久化 操作。 Eclipse RCP应用系统开发5.8 Hibernate映射文件映射文件的作用就在于告诉Hibernate应该访问哪个数据库的哪个表以及哪些字段, 这样Hibernate才能够将类的对象持久化到数据库的数据表。下面是一个示例: &?xml version=&1.0&?& &!DOCTYPE hibernate-mapping PUBLIC &-//Hibernate/Hibernate Mapping DTD//EN& &http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd& & &hibernate-mapping package=&test.model&& &class name=& Users & table=&users&& &meta attribute=&sync-DAO&&false&/meta& &id name=&Id& type=&integer& column=&id&& &generator class=&identity&/& &/id& &property name=&Username& column=&username& type=&string&/& &property name=&Password& column=&password& type=&string&/& &/class& &/hibernate-mapping& Eclipse RCP应用系统开发5.9 Hibernate牛刀小试(1) 启动MySQL。 (2)生成Hibernate配置文件hibernate.cfg.xml。。 注意,务必将hibernate.cfg.xml文件放置在项目 src文件夹下,以避免不必要的麻烦。 (3)生成映射文件。在src下新建包test.model, 单击鼠标右键,选择【New】→【Other…】→ 【Hibernate】→【Hibernate Mapping File】 (4)在hibernat.cfg.xml文件中添加Users.hbm.xml 映射。 (5)生成Java文件。 Eclipse RCP应用系统开发(6)编写测试程序public void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType(&text/html&); PrintWriter out = response.getWriter(); try { SessionFactory sf = new Configuration().configure().buildSessionFactory(); Session session = sf.openSession(); Transaction tx = session.beginTransaction(); Users users= new Users(); users.setUsername(&007&); users.setPassword(&1234567&); session.save(users); Eclipse RCP应用系统开发tx.commit(); session.close(); out.println(&sucess&); }catch (HibernateException e) { out.print(e); } out.flush(); out.close(); } Eclipse RCP应用系统开发5.10 Hibernate Session工厂管理类SessionFactory sf = new Configuration().configure().buildSessionFactory() 语句生成管理Hibernate Session的工厂类。生成 SessionFactory非常消耗时间和资源,如果每一 次都生成Hibernate Session工厂类,显然低效而 且繁琐。因此创建一个关键的类 HibernateSessionFactory,这个类的任务之一是 创建一个单例模式的SessionFactory来管理 Session的创建和关闭。 Eclipse RCP应用系统开发import … public class HibernateSessionFactory { private static final ThreadLocal&Session& threadLocal = new ThreadLocal&Session&(); private static final Configuration cfg = new Configuration(); private static SessionF //获取Session对象 public static Session getSession(String configFile) throws HibernateException { Session session = (Session) threadLocal.get(); if (session == null || !session.isOpen()) { if (sf == null) { try { cfg.configure(configFile);//设置配置文件 sf = cfg.buildSessionFactory();//创建Session工厂 } catch (Exception e) { e.printStackTrace();} } session = (sf == null) ? null : sf.openSession(); threadLocal.set(session); } } Eclipse RCP应用系统开发 //关闭Session对象 public static void closeSession() HibernateException { Session session = (Session) threadLocal.get(); threadLocal.set(null); if (session != null) session.close(); } private HibernateSessionFactory() {}}throws Eclipse RCP应用系统开发使用示例:Session session = HibernateSessionFactory.getSession(&hibernate_derby.cfg. xml&); String hql = &from Users where username=:user and password=:pwd&; Query query = session.createQuery(hql);//创建查询 query.setString(&user&, username); query.setString(&pwd&, password); if (query.list().size() & 0) { //登录成功 } HibernateSession}

我要回帖

更多关于 怎么让Word里的视图整体变小 的文章

更多推荐

版权声明:文章内容来源于网络,版权归原作者所有,如有侵权请点击这里与我们联系,我们将及时删除。

点击添加站长微信