文档库 最新最全的文档下载
当前位置:文档库 › java swing 中文教程

java swing 中文教程

java swing 中文教程
java swing 中文教程

作者:williamchen

译者:Matthew Chen

备注:本文是翻译,由于部分文本网上有提供,就直接使用了。作者的初稿,不是很规范的英文,但是内容值得一读,所以翻译了出来,一系列共有四篇,红字为译者评论。

Overview概述

Java GUI toolkits have always been a controversial topic. The same type of debates also happened in other languages such as Smalltalk. In fact there exist such debates on every

platform-independent language. It is especially prominent in Java because Java is the most dominating language today.

Java GUI 工具包一直是一个倍受争议的话题。同样的争论也发生在其他编程语言如Smalltalk。实际上每个平台无关的语言都存在着这样的争论。Java作为当前最受广泛使用的编程语言而尤为突出。

So what’s the controversy? Basically, it is a dispute between people who support emulated components(or widgets, or controls) and those who support native components. There are two camps among Java developers, one of which advocates for emulated components as in Swing, and the other native components as in SWT.

这场争论在支持模拟组件(如widgets和control,在下文中也称之为仿造组件)和支持本地组件(在下文中也称之为原生组件)的人们之间展开,于是Java开发者形成了两个不同的阵营,提倡使用模拟组件的Swing,和提倡使用原生组件的SWT。[战争从来都在相似的人们之间展开,因为它们想要一个东西]

History历史

There are many stories about around the dispute on the Internet. You should probably have already heard of them. One of them can help you to understand the whole picture. Let’s start with this one, in which Amy Fowler from Swing team is one of the protagonists.

Internet上有许多围绕这一争论的故事。你可能已经听说过它们中的大多数了,其中之一有助于让你理清头绪,让我们就从这里开始,Amy Fowler是Swing阵营的一个倡导者。

Back in 1990s, there were three companies, which developed their products using Smalltalk. They are IBM, Digital Talk and Parc-Place. IBM and Digital Talk adopted native components, while Parc-Place believed that emulation is the way to go. At the very beginning, all things went well until IBM overtook the others. The other two then merged to form a new company named Objectshare. Then a huge battle erupted when they tried to merge their products into one. The native and emulated crowd fought the battle nearly to death. When Amy Fowler from Parc-place, who insisted on emulated components, finally won the victory, IBM had got all of their accounts, because the two companies did nothing but quarrel for an entire year. The share price of the company, went down to under 1 dollar a share and were pulled from NASDAQ because of incorrect financial reportings.

回到上个世纪90年代,曾几何时有3家庞大的Smalltalk公司——IBM、Parc-Place和 Digitalk。在90年代初期3家公司的市场份额大致相等,生活是美好的。Parc-Place采用仿窗口部件(emulated widgets)的设计(即Swing的设计),IBM和Digitalk则采用原生窗口部件(native widgets)。后来IBM压倒了另外两家,因此他们打算合并成一家,假设叫做Parc-Place Digitalk。随后当他们试图将他们的产品融合到一个叫做Jigsaw的计划中时爆发了一场大战,计划由于政治原因失败了(开发人员实际上已经能让它运转起来),就因为原生和仿造两派的死战。Amy赢得了精神上的胜利,不过IBM赢得了他们所有的生意,因为这两家公司在一整年里除了吵架什么都没做。当尘埃落定之后PPD(Parc-Place Digitalk当时已改名为Objectshare,跟Windscale改名为Sellafield的原因相同——让人们淡忘之前发生的灾难)的股票价格从60美元掉到了低于1美元1股。他们因为伪报收入被NASDAQ摘牌,从此消失。

At that time, AWT had just existed. Sun had built a basic set of portable control classes that mapped to native components on the different operating systems. However AWT was very buggy. It was beyond belief this was just poor code that could be fixed. Just then, Amy was hired by Sun, and she promised to solve all of the problems by doing a lightweight solution. Convinced, Sun management to make her the head of the GUI development. Amy then hired all her old Parc-Place friends and they set about creating Swing.

当时,AWT已经出现了。SUN当时已经建立了一套基本的可移植控件类,这些类映射到不同操作系统上的原生窗口组件(native widget),当时的AWT还满是漏洞,远不能称为可靠,还需要SUN的coder们去修补。然后Amy被雇佣了,她承诺通过轻量级方案解决所有窗口组件的问题,以此说服SUN管理层让她当了GUI 开发部门的头头。随后Amy雇佣了所有她过去在Parc-Place的旧朋友,让他们来开发Swing。[不知道Amy 是不是理想主义者,但我是,从我选择Java那天起]

In IBM, Visual Age for Java were first written in Smalltalk, which used native components. Then they started to migrate them to a Java code. All of the IBM developers are the those Smalltalk guy, and they hated Swing for its emulated nature. They reluctantly built it using Swing. At that time, it is of no doubt that Swing was ugly, slow and buggy. Therefore they created a project

to migrate the Smalltalk native components over to Java. This toolkit was later called SWT, which initially means Simple Widget Toolkit and later Standard Widget Toolkit. It was a success as they released a product called Visual Age Micro Edition. The folks later found that there were bugs in Swing reading windows events, which could cause memory leaks. So they took the decision that SWT and AWT/Swing should not co-exist and then put the toolkit into Eclipse which is a tools platform derived from the early Visual Age.

在IBM,VisualAge for Java最初是用Smalltalk(用的是原生窗口组件)写的,当将这些工具向Java代码库迁移时,他们需要一套窗口组件。IBM这边的开发人员都是原来搞Smalltalk的那一批人,他们对管理层要求用Swing来构建WebSphere Studio工具都非常不情愿。“Swing是个可怕的充满缺陷的怪兽“。因此开始了一个新的项目,把他们的Smalltalk原生窗口组件移植到Java上去。这个工具集后来被成为SWT,S开始是Simple的缩写,不过后来变成了Standard的缩写。这个项目获得了成功,被运用在发布的VisualAge Micro Edition产品中。他们当时发现在Swing读事件队列的时候用了一种可能留下内存漏洞的方式,而不得不采用他们自己的查询 Windows事件队列的循环,以纠正这个错误。这促成了他们关于SWT 和 AWT/Swing不能共存的决定。他们把这个工具包放到了Eclipse中,这是一个来自于早期Visual Age

的工具平台。

The above story should have given you an overview of the history of the three, especially SWT. Now you might think, the reason IBM did to create SWT was valid and Swing should follow the way

SWT has been on. Actually this opinion is very superficial. When you dwell upon to the nature of Java, you will find that it is not that simple as you expect.

你应该已经从上述的故事中对三者的历史有了大概的了解,尤其是SWT。现在你也许会觉得,IBM创建SWT 的理由是合理的而Swing应该沿用SWT采用的方式。这样的观点是片面的,当你深入了解到Java的本质之后,你会发现其实并不像你想象的那么简单。

Prerequisite先决条件

What is the essential feature of Java, which has influenced the decision in the toolkit design? Or what is the prerequisite of a java GUI toolkit?

什么才是Java本质的,影响到工具集设计的特征呢?或者说,什么才是Java GUI工具集设计的先决条件呢?

The answer comes from one of Sun's promises about Java, write once, run anywhere. It is one of the java's advantages over other languages. Before Java was created, software portability was a nightmare especially to those who wanted to support multiple platforms. It is especially true in modern days when the Internet is so popular. People from different parts of the world are working on different platforms. And it is very common for a software vendor to support multiple operating systems. Java’s write-once-run-anywhere promise was obvious a relief to developers. It can greatly improve software development productivity.

答案来自于Sun对Java的承诺之一:write once, run anywhere(一次编写,随处运行)。这是Java不同于其他语言的优势所在。在Java被创建之前,软件的跨平台性能是开发者,特别是那些希望对多平台提供支持的开发者的梦魇。在当今的生活中Internet的使用已经相当的普遍了,在世界不同角落的人们在不同的平台上工作着。软件提供商为不同的操作系统提供支持是再平凡不过的事情。Java的

write-once-run-anywhere(WORA)承诺显然减轻了开发者的负担,极大地提高了软件开发的生产力。

However to write a portable applications, you should use those standard libraries, which provide platform-independent APIs. These standard libraries include language support, common utilities, networking, I/O and GUI toolkit, etc. So when Sun started to design the GUI toolkit, the first thing it should consider is a well-designed platform-independent API. AWT and Swing were designed carefully in such a way to avoid platform incompatibility. SWT on the contrary was initially designed without this portability in mind. It was first designed for an IDE, Visual Age for Java. And at that time, it seemed that Windows was their first priority. Therefore SWT API is more akin those of Windows. In general SWT is not as portable as Swing. Although Steve Northover, the father of SWT, argued that SWT is platform independent, you can easily find many Windows API inheritances.

然而编写跨平台的应用程序,你必须使用支持平台无关性的标准库。这些标准库包括语言支持,公共用途,网络,I/O和GUI工具集等。所以当Sun开始设计GUI工具集的时候,首要任务就是考虑一个设计良好的

平台无关的API。AWT和Swing都被小心地设计以保证平台兼容性。SWT则相反,它在设计之初并不以扩展性为原则,它为一个专有的IDE Visual Age for Java而设计,Windows作为这个IDE的首选运行环境拥

