原文:http://blogs.sun.com/Swing/entry/awt_swt_swing_java_gui2
作者:williamchen
译者:Matthew Chen
备注:内容有一些也是我以前不知道的,我也不得不说两句,红字为评论。
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对象作为参数。
(To be continued ...)