有很高的优先级考量。SWT API类似于WIndows,通常它并不如Swing的扩展性好,尽管Steve Northover,SWT之父,辩称SWT是平台无关的,你可以很容易地发现许多Windows API的痕迹。[Windows API的痕迹,并不是一个程序的问题,却是一个跨平台程序的问题,因为多数用linux或mac的人,对Windows上能提

供的东西并不感兴趣。]

Differences区别

GUI application is one of the major types of softwares. So Java GUI library should be standardized and integrated into the JRE platform. However different operating systems have different GUI styles and component sets. There are some components which exist on all the platforms and have similar look and feels. These common components such as button, label, textfield, checkbox, etc

are also called standard components. Different gui toolkits provide different set of components. Same component from different toolkits may have different look and feel. GUI toolkit usually follows different principle when choosing component types and features to implement. When examining a gui toolkit, we generally have two different levels of concerns. One is component types, the other is component features.

GUI应用程序是软件的一种主要类型,所以Java的GUI库应该是标准化并被集成到JRE平台中的。然而不同的操作系统有不同的GUi风格和组件集。有一些组件在所以平台上有相似的观感。这些共有组件如按钮,标签,文本域,单选框等被称为标准组件。不同的GUI工具集提供了不同的组件集。GUI工具集总是遵循不同的原则来选择组件类型和特征以实现。考察一个工具集,有两个不同的要素:组件类型和组件特征。

Terms

First let me illustrate two mathematical concepts to you: LCD and . LCD means least common denominator. means greatest common denominator. Look at the figure below. There are three different sets standing for different Oses. The intersecting part is LCD of the three, while the union is of the three.

首先让我图解两个数学概念:最大公约数和最小公倍数。如下图,三个集合代表不同的操作系统。相交的部分是最大公约数,合并的部分是最小公倍数。

Component Types and Features组件类型和特征

Now let’s examine the component types and features of the three Java GUI toolkits, AWT, SWT and Swing.

现在让我们来考察Java GUI工具集AWT,SWT和Swing的组件类型和特征

AWT

AWT component set complies LCD principle, which means AWT only has the common set of components which exist on all platforms. So you cannot find advanced components such as table or tree in AWT, because these components are not supported on some other platforms. As to feature set per component, AWT complies LCD too. It can only support those features available from all platforms. For example, AWT buttons is not able to be attached with an icon, because on Motif platform, button is not supposed to have an icon.

AWT组件集遵循最大公约数原则,即AWT只拥有所有平台上都存在的组件的公有集合。所以你在AWT中无法获取如表或树等高级组件,因为它们在某些平台上不支持。AWT的组件特征同样遵循这一原则。它只提高平台上公有的特征。例如AWT按钮不能附着图片,因为在Motif平台上,按钮是不支持图片的。

Since its poor component and feature support, AWT did not attract developers much. And it is deprecated by Sun. It is only there to ensure backward compatibility and support Swing.

由于它低劣的组件集和特征,AWT无法吸引开发者。它是Sun不推荐使用的,只是为了确保向下兼容和支持Swing。

SWT

One of SWT’s initial goal is to provide a more rich component set than AWT. It adopts (greatest common denominator) principle to provide a union set of components that appear on every platform. The idea is that if a component type exists on the platform, then SWT will encapsulate it using java code and JNI call. If a component does not exist on the platform, it then emulates the component by extending and drawing a Composite. A SWT Composite is similar to AWT Canvas. By this way, SWT provides a richer component set than AWT. It is worth to point out that SWT JNI wrapper is different from AWT. Its emulation is also different from Swing.

SWT最初的目标之一是为了提供比AWT更为丰富的组件集。它遵循最小公倍数原则以提供一个各个平台上包含的组件的并集。思路是如果一个组件在某个平台上包含,那么SWT就会包装它并用java代码和JNI来调用它。如果一个组件在某一平台上不存在,它就会用继承并绘制Composite的方式来模拟组件。一个SWT Composite类似于AWT的Canvas。以这种方式,SWT提供了较AWT更为丰富的组件集。值得指出的是SWT

的JNI封装不同于AWT,它的模拟也不同于Swing。

As to component feature set, SWT is similar to AWT. They complies to LCD. In early SWT versions, SWT button did not support icon attachment for the same reason as AWT. But later, many of those missing features were made up using emulations. But still, there are features which cannot be implemented purely by emulation. SWT has its components completely controlled native operating system. It is hard to extend. Only features like some graphic decoration can customized by emulating. So strictly speaking, SWT component feature set can not be as rich as Swing due to its difficult to extend.

在组件特征方面,SWT类似于AWT。它遵循最大公约数原则。在早期的SWT版本中,SWT按钮因为和AWT同样的原因不支持附着图片。在之后的版本中,许多缺失的特征采用模拟的方式补全。但仍有许多特征无法采用纯粹的模拟实现。SWT将组件的控制交给本地操作系统。它难以扩展。只有例如图形装饰等特征可以借助模拟绘制来自定义实现。所以严格意义上将,SWT组件的组件集和特征因其难于扩展而不如Swing来得丰富。

Swing

Swing is the most powerful and flexible of the three. With respect to component types, Swing complies to greatest common denominator. Because Swing controls all of the GUI system and it is very extensible and flexible, Swing can almost create any component you could imagine. The only limitation of Swing is its AWT containers. In Swing you still can not implement real transparent or irregular-shaped windows, because Swing depends on those AWT top containers including Applet, Window, Frame and Dialog etc. Except these niches, Swing has implemented almost all the standard components on every platform.

Swing是三者中最强大和灵活的。在组件类型上,它遵循最小公约数原则。由于Swing可以控制自身GUI 系统的全部并有很好的可扩展和灵活性,它几乎可以创建所有你想象得到的组件。唯一的限制是它的AWT 容器。在Swing中你还不能跨平台地实现真正的透明化和不规则矩形窗口,因为Swing依赖于AWT顶层容器例如Applet, Window, Frame and Dialog等。除此之外,Swing几乎实现了所有平台上的标准组件。[都说Java7中能够实现,也有一些迹象看来接近,期待吧]

As to component feature set, Swing complies to greatest common denominator. It has most of the component features available on every platform. What's more, you can extend the existing Swing components and add more features to them.

在组件特征上,Swing遵循最小公倍数原则。它拥有所有平台上可提供的组件特征。不仅如此,你还可以继承已有的Swing组件并添加新的特性。

Implementations

The above comparison is mainly conducted in API level. Let's continue the comparison with focus on implementation details. In all the difference between Swing and SWT/AWT is that Swing is purely implemented in Java, while SWT and AWT is a mixture of Java and JNI. Of course, their target is

same, to provide a cross-platform APIs. However to achieve this, SWT and AWT has to sacrifice some components and some features so that they can provide a universal APIs.

上一篇的比较主要是在API级别上的。让我们将比较的焦点转移到实现细节上。Swing和SWT/AWT的区别是Swing是纯Java实现,而SWT和AWT是Java和JNI的混合。当然,它们的目标都是相同的,提供一个跨平台的APIs。然而为了达到这一点,SWT和AWT不得不牺牲一些组件和特性以提供一个通用的APIs。

AWT

An AWT component is usually a component class which holds a reference with a peer interface type. This reference points to a native peer implementation. Take https://www.wendangku.net/doc/1c15469123.html,bel for example, its peer interface is LabelPeer. LabelPeer is platform independent. On every platform, AWT provides different peer class which implements LabelPeer. On Windows, the peer class is WlabelPeer, which implement label functionalities by JNI calls. These JNI methods are coded in C or C++. They do the actual work, interacting with a native label. Let's look at the figure. You can see that AWT components provide a universal public API to the application by AWT component class and AWT peers.

A component class and its peer interface are identical across platform. Those underlying peer classes and JNI codes are different.

一个AWT组件通常是一个包含了对等体接口类型引用的组件类。这个引用指向本地对等体实现。举

https://www.wendangku.net/doc/1c15469123.html,bel为例,它的对等体接口是LabelPeer。LabelPeer是平台无关的。在不同平台上,AWT提供不同的对等体类来实现LabelPeer。在Windows上,对等体类是WlabelPeer,它调用JNI来实现label的功能。这些JNI方法用C或C++编写。它们关联一个本地的label,真正的行为都在这里发生。作为整体,AWT组件由AWT组件类和AWT对等体提供了一个全局公用的API给应用程序使用。一个组件类和它的对等体接口是平台无关的。底层的对等体类和JNI代码是平台相关的。

SWT

SWT implementation also utilize JNI methodology. But the detail is different from that of AWT. SWT evangelists often became furious when they heard people describing SWT as another AWT. Steve Northover, the father of SWT, once complained about this.

SWT也使用JNI的方法论来实现。但细节不同于AWT。SWT的拥护者听到人们拿SWT和AWT相提并论可是会很生气的,Steve Northover,SWT之父,就曾为此抱怨过。

Yes, they are different. Let's delve into SWT code. In SWT, the only identical part on every platform is the component interface. That is class and method definition signature. All the underlying codes are different from platform to platform. SWT provides an OS class for every platform. This class encapsulates many native APIs by JNI methods. And then SWT component class glues these JNI method together to provide a meaning functionality.

没错,它们是不同的。让我们深究SWT的代码。在SWT中,各个平台上唯一相同的部分是组件的接口,是类和方法的定义签名。所有的底层代码都是平台差异的。SWT为每个平台提供了OS类。这个类用JNI封装了许多本地APIs。SWT组件类通过把这些JNI方法黏合在一起提供一个有意义的功能。

For example, on Windows, text field selection can be conducted by only one system call. This system call is implemented in the Windows OS class as an native method. So there is only one JNI call in the setSelection method of Text on Windows.

例如,在Windows上,文本域的选择是由一个系统调用处理的。这个系统调用在Windows的OS类中作为一个本地方法实现。所以在Windows平台的Text的setSelection方法中只用到了一个JNI调用。

However, on motif platform, text selection involves two native calls. Again SWT implements these two calls in the motif OS class. So the component class on motif needs to call these two calls to achieve text selection.

然而,在motif上,文本域的选择包含两个本地调用。SWT就在motif的OS类中实现了两个调用。所以在motif上组件类需要作两次调用来实现文本的选择。

By now, you can see the major difference between SWT and AWT is that they use different peer code to wipe out the differences. SWT uses java code, or java peer to glue system calls implemented by JNI. However, AWT put these code in native peers, which complicates the situation. I think SWT's method is more clever.

现在你应该能看出SWT和AWT的最大不同了,它们使用了不同的对等体编程方式来消除平台差异。SWT用java代码或有JNI实现的java对等体来黏合系统调用。而AWT把代码包含在对等体中,使情况复杂化了,

我个人觉得SWT的方法更加明智。[是否我翻译有问题,因为我并不觉得是这样更明智,SWT的无则模拟是不必要的,这是使用者才去做的事,SWT作为提供者应该无则C++实现,当然实现的是最核心的高度复用的又或者需要极大性能支持的,毕竟带了动态链接库,索性多放点东西。]

Swing

When it comes to Swing, everything becomes clear and straight forward. Except the top containers, Swing implementation depends on nothing of individual platform. It has all the controls and resources. What Swing needs is event inputs to drive the system, and graphics, fonts and colors which are inherited from the top AWT containers. Ordinary Swing components can be seen as a logical area on AWT containers. They do not have a peer registered. All swing components added to a same top container share its AWT peer to acquire system resources, such as font, graphics etc. Swing has its own component data structure stored in JVM space. It manages drawing process, event dispatching and component layout totally by itself.

到了Swing这里,一切就变得清晰和直接了。除了顶层容器,Swing的实现不依赖于具体平台。它掌管了所有的控制和资源。Swing所需要的是事件输入来驱动系统,以及承接自顶层AWT容器的图形处理,字体和颜色。普通的Swing组件可以看作是AWT容器的一块逻辑区域。它们并没有注册对等体。所有添加到同一顶层容器的Swing组件共享它的AWT对等体以获取系统资源,如字体,图形处理等。Swing将组件自己的数据结构存储在JVM的空间中。它完全由自己管理画图处理,事件分发和组件布局。

Resource Management

Because both AWT and SWT holds reference to native components, they must release them in a correct manner to avoid memory leaks and JVM crashes. AWT takes most of the resource management task to the system, relieving developers from tedious resource management. However this complicates the AWT implementation. Once it is implemented, developers has less opportunities to make errors and crash their applications.

由于AWT和SWT都持有对本地组件的引用,它们必须以正确的方式释放这些引用以避免内存泄露和JVM崩溃。AWT将绝大多数资源管理任务交给系统,将开发者从单调乏味的资源管理中解救出来。然而这使得AWT 的实现复杂化了。一旦它实现了,开发者很少有机会犯错误并使他们的程序崩溃。

SWT follows another way. In essence, SWT let the developers to manage those resources by themselves. There's a famous rule there. That is those who create the component should release it as well. Thus developers have to explicitly and carefully call the dispose method on every component or resource he has created. This greatly simplifies the SWT implementation model. But it puts the developers at the risk that they might easily crash their applications due to incorrect coding.

SWT用的是另一种方法。大体上,SWT让开发者自己来管理资源。它的一条著名的规则是:谁创建,谁释放。因此开发者必须谨慎地显式调用dispose方法释放每一个由他创建的组件和资源。这简化了SWT的实现模型,但把开发者摆在了因错误编码而易于造成程序崩溃这一风险之上。

Emulation difference模拟方式的区别

Both Swing and SWT uses emulation in their implementation. SWT emulate those components which are missing from one platform. The difference is that SWT's emulation is much more like those of AWT Canvas. SWT has a Composite class which has a counterpart peer in the operating system. It gets all the resources it needs such as graphics object, font or color from its own peer. It gets all the events directly from the operating systems process it. However, swing component does not have a counterpart peer. It is only logical area of the top container. The resources it acquires from itself are in fact borrowed from those top containers' peer. As to event, swing event is not the event generated from the underlying system. It is in fact a pseudo event which is generated when the top container processes AWT event. We'll detail it later in the event parts.

Swing和SWT在它们的实现上都使用了模拟。SWT只模拟平台上缺失的组件。区别是SWT的模拟更像是AWT 的Canvas实现的模拟。SWT的Composite类有它自己在操作系统中相应的对等体。它从自己的对等体中获得所有它所需要的资源如图形处理的对象,字体和颜色等。它直接从操作系统获取所有的事件并进行处理。然而,Swing组件在操作系统中没有相应的对等体。它只是一块顶层容器中的逻辑区域,实际上它从顶层

容器的对等体中借用资源。Swing的事件并不是底层系统产生的事件。它们实际是由顶层容器处理AWT事

件所产生的伪事件。我们会在稍后的事件部分中详细介绍它。

Graphical Layer Architecture图形层结构

The other difference is that swing components have its own separate z-order system from AWT components. As I mentioned above, swing components share a same peer with the top AWT container. Therefore, swing components have same z-order with the top container. SWT and AWT components each have a different z-order from the top container. So if AWT components and Swing components are mixed together, Swing components will probably be hidden by AWT components, because z-order values of AWT components are higher than the top container, while Swing components have the same z-order value with the top container. When operating system begin to update the UI, top container and swing components are always painted earlier than those of AWT. When they finished painting, AWT components will wipe out what swing has painted. So it is not encouraged to mix swing and AWT components together. If there are floating swing components such as menu, AWT component probably can hide menus.

另一个不同之处是Swing组件的z-order系统是来自于AWT组件的。如上所述,Swing组件与顶层AWT容

器共享一个对等体。因此,Swing组件也和顶层容器有相同的z-order。SWT和AWT组件都有不同于顶层容

器的z-order,通常是高于顶层容器。故而如果AWT组件和Swing组件混合在一起的话,Swing组件将可能被AWT组件遮住。当操作系统开始更新UI的时候,顶层容器和Swing组件总是先于AWT组件绘制。当它们

完成绘制,AWT组件会覆盖Swing可能绘制过的地方。因此不提倡Swing和AWT组件的混用。如果有一个浮动的Swing组件如菜单,AWT组件很可能遮盖菜单。

Layout Manager布局管理器

Not all of the elements of the three are different. Layout manager is an exception. What is layout manager? When developing a gui application, developers need to re-position or resize components when the container is resized. In traditional language, this is usually achieved by listening to resizing events. The code snippets usually scattered around and mess up the code. Java introduces the idea of wrapping layout codes together and name it Layout Manager. When a layout manager object is set to the container, it is automatically connected to resizing events. When resizing happens, layout method of the manger is called to re-position or reshape its children components.

并不是三者中的所有部分都是不同的。布局管理器是一个例外。开发GUI应用程序,当容器改变大小的时候,组件需要重定位或改变大小。在传统的编程语言中,这依靠监听大小改变的事件来实现。相应的片段散落在源代码的各个角落降低了程序的可读性。Java引入了将布局代码封装的思路,称之为布局管理器。当布局管理器对象被设置到一个容器中,它自动处理大小改变的事件。当大小改变时,管理器的布局方法被调用以重定位子组件或调整它们的形状。

AWT, SWT and Swing agree on this infrastructure. However every one has its own specific layout managers. Because AWT and Swing share a common parent class https://www.wendangku.net/doc/1c15469123.html,ponent, therefore AWT and Swing layout manger can work interchangeably.

AWT,SWT和Swing都以这样的方式来组织,而都有它们各种独特的布局管理器。由于AWT和Swing拥有一个共同的超类https://www.wendangku.net/doc/1c15469123.html,ponent,它们的布局管理器可以交替地使用。

Look And Feel观感

Native toolkits including SWT and AWT do not support Look And Feel mechanism. They bind their components to operating systems, which have both pros and cons. One of the cons is that they cannot support pluggable Look And Feel. Handling the drawing process to operating system deprives of their ability to customize component look and feel. This prevent them from providing Look And Feel mechanism. Look And Feel mechanism is becoming more and more indispensable in GUI toolkit.

包括SWT和AWT在内的本地工具集并不支持Look And Feel机制。它们将组件捆绑在操作系统上,有其优势和劣势。其中的一个劣势是它们不支持可插拔的Look And Feel。将绘制处理交由操作系统完成剥夺了

它们实现自定义组件Look And Feel的能力,也就使得它们无法提供这种机制。Look And Feel机制越来

越成为GUI工具集中不可缺少的一部分。

Swing has wonderful Look And Feel support. You can even change Swing application's look and feel dynamically. This is an insurmountable task for AWT and SWT, since they handle their control entirely to operating system. I've heard many people complains about Sun on Swing design. They think why Swing can not be built on SWT like AWT. In fact, Look And Feel mechanism is one of reason why Swing should go in that direction. If Swing follows the way that wrapping existing components and emulating non-existing components, it cannot provide Look And Feel mechanism. Providing pluggable Look and Feel mechanism is an insurmountable task to native strategy.

Swing拥有很好的Look And Feel支持。你甚至可以动态地改变Swing应用程序的Look And Feel,鉴于AWT和SWT将组件控制完全交给操作系统处理,这是它们所无法超越的任务。我曾经听很多人抱怨过Sun

在Swing上的设计。他们觉得Swing为什么不像SWT那样沿用AWT的思路呢?事实上,Look And Feel机

制正是Swing走到这个方向上的原因之一。如果Swing遵循的是包装已有的组件并模拟不存在的组件的路线,那它就无法提供Look And Feel机制。因为提供Look And Feel机制是本地策略所无法完成的任务。

Graphics and Fonts图形和字体

Since Swing is an emulated system, its graphics tools is much more powerful than those of AWT and SWT. Swing bases its whole system on two fundamental components, one is Java 2D and the other is AWT. Java 2D is a powerful library in Java. It provides rich features of advanced image processing, color management, graphical drawing and filling, coordination system transmission and font manipulations. AWT and SWT only provides limited access to these features. Compared to Java 2D, they are comparably primitive and inferior.

Swing作为一个仿生系统,它的图形工具集较之AWT和SWT强大许多。Swing基于其自身系统中的两个基础组件群:Java 2D和AWT。Java 2D在Java中是强大的类库,它为高级图像处理,颜色管理,图形绘制和

填充,坐标系变换和字体生成提供丰富的特性。相较之下,AWT和AWT仅对这些特性提供有限访问,它们

是相对原始和低级的。

JavaBeans Specification Conformity JavaBeans规范一致性

Swing and AWT was designed with JavaBeans specification in mind. So their component classes conform to JavaBeans specification. However SWT does not quite conforms to this specification. For example,

there's no empty-argument constructor in every component classes. Every component in SWT must has at least a single parameter constructor. This parameter is the parent of the components. That means whenever a component is created, it must be immediately added to a component tree. A component cannot exist without registered native peer. By this way, SWT wants the components created by programmer can be automatically released when dispose methods of display is called.

Swing和AWT在设计之初就秉承了JavaBeans规范,它们的组件类与JavaBeans规范一致。然而SWT并没有很好的遵循这一规范。例如,在SWT的组件类中没有无参的构造器。每个组件都必须至少拥有一个单参数的构造器。这个参数就是父组件的引用。这意味着无论何时组件被创建,它都直接被添加到一棵组件树中。一个组件无法脱离于已注册的本地对等体而存在。这样,SWT就能让由编程者创建的组件在display

的dispose方法被调用的时候自动被释放。

More on Resource Management更多在资源管理方面的内容

SWT's strategy of component constructor can eliminate some possibility of memory leaks. AWT has the similar question about resource management. But it resolve the issues using a different way. When an AWT component is created, the counterpart peer will not immediately be added. When it is added to a component tree, but the tree is not visible yet, the peer will be still not created. Only when top container is set visible, will these peers be created. The method creating the peer generally is located in addNotify method. They generally call their parent's addNotify recursively until all of the peers on the component tree are created. When top container is dismissed by calling dispose method, a reverse method removeNotify will be called recursively to release these peers. By this way, AWT manage its resource without any interference from the developers.

SWT的组件构造器策略可以排除某些内存泄露的可能性。AWT在资源管理方面也有类似的问题。但它采用了不同的方式解决。当AWT组件被创建的时候,相应的对等体并不会立即被创建。即便它被添加到一棵组件树,而如果这棵树还不可见,那么对等体仍不会被创建。只有当顶层容器被设为可见,这些对等体才会被创建。创建对等体的方法通常在addNotify中,它们通常递归地调用父组件的addNotify直到整棵组件树上的对等体都被创建了。当顶层容器由dispose方法销毁的时候,一个对应的方法removeNotify将会被递归地调用以释放这些对等体。这样,AWT在不由开发者介入的情况下管理了它的资源。

Event System事件系统

An event is the message sent to a GUI system, either from the outside or from the system itself, which requires certain action to be taken. These events include I/O interrupts from computer devices such as mouse or keyboard or network ports, and logical events triggered by GUI system, such as ActionEvent posted by a button.

一个事件要求特定的动作被执行,它被作为消息由外界或系统自身发送给GUI系统。这些事件包括来自计算机设备如鼠标键盘和网络端口的I/O中断,以及GUI系统的逻辑事件触发,比如一个按钮的ActionEvent 事件。

Single-Threaded vs Multiple-Threaded 单线程 vs 多线程

Dispatching events can follow two different models. One is called single-threaded dispatching model and the other multiple-threaded dispatching model.

事件分发遵循两种不同的模型。单线程分发模型和多线程分发模型。

In single-threaded dispatching model, an event is pumped from the queue and processed in the same thread immediately. After the event being processed, next pending event in the queue is pumped again and continues the next round of cycle. In multiple-threaded dispatching model, the thread

fetching the events from the queue launches another thread called task thread, and hand the event over to it for processing. The thread responsible for fetching the event does not wait for the end of the processing thread. It simply goes on to fetch next pending event and dispatch it.

在单线程分发模型中,一个事件从队列中抽出并在同一个线程中被立即处理。事件处理后,队紧跟着的下一个事件再被抽出并继续下一轮的循环。在多线程分发模型中,从队列中获取事件的线程启动另一个被称作任务线程的线程,并把事件交给它处理。而获取事件的线程并不等待处理线程的结束。它简单的获取下一个线程并分发它。

Event processing usually involves changing application data. While these data are often the source data that components display. Multiple-threaded dispatching can easily raise synchronization issues. It generates multiple event processing threads, which might interfere with each other. In a stable GUI system, component should be able to keep the view synchronized with the model. Because of the synchronization issue, multiple-threaded model requires developers to be more experienced in concurrent programing. For ordinary programmers, it is very easy to make synchronization errors. Therefore many GUI system don't use this model.

事件处理通常涉及应用程序的数据变化。而且这些数据经常是组件需要显示的。多线程分发很容易产生同步问题,它产生多个可能互相干扰的事件处理线程。在一个稳定的GUI系统中,组件应该能够保持视图与模型间的同步。由于同步问题的出现,多线程模型要求开发者拥有更多并发编程的经验。而对于普通编程人员,造成同步错误是很容易的。因此许多GUI系统并不使用这一模型。

Single-threaded model provide natural synchronizations by enforcing sequential event processing. AWT, SWT and Swing all use this model to dispatch events. But single-threaded model also has its own issues. One of them is thread engrossment. Since all events are dispatched by a single thread, if one event processing last too long, it will hold back pending events from being processed. If there are PAINT event holding back, then the screen will appear to be unresponsive. This usually make user feel that the software is slow. There are many such slow applications that are programmed by inexperienced developers. What they did is most probably cramming a listener method with time-consuming tasks. Swing is especially prominent, since it is widely used. This has brought swing a bad reputation of slow and ugly. In fact, swing application can be very responsive if you knows to thread.

单线程模型通过强制事件序列化地被处理提供了实际上的同步。AWT,SWT和Swing 都采用了这一模型来分发事件。但单线程模型也会有它自己的问题。其中之一就是线程专注。既然所有的事件都在一个线程中被分发,如果其中的一个事件的处理费时过久,将会拖延下一个事件的抽取和执行。如果有一个PAINT事件被延后,那么在屏幕上就会呈现为无法响应。这经常使用户感觉到软件很慢。许多这样的低效程序是由于开发者的经验不足造成的。他们的做法是将耗时任务填充到监听器方法中。由于这种错误的编程方式在Swing中大量被使用而尤为突出,这也是它慢而丑陋的坏名声的由来之一。实际上,如果你懂得使用线程,Swing应用程序可以表现出很高的响应度。[没错,三者在gui上都是典型的单线程事件分发模式,如果你了解操作系统和编程语言的实现细节,你就不会对此表现的诧异,因为单核中,多线程和多进程本质上也是单任务处理基础上的抽象。]

Thread Safety线程安全

The solution to the above issue is launching a separate worker thread to handle long-time processing, thus releasing the event dispatching thread to continue. Just like what

multiple-threaded model does. But that also invites the synchronization issues that happen in multiple-threaded model. Many GUI toolkits often setup some innate mechanism to avoid this, for example, by a complex lock on a component tree. Developers don't have to worry about how to program to be safe. This kind of toolkit is called thread-safe. AWT is one of them.

上述问题的解决方案是启动一个单独的工作者线程来完成耗时处理,这样就能把事件分发线程释放处理以继续运作。如果多线程模型中所做的那样,然而这同样会引入在多线程模型中出现的同步问题。许多GUI

工具集都有自己先天性的机制来解决这一问题,例如,在组件树上的组合锁。开发者不需要为如何安全编程而操心。这样的工具集被成为线程安全的。AWT就是其中之一。

However, it is often too complex to build such GUI system and usually it creates a lot overhead because of unnecessary synchronization. Therefore, Swing and SWT were designed to be thread unsafe. That means developers have to program carefully when they want to do multi-threading task. There is a little difference between SWT and Swing about runtime behavior towards thread safety. SWT always checks if the action modifying component takes place in the event dispatching thread. By this way, developers can find out the probable synchronization issues. Swing does not have. This is a shortage of Swing, which I think should not be so hard to implement.

然而,由于不必要的同步使得建立这样的GUI系统过于负责并造成了额外的开销。因此,Swing和SWT被

设计为非线程安全的,这意味着开发者必须谨慎地实现他们的多线程任务。SWT和Swing在运行时线程安

全行为上有一个小小的区别。SWT总是检查改变组件的操作是否在事件分发线程上执行。这样,开发者就

能够发现同步问题。而Swing不这样,这是Swing的一个不知之初,这其实并不难实现。[Swing似乎有相应的checkLock这样的方法,检查是否在事件分发线程上执行应该已经由Swing实现了,你不必显示调用它,因为你调用的每一个组件操作方法都首先要执行一遍它]

Event Dispatching Thread事件分发线程

AWT reads the primitive event from the operating systems and process them in java codes. AWT event dispatching thread is named as AWT-{OS}-Thread. This thread is launched implicitly by AWT system. When an AWT application launches, this thread starts in background, pumping and draining events from the operating systems. When logical events such button action is fired, it is passed over to action listeners registered on button. Developers can also listen to primitive events such as mouse, keyboard or paint event to write customized AWT components. This is generally done by extending AWT Canvas component. This component enables all of the available event happened on them, and by overriding the event processing method, you can implement a custom component.

AWT读取操作系统中的基本事件并在java代码中处理它们。AWT事件分发线程被命名为 AWT-{OS}-Thread。这个线程由AWT系统隐式启动。当AWT应用程序启动时,这个线程在背后启动,在操作系统上抽取和移除事件。当诸如按钮动作这样的逻辑事件被触发时,它传递给注册在按钮上的操作监听器。开发者也能为AWT 组件编写鼠标,键盘和绘制事件的事件监听器。这通常通过扩展AWT Canvas组件来完成。这一组件支持了所有已提供的事件,而且你可以通过重写事件处理方法,实现一个自定义的组件。

However, in Swing, this is a different thread. Swing takes AWT events as the input of its event system. It gets AWT events and after some initial processing, generate a swing counterpart event and put it into its own event queue. Swing has own dispatching thread, usually named EventQueue-0. This thread pump swing events from the event queue, just as AWT does from the operating system. Then it dispatches this event to the target components. Usually an event is first post to the top container components. This event is then processed by the top container's dispatch methods.

Then it may re-dispatching or re-targeting this event to a swing component, which in turn continues the processing by its listeners.

然而,在Swing中,这是一个不同的线程。Swing把AWT事件作为自身事件系统的一个输入。它获取AWT

事件并做一些初始化处理,产生一个对应的Swing事件并把它放到自己的事件队列上。Swing也有自己的事件分发线程,通常命名为EventQueue-0。这个线程从事件队列中抽取Swing事件,就如同AWT从操作系统中抽取那样。然后它把事件分发给目标组件。通常事件首先被分发给组件的顶层容器,然后由顶层容器的dispatch方法处理,它可能被再分发或重定向到一个Swing组件,在那里继续由自己的监听器进行处理。

For example, when a mouse moves over a Jbutton on a Jframe, an AWT event targeting Jframe is fired to the AWT-thread. The AWT-thread checks to see if it needs further processing. Then it wraps the event into a Swing MouseEvent object and enqueue it into the EventQueue. Upon receiving the MouseEvent, EventQueue-0 pumps this event out and dispatch it to Jframe by calling its.dispatching method. This method then translate MouseEvent and figure out the target Swing component. Here, the component is Jbutton. After that, it created a new MouseEvent with the new coordinations and event source re-target to the Jbutton. After that, it calls the jbutton.dispatch to continue dispatching. Jbutton.dispatch filters these event to a specific method and finally hit the point where it is dispatched to specific mouse listener.

例如,当一个鼠标移过一个JButton或JFrame时,一个指向JFrame的AWT事件在AWT线程上触发。AWT 线程检查它是否需要作更多的处理,然后把它包装成一个Swing的MouseEvent对象并把它添加到EventQueue队列中。当获得MouseEvent事件后,EventQueue-0抽取这个事件并判断出目标Swing组件。这里,这个组件是JButton。然后它产生了一个包含相对坐标位置和事件源的新的MouseEvent重定向到这个JButton上,然后调用这个JButton的dispatch以继续分发。JButton的dispatch过滤事件给特定的方法最终实现由鼠标监听器在该点上的分发的点击。

SWT is more akin to AWT. The only difference is that it requires the developers to explicitly write the event looping codes. However, the underneath implementation is different from that of AWT. Look at the code that SWT read and dispatching events, it reminds you MFC code style.

SWT更类似于AWT。唯一的区别是它要求开发者显式地书写事件循环代码。然而底层的实现细节是不同于AWT的。看看SWT的读取和分发事件代码,它会让你想起MFC的代码风格。

Event Listener事件监听器

AWT, SWT and Swing have similar event listener models. They all use observer pattern, in which, components and listeners are connected by adding listeners to components. This model forms a object-net model as shown in the following figure. When an event is fired and transmitted to the component by dispatching, the component call its listeners to process this event. A listener can also further dispatching this event after processing, or it can event generate a new event and broadcast it to other nodes of the net. Basically there are two different way of broadcasting events. One is synchronously calling other listeners. The other is asynchronously posting this event to the queue, where it can get dispatched during next round of event dispatching.

AWT,SWT和Swing都有相似的事件监听器模型。它们都使用观察者模式,组件和监听器的连接方式是把监听器添加到组件上,这组成了一个对象网络的模型。当事件被触发并分发给组件,组件调用它的监听器以处理事件。一个监听器也可以继续分发事件给后续的处理,或产生一个新的事件并把它广播到网络中的其他节点上。基本上有两种不同的广播事件方式。一种是同步调用监听器。另一种是异步地将事件发送回队列,它将在新一轮的事件分发中被分发出去。

Besides post method, Swing has some other way of dispatching asynchronous event. One of them is invokeLater from SwingUtilities or EventQueue. This method can wrap a Runnable object into a event and post it into the event queue. This ensures the run method of Runnable can be executed on the event dispatching thread, enabling thread-safety operation. In fact, Swing Timer and SwingWorker is implemented based on this mechanism. SWT also has this counterpart utilities which can asynchronously post events. Its invokeLater counterpart is display.asyncExec which takes a Runnable object as parameter.

除了直接发送给队列的方式,Swing还有一些其他的分发异步事件的方法。其中之一是调用SwingUtilities 或EventQueue 的invokeLater,这一方法包装一个Runnable对象到事件中并把它发送给事件队列。这确保了Runnable的run方法能在事件分发线程上执行,保证了线程安全。实际上,Swing的Timer好SwingWorker基于这一机制实现。SWT也有相应的发送异步事件的方式。它的invokeLater的对应方法是display.asyncExec,它以一个Runnable对象作为参数。

Pros & Cons

To conclude the article, I'll give a list of pros & cons for each of them from a technical perspective.

我从一个技术层面给出了他们优劣势上的一个清单,以结束本文。

AWT

AWT is a deprecated toolkit by Sun. However, it does has advantage. In many areas other than desktop environment such as mobile or embedded device, AWT has many advantages.

AWT是Sun不推荐使用的工具集。然而它在许多非桌面环境如移动或嵌入式设备中有着自己的优势。[SWT 因相同的理由在mobile环境中也具有优势,那Android呢。Java是世界上用得最广泛的编程语言,然而分裂和变异是生命体进化的必然,java guys,你准备好面对即将到来的一切了吗?]

Less memory. Therefore it is suitable for developing GUI application which runs in an limited environment, for example, mobile phone and so on.

更少的内存。它对运行在有限环境中的GUI程序的开发,是合适的。

1.Less startup time. Because AWT components are native components which are implemented

by the operating system, most of the binary codes can be loaded in advanced, for example, when operating system starts. This can help to reduce AWT application startup time.

2.More responsive, Because native components are rendered by operating systems.

3.Standard GUI toolkit supported by JRE since java 1.x time. You don't have to install them

separately. You don't have to worry about platform differences.

4.Mature and stable. Seldom will it crash you applications and it just works.

1. 更少的启动事件。由于AWT组件是本地由操作系统实现的。绝大多数的二进制代码已经在如系统启动的时候被预装载了,这降低了它的启动事件。

2. 更好的响应。由于本地组件由操作系统渲染。

3. 从java 1.x时代就为JRE支持的标准GUI工具集,你不用单独安装它,你不用担心平台差异的问题。

4. 成熟稳定的。它能够正常工作并很少使你的程序崩溃。

However, everything has its own Achilles heel. Let's enumerate them:

然而,事物都有它们不好的一面。让我们来例数它吧。

1.Less component types. Table and tree are very important components missing. while table

and tree are very commonly used components in desktop applications.

https://www.wendangku.net/doc/1c15469123.html,cking rich component feature. Its buttons cannot have icon attached. This is clearly

due to the fact, it is design according to principle.

3.No Look And Feel support. AWT is designed to use native components. Therefore, it depends

on the system to provide Look And Feel support. If there are no such support on the target platform, there's no way for AWT to change its look and feel.

4.Not extensible. AWT components are native components. The JVM instance of AWT classes

are in fact only references to the native components. The only extension point of AWT is its Canvas component, where you can create a custom component from scratch. However there's no way to extends and reuse an existing AWT component.

1. 更少的组件类型。表和树这些重要的组件缺失了。它们是桌面应用程序中普遍使用的。

2. 缺乏丰富的组件特征。按钮不支持图片附着。这很明显是它遵循的设计原则造成的。

3. 不支持Look And Feel。AWT被设计为使用本地组件。因此,它依赖系统来提供Look And Feel 支持。如果目标系统并不支持这一特性,那么AWT将无法改变它的Look And Feel。

4. 无扩展性。AWT的组件是本地组件。JVM中的AWT类实例实际只是包含本地组件的引用。唯一的扩展点是AWT的Canvas组件,你可以从零开始创建自定义组件。然而无法继承和重用一个已有的AWT组件。[SWT同样,extends在这里的使用确实不如Swing可以做到的事情多,但别忘了原生只是人们加给SWT的一个名字而已,它的姓是IBM]

SWT

SWT has the following advantages:

SWT有如下优势:

1.Rich component types. SWT provide a wide variety of components, from primitive components

such as Buttons and Labels to Tables and Trees.

2.Relative rich component feature. Although SWT is also designed following LCD principle,

it has been re-engineered to support more component features by emulations. So compared to AWT, it has relative more component features.

3.Better response time. Due to the same reason as AWT, SWT components are wrapped native

components, which are rendered by the operating system. Operating system can usually

跟我学Java Swing GUI组件技术及应用实例——JTable表格组件及应用实例

1.1跟我学Java Swing GUI组件技术及应用实例——JTable表格组件及应用实例 1.1.1表格控件JTable 1、JTable表格控件的主要功能 JTable顾名思义就是一个将数据以表格显示的组件,它提供以行和列的方式来显示数据,并且可以拖动列。如下示图为应用JTable表格控件所创建出的数据表格。 JTable的数据选项不仅仅是可以显示字符串,还可以显示Checkbox选择框、下拉列表框或者图片等内容。如下为Sun 公司的Swing 教程中的TableDialogEditoDemo 应用程序的执行结果示图,在该示例的数据表格中显示Checkbox选择框、下拉列表框和图片等内容。

2、JTable类的API功能说明 (1)JTable类的API功能说明 如下示图为JDK API文档中对JTable类的API功能说明的相关信息。 如果需要对数据表格中的表头数据列和数据单元格中的数据列进行定制,则需要通过继承封装表头数据列JTableHeader类或者继承封装数据列的TableColumn类。如下为JTableHeader类和TableColumn类的功能说明。 (2)表头数据列JTableHeader类的功能说明

(3)数据列TableColumn类的功能说明 TableColumn 类封装表示JTable中数据列的所有属性,如宽度、大小可调整性、最小和最大宽度。 3、JTable表格控件中的数据可以以多种不同的方式被选中 (1)选中某一数据行

(2)选中连续的多行数据行

(3)选中不连续的多行数据行

4、JTable类的构造函数定义 可以通过JTable(Object[][] rowData, Object[] columnNames)形式的构造方法创建出数据表格组件,该JTable组件将用来显示一个二维数组rowData 中的值(它是一个行数组),其列名称为columnNames所代表的数组。JTable类的其它形式的构造函数定义如下:

java_swing_入门教程

swing入门教程 swing简介(2009-04-20 23:52:40) U I组件简介 在开始学习Swing之前,必须回答针对真正初学者的一个问题:什么是UI?初学者的答案是“用户界面”。但是因为本教程的目标是要保证您不再只是个初学者,所以我们需要比这个定义更高级的定义。 所以,我再次提出这个问题:什么是UI?您可能把它定义成您按下的按钮、打字的地址栏、打开和关闭的窗口,等等,这些都是U I 的元素,但是除了在屏幕上看到的这些之外,还有更多都是U I 元素。比如鼠标、键盘、音量、屏幕颜色、使用的字体,以及一个对象相对于另一个对象的位置,这些都包含在U I 之中。实际上,在计算机和用户的交互之中扮演角色的任何对象都是U I 的组成部分。这看起来足够简单,但是您应当惊讶的是,有许多人和大型公司已经为它努力了很多年。实际上,现在有的大学专业的惟一课程就是研究这种交互。Swing的角色 Swing是Java平台的U I ——它充当处理用户和计算机之间全部交互的软件。它实际上充当用户和计算机内部之间的中间人。Swing 到底是如何做这项工作的呢?它提供了处理前面一节中描述的U I 各方面内容的机制: ?键盘:Swing 提供了捕捉用户输入的方法。 ?颜色:Swing 提供改变在屏幕上看到的颜色的方法。 ?打字的地址栏:Swing 提供了文本组件,处理所有普通任务。

音量:Swing 不太擅长。 无论如何,Swing为您提供了创建自己的U I 所需要的所有工具 MVC Swing甚至走得更远一步,在基本的U I 原则之上又放上了一个公共的设计模式。这个设计模式叫做模型-视图-控制器(Model-Vie w-Co ntroller,MVC),它试图“把角色分开”。MVC 让负责显示的代码、处理数据的代码、对交互进行响应并驱动变化的代码彼此分离。 有点迷惑?如果我为这个设计模式提供一个现实世界的非技术性示例,它就比较容易了。请想像一次时装秀。把秀场当成U I,假设服装就是数据,是展示给用户的计算机信息。现在,假设这次时装秀中只有一个人。这个人设计服装、修改服装、同时还在T 台上展示这些服装。这看起来可不是一个构造良好的或有效率的设计。 现在,假设同样的时装秀采用MVC 设计模式。这次不是一个人做每件事,而是将角色分开。时装模特(不要与MVC 缩写中的模型混淆)展示服装。他们扮演的角色是视图。他们知道展示服装(数据的)适当方法,但是根本不知道如何创建或设计服装。另一方面,时装设计师充当控制器。时装设计师对于如何在T 台上走秀没有概念,但他能创建和操纵服装。时装模特和设计师都能独立地处理服装,但都有自己的专业领域。 这就是MVC 设计模式背后的概念:让U I 的每个方面处理它擅长的工作。如果您仍然不明白,那么教程后面的示例有望消除您的迷惑——但是在您继续进行的时候,请记住基本的原则:用可视组件显示数据,同时让其他类操纵数据。

JAVA SWING 连接数据库的步骤

Java swing连接数据库的步骤 1.在工程中导入3个jar包,详见(导入Jar包的过程.doc) 2.在类中导入包 a)import java.sql.*; b)import com.microsoft.jdbc.sqlserver.*; 3.声明连接对象,执行语句对象,结果集对象 a)Connection conn=null; b)Statement stmt=null; c)ResultSet rs=null; 4.定义连接字符串 a)final String CLASSFORNAME="com.microsoft.jdbc.sqlserver.SQLServerDriver"; b)final String DBURL="jdbc:microsoft:sqlserver://127.0.0.1:1433;DataBaseName=pubs"; c)final String USER="sa"; d)final String PASS=""; 5.创建连接对象 try{ Class.forName(CLASSFORNAME); conn=DriverManager.getConnection(DBURL,USER,PASS); }catch(SQLException e){ System.out.println(e.getMessage()); }catch(ClassNotFoundException ex){ JOptionPane.showMessageDialog(this,"练苦失败"); return; }

6.创建执行语句对象stmt try{ String sql="insert into users values('name1','pass1')"; //上一行代码可以写成下一行的方式,试分析它的作用是什么? //String sql="insert into users values('"+name+"','"+pass+"')"; stmt=conn.createStatement(); stmt.executeUpdate(sql); }catch(SQLException ex1){ } 7.完毕

JavaSwing中处理各组件事件的一般步骤完整版

J a v a S w i n g中处理各组件事件的一般步骤 集团标准化办公室:[VV986T-J682P28-JP266L8-68PNN]

Java Swing中处理各组件事件的一般步骤是: 1.新建一个组件(如JButton)。 2.将该组件添加到相应的面板(如JPanel)。 3.注册监听器以监听事件源产生的事件(如通过ActionListener来响应用户点击按钮)。 4.定义处理事件的方法(如在ActionListener中的actionPerformed中定义相应方法)。 以上步骤我们可以用多种方法实现。但人们通常用二种方法。第一种方法是只利用一个监听器以及多个if语句来决定是哪个组件产生的事件;第二种方法是使用多个内部类来响应不同组件产生的各种事件,其具体实现又分两种方式,一种是匿名内部类,一种是一般内部类。 为了说明如何使用上述三种方法实现事件的处理方法,我们建立一个简单的应用程序。该程序界面有两个按钮,当用户点击相应的按钮,就会弹出一个对话框显示相应的内容。通过这个简单程序,你可以实现自己更多、更复杂的用户界面程序。 首先,我们利用单个监听器来实现该程序。我们定义一个名为Simple1的类来包括所有代码。所有的用户行为(如点击按钮)由一个监听器SimpleListenner中的actionPerformed方法来处理。以下是代码: import .*; import .*; public class Simple1 {

private static JFrame frame;dd(myPanel); (); (true); } } 让我们来看看以上代码是如何工作的。在main方法中,我们定义了一个JFrame,然后将面板Jpanel添加到窗体中,该面板包括两个按钮。相应的变量Frame,button1,button2定义在程序的开头部分。 在程序入口main方法中,首先新建Simple1组件,通过构造器建立用户GUI,定义一个面板Jpanle,,增加两个按钮,然后利用将两个按钮加入到一个活动监听器SimpleLister中,最后,两个按钮添加到面板。当GUI 建立后,我们将面板添加到窗体并显示结果。当用户点击按钮时,程序调用actionPerformed方法,通过if语句来判断是哪一个按钮被点击,然后在对话框中显示相应的内容。 利用一个监听器来处理事件的缺点是,当程序比较复杂时,需要一大串的if 语句来实现,程序代码较难阅读与维护。当然,如果处理的事件较少,这种方式比较简单。 通过使用匿名内部类可以解决上述存在的问题。使用简单的匿名内部类作为addActionListener的变量即可。以下是实现代码:

易经入门(最全解答)

易经入门(最全解答) 对于周易的迷途者,可能需要找些入门的书籍,建议。但是百度,网站等会经常变动,比如我之前找到一个周易入门的好网站,是从百度里面搜到的,过几天就搜不到了,后悔当时没有收藏网站,所以现在把之前积累的公布出来建议或书籍发布出来,大家收藏一下。 (1)这个比较全面客观的: 数目有很多,建议你你有整体的观念,这样会比较容易学。以下这段介绍,是我保存的,觉得很好,希望对你有用。 选书如选老师,因此选择书籍是一件十分重要的事。在此,向给大家推荐相关书籍,让你少走弯路,成为大师级高手! 重要叮嘱 易学、佛经是迷宫,进门后一定要学会出得了门。正如紫钦天老师在《太极博弈原理》里面“信息对抗:命越算越薄,知命与宿命”提到的,其实现在才最真实的,人要克服的是未来信息对现在的影响!很多人能懂一点点了,以为天下无敌,但是如果未来的信息,没有百分百准确,都是误导人的。最怕三分真,七分假。人依然会迷茫,犹豫,错失。 另外,易曰:知得也要知丧,当你得到了一些东西的时候,你也会失去一些东西。诚然,人生从某种意义上讲,没有绝对的好、坏、善、恶,而在于你的选择。为什么还要特别提醒呢?因在现实中接触不少易友,一学什么易或练什么功,就顾及不到其他方面,给家庭社会造成一些不好的影响。古曰:平常心是道!不要把自己标榜成与别人不一样,否则你会一事无成。要明白你只是一个凡人,不要以为自己学易了就有什么了不起。法、侣、财、地(简单讲就是方法、同道、财力、环境)是学好功法,其实也是学好易经的最好指导。千万不要指望学易来发大财,否则你将走上不归路。以此为职业的人,是有宿因的。薄迦梵歌曰:要把成与败、得于失等同看待。患得患失不是学易人应有的心态。好好工作,养家糊口,业余修习,平凡一生这是吾师给本人的开示和指导,希望易友也能从中得到启发! 最后以一句话与大家共勉:天行健,君子以自强不息;地势坤,君子以厚德载物!众善奉行,诸恶莫作最为紧要! 1、基础书 (1)周易原文注解类: 如果不读周易原文,而想彻底搞懂周易基本是不可能的,万丈高楼平地起,基础越牢,对后面的学习帮助越大。 建议采用中国易经协会会长、哲学教授刘大钧著的《周易概论》,其他如上海古籍出版社、商务印书馆等较大的出版社出版的《周易》都是比较可靠的。 南怀瑾老师倡导的儿童经典导读中心出版的原文《易经》,可以帮助大家认识和听懂一些难读的字。 (2)周易精华思想融汇类: 应该说,目前只有紫钦天老师的《太极博弈原理》一书能做到这点,全书中是没有解释卦象的。但是如果对于一个研究周易几十年的学者来说,一看这书,应该明白其实里面是是蕴含

跟我学Java入门到精通培训教程——利用Eclipse Swing可视化开发实现快闪屏

1.1利用Eclipse Swing可视化开发实现应用程序中的快闪屏 1、新建一个Swing JFrame(代表主窗口) (1)选择File>New>Other... 菜单,然后再选择MyEclipse>Swing>Matisse Form (2)点击Next按钮 输入包名称为com.px1987.javaapplication.swing.matisse,类名称为SplashMainFrame,并选择Swing JFrame类型。

(3)点击“Finish”按钮,将进入可视化设计器视图 2、设置SplashMainFrame窗口的属性 (1)取消标题条及控制按钮

将窗口的undecorated属性设置为true。 (2)不允许改变窗口的大小,设置resizeable为false。 3、定位及设置窗口的大小 在源代码视图中找到该窗口的构造方法,在其中的initComponents初始化函数后面添加如下的代码: public SplashMainFrame() { initComponents(); /** * 获取整个屏幕的尺寸大小 */ Dimension scmSize=Toolkit.getDefaultToolkit().getScreenSize(); /** * 背景大图像的宽和高 */ int nImageWidth=570; int nImageHeight=247;

/** * 设置快闪屏窗口的大小 */ setSize(nImageWidth,nImageHeight); /** * 设置快闪屏窗口在显示屏幕内的居中位置显示 */ setLocation(scmSize.width/2-nImageWidth/2, scmSize.height/2-nImageHeight/2); } 最后为如下的代码状态

太极化形

太极化形地理要诀 自序 且自孔子而后,斯文同骨肉,惟有地理不一家也,盖自古圣贤所创,阴阳五行,浑包天地万物,是有理而無形,理为一本,形为万殊,千变万化,甚难图也。而后世之人,遵圣道分其条目者,百家各有所师,惟有地理,無所遵者也,差错讹谬,背乎性理,此何故也?因古人草率無形,令人阅之不明,含渾無图,復行错认而不自知,故为细加搜剔,草率者详之,重复者删之,不足者补之,另行刻刊。使清纯不杂,庶地理异日可归於一家焉,况今清明二代,地理失传久矣,余作此书,遵沈公地学之形,绘其图像。明乾坤法窍之理,辩其伪真,学者以此为门路,則於隂陽理性之道,未必無小补云。 序 且地理之说,由来久矣,地理之书,亦甚繁矣,问其说,不曰天星遊年,即曰五音卦例,睹其书,非拘泥于星峰砂水,即拘泥乎黄泉会局,求其有合乎太极动静之理,五行造化之用者,百中無一,然彼非不言太极,而实不知太极之所以动静,实不知五行之所以造化。其不知所以动静造化者,縂由於不识地理之隂陽,穴星之向背,相地入乎先观穴星之向背,次察五行之形体,孰阴孰阳,不必求合乎太极,而太极动静之理,自無不含矣,以此寻龍察脉,认穴定向,如在掌握,独怪今时之師,五行莫辩隂陽不分,自诩深识地理,郎有人延卜地,虽十日半月,未能得一吉地。不曰天星不合,即曰卦例不吉,不曰峰水有石疑,即云泉局不利。如是以云卜地,未有能得真地者也,如是

为之葬人,未有不害人者也,余有感而笔於此,庶使后人不受其害,而吾師之道,得以传焉。 太极化形地理要诀 太极为地理子纲,地理要诀可知矣,夫地理不能离乎太极也,明太极者,不诚可知地理要诀哉,且古今地理不離太极,所患者人多昧耳,昧乎比則不能识太极变化之道,亦不能本太极会之会,难多言地理乎,要难卜云其吉矣。今夫太极,在天成象可观,太极在地成形可察,此中之变化無穷也。就生化之五者言之,水火木金土定也,故以五者定其形,即於色味方位预卜凶之兆,就生之四者观之,窝钳乳突是也,故以四者相其局。即於向皆运近,先知祸福之机。然则考夫地理者,可忽太极化生之機乎,而太极化形地理可考矣。 大地层次先天为体,后天为用。何为先天体?龍虎外扩,外坐山、内坐山、内外映山。何为后天为用?穴場隂陽,陽長高隂長高,隂陽皆低以中限高为行,至於结穴多不平,不识阴阳不能用,阴面如鏊背,阳面如掉平,阴属黑,阳属白,如太极之半黑半白也。 小地层次后天为体,先天为用。何为后天体?四面土色前后土左右土,於中不一,其中必有宝色。何为后天用?八方生旺,艮向丙離向庚先后皆合,必兼中有分金。至於穴場多平正,不识土色不能用,陽土有光华,隂土無气色,阴土湿,陽土干如太极之一半纯白也。纯白無黑,黑在穴后,或高或低,必有鏊背之形。半黑半白,黑在左右或平或仄,亦有阴阳之理,合於太极不亦宜乎。地理要诀在太极,而太极尚矣,夫地理千变万化,非太极無以绳之也,則要诀不在乎且以

java中swing用法

import java.awt.BorderLayout; import java.awt.Color; import java.awt.Container; import java.awt.FlowLayout; import javax.swing.JButton; import javax.swing.JFrame; public class FlowLayoutDemo{ private JFrame frame; private JButton button1,button2,button3,button4; public static void main(String[]args){ FlowLayoutDemo that=new FlowLayoutDemo(); that.go(); } public void go(){ frame=new JFrame("Folw Layout");//创建主题实例 Container contenPane=frame.getContentPane();//获得JFamel实例默认的内容窗格,此后可以修改它的布局管理器 contenPane.setBackground(Color.CYAN);//将JFranme实例的背景设置为蓝色 Container contentPane=frame.getContentPane(); contentPane.setLayout(new FlowLayout()); button1=new JButton("OK"); button2=new JButton("Open"); button3=new JButton("Close"); button4=new JButton("点我"); contentPane.add(button1);

薛传正:易林愚公的习易之路

薛传正:易林愚公的习易之路 今日记者有幸采访薛传正老师,经介绍得知薛传正老师现任中华周易名家协会青岛分会会长、常务理事、学术委员会委员、高级预测师、会员等职务。薛传正老师在多年的习易道路上有很多的感悟,今天让我们来聆听薛传正老师30余年来一直不间断的研习易学文化的心声。 记者问:“关于《周易》是迷信的说法,您怎么看?” 薛传正老师答道:“《周易》是中国周代的典箱,被尊为“群经之首,诸子百家之源”,西方文明有《圣经》,东方文明有《周易》。周易文化是中华文化发展的根本与源头,对中国后来历代的政治、经济、文化等诸多方面都产生巨大而又深远的影响,中国的建筑、医学、音乐、绘画、日常生活等无不与《周易》有着千丝万缕的联系,乃至影响到中国人的民族性格与民族精神。如:“天行健君子以自强不息,地势坤君子以厚德载物;”孔子读易、韦编三绝,他的千古名言“生死有命,富贵在天”就连《论语》中也多处引用《周易》的词语。”

记者问:“您是怎样与周易文化结缘的呢?” 薛传正老师答道:“我孩提时受祖父的影响,祖父酷爱中华民族的传统文化(如符咒文化),擅长中医,为当地百姓医治疑难杂症,在家乡享有盛名,我从小受祖父耳闻目睹,印上了周易的烙印,从此激起了学习周易的兴趣;记得,我六岁时,家父放在炕席下的用来护家防身的小土枪,我信手拿着玩耍,姐姐怕我出危险,拼命从我手中夺抢,我生气地把小土枪摔在墙上,土枪走火打在我屁股上,疼痛难忍,血流不止,我祖父运用周易符咒即止血咒给我止住血,顿时疼痛消失,从那以后我对周易文化产生了浓厚的兴趣;在八四年偶遇一周易高人,老人家说:“你在31--35岁几年,会出现经济拮据及官非”,结果在1989年生育二胎,夫人因孩子小而辞去了工作,只靠我自己的收入维持四口人的家庭,生活相当拮据。从那以后更深深爱上了易经,一发不可收拾;自此开始先后研读了命理类书:邵伟华老师的《四柱预测学》李后启老师的《秀枝命理》、《算命100法》、刘文元老师的《四柱正源》以及《三命通会》、《穷通宝鉴》、《滴天髓》、《神峰通考》;风水类:《阴宅三要》、《阳宅爱众》、《堪舆大全》、《阳宅十书》、《八宅明镜》、《阴阳宅大全》、《入地神眼》、《地理五诀》、《雪心赋》、《沈氏玄空学》、《地理啖蔗录》、《金锁玉关》、《地理辨证疏》、《宅经》、秦伦诗老师的《风水》,韩少清的《玄空风水精论》,钟义明的《玄空操作实务》、朱镇强的《择吉安居》;八卦类:邵伟华老师的《周易预测学》、《筮府珠林》;奇门类:张志春老师的《神奇之门》、《开悟之门》,杜新会老师的《奇门遁甲现代实例精解》,石建国老师的《奇门遁甲解真》,刘文元老师的《奇门启悟》,李万福老师的《奇门与四柱》,刘广斌老师的 《奇门预测学》以及《奇门遁甲统综》、《金函玉匣奇门遁甲》、《奇门归旨》;择

JAVA swing界面实现数据库增删改查

数据库程序设计 大作业 班级:2012级软件外包服务一班学号:201215140117 姓名:。。。 时间:2013-6-19

1.功能描述 1.1 功能简介 用swing做出图形化界面形式,实现数据库的增删改查把员工表跟部门表连接起来,实现数据的增加,删除,修改,查找。 1.2 实现步骤 (1)安装好虚拟机,并在其下确认oracle已安装成功(可以在dos下输入相关命令来检查是否安装成功)。 (2)在网络中心修改pc机上的VMware Network Adapter的IP、子网页码(默认)、网关。 (3)修改虚拟机的IP、网掩码(默认)、网关,确保PC机上的网关和虚拟机的IP一致。(在控制面板——>网络和共享中心——>本地连接3——>属性中,修改IP、网掩码)(4)在PC机的dos命令控制台ping虚拟机的IP,确保正常,能ping通(即将虚拟机内外ping通)。 (5)配置好虚拟机下的oracle的数据库和监听。 (6)在eclipse中编写相关代码,并用jtable实现图形化界面,用以实现与数据库的连接和操作数据库等功能。 (7)在eclipse中导入数据库的驱动。 (8)运行eclipse,查看运行结果。

2. 核心代码 2.1 1.数据库连接 package https://www.wendangku.net/doc/1c15469123.html,.dbc; import java.sql.Connection; import java.sql.DriverManager;

import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; public class DatabaseConnection { public static void main(String[] args) { Connection conn = null; Statement stmt = null; ResultSet rs = null; try { Class.forName("oracle.jdbc.driver.OracleDriver"); String url = "jdbc:oracle:thin:@192.168.0.128:1521/WFJ"; conn = DriverManager.getConnection(url, "hr", "hr"); stmt = conn.createStatement(); String sql = "select * from departments"; rs = stmt.executeQuery(sql); while (rs.next()) { System.out.print(rs.getInt("department_id")); System.out.print("\t"); System.out.print(rs.getString("department_name")); System.out.print("\t"); System.out.print(rs.getInt("manager_id")); System.out.print("\t"); System.out.print(rs.getInt("location_id")); System.out.println(); } } catch (ClassNotFoundException e) { e.printStackTrace(); } catch (SQLException e) { e.printStackTrace(); } finally { try { if (rs != null) { rs.close(); } if (stmt != null) { stmt.close(); } if (conn != null) { conn.close(); } } catch (SQLException e) {

Java Swing中处理各组件事件的一般步骤

Java Swing中处理各组件事件的一般步骤是: 1.新建一个组件(如JButton)。 2.将该组件添加到相应的面板(如JPanel)。 3.注册监听器以监听事件源产生的事件(如通过ActionListener来响应用户点击按钮)。 4.定义处理事件的方法(如在ActionListener中的actionPerformed中定义相应方法)。 以上步骤我们可以用多种方法实现。但人们通常用二种方法。第一种方法是只利用一个监听器以及多个if语句来决定是哪个组件产生的事件;第二种方法是使用多个内部类来响应不同组件产生的各种事件,其具体实现又分两种方式,一种是匿名内部类,一种是一般内部类。 为了说明如何使用上述三种方法实现事件的处理方法,我们建立一个简单的应用程序。该程序界面有两个按钮,当用户点击相应的按钮,就会弹出一个对话框显示相应的内容。通过这个简单程序,你可以实现自己更多、更复杂的用户界面程序。 首先,我们利用单个监听器来实现该程序。我们定义一个名为Simple1的类来包括所有代码。所有的用户行为(如点击按钮)由一个监听器SimpleListenner中的actionPerformed方法来处理。以下是代码: import java.awt.*; import javax.swing.*; public class Simple1 {

private static JFrame frame; // 定义为静态变量以便main使用 private static JPanel myPanel; // 该面板用来放置按钮组件 private JButton button1; // 这里定义按钮组件 private JButton button2; // 以便让ActionListener使用 public Simple1() // 构造器, 建立图形界面 { // 新建面板 myPanel = new JPanel(); // 新建按钮 button1 = new JButton("按钮1"); // 新建按钮1 button2 = new JButton("按钮2"); SimpleListener ourListener = new SimpleListener(); // 建立一个actionlistener让两个按钮共享 button1.addActionListener(ourListener); button2.addActionListener(ourListener); myPanel.add(button1); // 添加按钮到面板 myPanel.add(button2); } private class SimpleListener implements ActionListener { public void actionPerformed(ActionEvent e) {

Javaswing连接数据库的步骤(精)

Java swing 连接数据库的步骤 1.在工程中导入3个jar包,详见(导入Jar包的过程.doc 2.在类中导入包 aimport java.sql.*; bimport com.microsoft.jdbc.sqlserver.*; 3.声明连接对象,执行语句对象,结果集对象 aConnection conn=null; bStatement stmt=null; cResultSet rs=null; 4.定义连接字符串 afinal String CLASSFORNAME = "com.microsoft.jdbc.sqlserver.SQLServerDriver"; bfinal String DBURL = "jdbc:microsoft:sqlserver://127.0.0.1:1433;DataBaseName=pubs"; cfinal String USER="sa"; dfinal String PASS=""; 5.创建连接对象 try { Class.forName(CLASSFORNAME;

conn=DriverManager.getConnection(DBURL,USER,PASS; } catch (SQLException e { System.out.println(e.getMessage(; } catch (ClassNotFoundException ex { JOptionPane.showMessageDialog(this,"练苦失败"; return; } 6.创建执行语句对象stmt try { String sql = "insert into users values('name1','pass1'"; //上一行代码可以写成下一行的方式,试分析它的作用是什么? //String sql = "insert into users values('" +name+ "','"+pass+"'"; stmt = conn.createStatement(; stmt.executeUpdate (sql; } catch (SQLException ex1 { } 7.完毕

相关文档
相关文档 最新文档