13.16 新型AWT

在Java 1.1中一个显著的改变就是完善了新AWT的创新。大多数的改变围绕在Java 1.1中使用的新事件模型:老的事件模型是糟糕的、笨拙的、非面向对象的,而新的事件模型可能是我所见过的最优秀的。难以理解一个如此糟糕的(老的AWT)和一个如此优秀的(新的事件模型)程序语言居然出自同一个集团之手。新的考虑事件的方法看来中止了,因此争议不再变成障碍,从而轻易进入我们的意识里;相反,它是一个帮助我们设计系统的工具。它同样是Java Beans的精华,我们会在本章后面部分进入讲述。

新的方法设计对象做为“事件源”和“事件接收器”以代替老AWT的非面向对象串联的条件语句。正象我们将看到的内部类的用途是集成面向对象的原始状态的新事件。另外,事件现在被描绘为在一个类体系以取代单一的类并且我们可以创建自己的事件类型。

我们同样会发现,如果我们采用老的AWT编程,Java 1.1版会产生一些看起来不合理的名字转换。例如,setsize()改成resize()。当我们学习Java Beans时这会变得更加的合理,因为Beans使用一个独特的命名协议。名字必须被修改以在Beans中产生新的标准AWT组件。

剪贴板操作在Java 1.1版中也得到支持,尽管拖放操作“将在新版本中被支持”。我们可能访问桌面色彩组织,所以我们的Java可以同其余桌面保持一致。可以利用弹出式菜单,并且为图像和图形作了改进。也同样支持鼠标操作。还有简单的为打印的API以及简单地支持滚动。

13.16.1 新的事件模型

在新的事件模型的组件可以开始一个事件。每种类型的事件被一个个别的类所描绘。当事件开始后,它受理一个或更多事件指明“接收器”。因此,事件源和处理事件的地址可以被分离。

每个事件接收器都是执行特定的接收器类型接口的类对象。因此作为一个程序开发者,我们所要做的是创建接收器对象并且在被激活事件的组件中进行注册。event-firing组件调用一个addXXXListener()方法来完成注册,以描述XXX事件类型接受。我们可以容易地了解到以addListened名的方法通知我们任何的事件类型都可以被处理,如果我们试图接收事件我们会发现编译时我们的错误。Java Beans同样使用这种addListener名的方法去判断那一个程序可以运行。

我们所有的事件逻辑将装入到一个接收器类中。当我们创建一个接收器类时唯一的一点限制是必须执行专用的接口。我们可以创建一个全局接收器类,这种情况在内部类中有助于被很好地使用,不仅仅是因为它们提供了一个理论上的接收器类组到它们服务的UI或业务逻辑类中,但因为(正像我们将会在本章后面看到的)事实是一个内部类维持一个引用到它的父对象,提供了一个很好的通过类和子系统边界的调用方法。

一个简单的例子将使这一切变得清晰明确。同时思考本章前部Button2.java例子与这个例子的差异。

  1. //: Button2New.java
  2. // Capturing button presses
  3. import java.awt.*;
  4. import java.awt.event.*; // Must add this
  5. import java.applet.*;
  6. public class Button2New extends Applet {
  7. Button
  8. b1 = new Button("Button 1"),
  9. b2 = new Button("Button 2");
  10. public void init() {
  11. b1.addActionListener(new B1());
  12. b2.addActionListener(new B2());
  13. add(b1);
  14. add(b2);
  15. }
  16. class B1 implements ActionListener {
  17. public void actionPerformed(ActionEvent e) {
  18. getAppletContext().showStatus("Button 1");
  19. }
  20. }
  21. class B2 implements ActionListener {
  22. public void actionPerformed(ActionEvent e) {
  23. getAppletContext().showStatus("Button 2");
  24. }
  25. }
  26. /* The old way:
  27. public boolean action(Event evt, Object arg) {
  28. if(evt.target.equals(b1))
  29. getAppletContext().showStatus("Button 1");
  30. else if(evt.target.equals(b2))
  31. getAppletContext().showStatus("Button 2");
  32. // Let the base class handle it:
  33. else
  34. return super.action(evt, arg);
  35. return true; // We've handled it here
  36. }
  37. */
  38. } ///:~

我们可比较两种方法,老的代码在左面作为注解。在init()方法里,只有一个改变就是增加了下面的两行:

  1. b1.addActionListener(new B1());
  2. b2.addActionListener(new B2());

按钮按下时,addActionListener()通知按钮对象被激活。B1B2类都是执行接口ActionListener的内部类。这个接口包括一个单一的方法actionPerformed()(这意味着当事件激活时,这个动作将被执行)。注意actionPreformed()方法不是一个普通事件,说得更恰当些是一个特殊类型的事件,ActionEvent。如果我们想提取特殊ActionEvent的信息,因此我们不需要故意去测试和向下转换参数。

对编程者来说一个最好的事便是actionPerformed()十分的简单易用。它是一个可以调用的方法。同老的action()方法比较,老的方法我们必须指出发生了什么和适当的动作,同样,我们会担心调用基类action()的版本并且返回一个值去指明是否被处理。在新的事件模型中,我们知道所有事件测试推理自动进行,因此我们不必指出发生了什么;我们刚刚表示发生了什么,它就自动地完成了。如果我们还没有提出用新的方法覆盖老的方法,我们会很快提出。

13.16.2 事件和接收者类型

所有AWT组件都被改变成包含addXXXListener()removeXXXListener()方法,因此特定的接收器类型可从每个组件中增加和删除。我们会注意到XXX在每个场合中同样表示参数的方法,例如,addFooListener(FooListener fl)。下面这张表格总结了通过提供addXXXListener()removeXXXListener()方法,从而支持那些特定事件的相关事件、接收器、方法以及组件。

  • 事件,接收器接口及添加和删除方法
    • 支持这个事件的组件
  • ActionEvent
  • ActionListener
  • addActionListener( )
  • removeActionListener( )
    • Button, List, TextField, MenuItem, and its derivatives including CheckboxMenuItem, Menu, and PopupMenu
  • AdjustmentEvent
  • AdjustmentListener
  • addAdjustmentListener( )
  • removeAdjustmentListener( )
  • Scrollbar
    • Anything you create that implements the Adjustable interface
  • ComponentEvent
  • ComponentListener
  • addComponentListener( )
  • removeComponentListener( )
    • Component and its derivatives, including Button, Canvas, Checkbox, Choice, Container, Panel, Applet, ScrollPane, Window, Dialog, FileDialog, Frame, Label, List, Scrollbar, TextArea, and TextField
  • ContainerEvent
  • ContainerListener
  • addContainerListener( )
  • removeContainerListener( )
    • Container and its derivatives, including Panel, Applet, ScrollPane, Window, Dialog, FileDialog, and Frame
  • FocusEvent
  • FocusListener
  • addFocusListener( )
  • removeFocusListener( )
    • Component and its derivatives, including Button, Canvas, Checkbox, Choice, Container, Panel, Applet, ScrollPane, Window, Dialog, FileDialog, Frame ``Label, List, Scrollbar, TextArea, and ``TextField
  • KeyEvent
  • KeyListener
  • addKeyListener( )
  • removeKeyListener( )
    • Component and its derivatives, including Button, Canvas, Checkbox, Choice, Container, Panel, Applet, ScrollPane, Window, Dialog, FileDialog, Frame, Label, List, Scrollbar, TextArea, and TextField
  • MouseEvent(for ``both ``clicks ``and ``motion)
  • MouseListener
  • addMouseListener( )
  • removeMouseListener( )
    • Component and its derivatives, including Button, Canvas, Checkbox, Choice, Container, Panel, Applet, ScrollPane, Window, Dialog, FileDialog, Frame, Label, List, Scrollbar, TextArea, and TextField
  • MouseEvent[55] (for ``both ``clicks ``and ``motion)
  • MouseMotionListener
  • addMouseMotionListener( )
  • removeMouseMotionListener( )
    • Component and its derivatives, including Button, Canvas, Checkbox, Choice, Container, Panel, Applet, ScrollPane, Window, Dialog, FileDialog, Frame, Label, List, Scrollbar, TextArea, and TextField
  • WindowEvent
  • WindowListener
  • addWindowListener( )
  • removeWindowListener( )
    • Window and its derivatives, including Dialog, FileDialog, and Frame
  • ItemEvent
  • ItemListener
  • addItemListener( )
  • removeItemListener( )
    • Checkbox, CheckboxMenuItem, Choice, List, and anything that implements the ItemSelectable interface
  • TextEvent
  • TextListener
  • addTextListener( )
  • removeTextListener( )
    • Anything derived from TextComponent, including TextArea and TextField

⑤:即使表面上如此,但实际上并没有MouseMotiionEvent(鼠标运动事件)。单击和运动都组合到MouseEvent里,所以MouseEvent在表格中的这种另类行为并非一个错误。

可以看到,每种类型的组件只为特定类型的事件提供了支持。这有助于我们发现由每种组件支持的事件,如下表所示:

  • 组件类型
    • 支持的事件
  • Adjustable
    • AdjustmentEvent
  • Applet
    • ContainerEvent, FocusEvent, KeyEvent, MouseEvent, ComponentEvent
  • Button
    • ActionEvent, FocusEvent, KeyEvent, MouseEvent, ComponentEvent
  • Canvas
    • FocusEvent, KeyEvent, MouseEvent, ComponentEvent
  • Checkbox
    • ItemEvent, FocusEvent, KeyEvent, MouseEvent, ComponentEvent
  • CheckboxMenuItem
    • ActionEvent, ItemEvent
  • Choice
    • ItemEvent, FocusEvent, KeyEvent, MouseEvent, ComponentEvent
  • Component
    • FocusEvent, KeyEvent, MouseEvent, ComponentEvent
  • Container
    • ContainerEvent, FocusEvent, KeyEvent, MouseEvent, ComponentEvent
  • Dialog
    • ContainerEvent, WindowEvent, FocusEvent, KeyEvent, MouseEvent, ComponentEvent
  • FileDialog
    • ContainerEvent, WindowEvent, FocusEvent, KeyEvent, MouseEvent, ComponentEvent
  • Frame
    • ContainerEvent, WindowEvent, FocusEvent, KeyEvent, MouseEvent, ComponentEvent
  • Label
    • FocusEvent, KeyEvent, MouseEvent, ComponentEvent
  • List
    • ActionEvent, FocusEvent, KeyEvent, MouseEvent, ItemEvent, ComponentEvent
  • Menu
    • ActionEvent
  • MenuItem
    • ActionEvent
  • Panel
    • ContainerEvent, FocusEvent, KeyEvent, MouseEvent, ComponentEvent
  • PopupMenu
    • ActionEvent
  • Scrollbar
    • AdjustmentEvent, FocusEvent, KeyEvent, MouseEvent, ComponentEvent
  • ScrollPane
    • ContainerEvent, FocusEvent, KeyEvent, MouseEvent, ComponentEvent
  • TextArea
    • TextEvent, FocusEvent, KeyEvent, MouseEvent, ComponentEvent
  • TextComponent
    • TextEvent, FocusEvent, KeyEvent, MouseEvent, ComponentEvent
  • TextField
    • ActionEvent, TextEvent, FocusEvent, KeyEvent, MouseEvent, ComponentEvent
  • Window
    • ContainerEvent, WindowEvent, FocusEvent, KeyEvent, MouseEvent, ComponentEvent

一旦知道了一个特定的组件支持哪些事件,就不必再去寻找任何东西来响应那个事件。只需简单地:

(1) 取得事件类的名字,并删掉其中的Event字样。在剩下的部分加入Listener字样。这就是在我们的内部类里需要实现的接收器接口。

(2) 实现上面的接口,针对想要捕获的事件编写方法代码。例如,假设我们想捕获鼠标的移动,所以需要为MouseMotiionListener接口的mouseMoved()方法编写代(当然还必须实现其他一些方法,但这里有捷径可循,马上就会讲到这个问题)。

(3) 为步骤2中的接收器类创建一个对象。随自己的组件和方法完成对它的注册,方法是在接收器的名字里加入一个前缀add。比如addMouseMotionListener()

下表是对接收器接口的一个总结:

  • 接收器接口
    • 接口中的方法
  • ActionListener
    • actionPerformed(ActionEvent)
  • AdjustmentListener
    • adjustmentValueChanged(AdjustmentEvent)
  • ComponentListener
  • ComponentAdapter
    • componentHidden(ComponentEvent)
    • componentShown(ComponentEvent)
    • componentMoved(ComponentEvent)
    • componentResized(ComponentEvent)
  • ContainerListener
  • ContainerAdapter
    • componentAdded(ContainerEvent)
    • componentRemoved(ContainerEvent)
  • FocusListener
  • FocusAdapter
    • focusGained(FocusEvent)
    • focusLost(FocusEvent)
  • KeyListener
  • KeyAdapter
    • keyPressed(KeyEvent)
    • keyReleased(KeyEvent)
    • keyTyped(KeyEvent)
  • MouseListener
  • MouseAdapter
    • mouseClicked(MouseEvent)
    • mouseEntered(MouseEvent)
    • mouseExited(MouseEvent)
    • mousePressed(MouseEvent)
    • mouseReleased(MouseEvent)
  • MouseMotionListener
  • MouseMotionAdapter
    • mouseDragged(MouseEvent)
    • mouseMoved(MouseEvent)
  • WindowListener
  • WindowAdapter
    • windowOpened(WindowEvent)
    • windowClosing(WindowEvent)
    • windowClosed(WindowEvent)
    • windowActivated(WindowEvent)
    • windowDeactivated(WindowEvent)
    • windowIconified(WindowEvent)
    • windowDeiconified(WindowEvent)
  • ItemListener
    • itemStateChanged(ItemEvent)
  • TextListener
    • textValueChanged(TextEvent)

(1) 用接收器适配器简化操作

在上面的表格中,我们可以注意到一些接收器接口只有唯一的一个方法。它们的执行是无轻重的,因为我们仅当需要书写特殊方法时才会执行它们。然而,接收器接口拥有多个方法,使用起来却不太友好。例如,我们必须一直运行某些事物,当我们创建一个应用程序时对帧提供一个WindowListener,以便当我们得到windowClosing()事件时可以调用System.exit(0)以退出应用程序。但因为WindowListener是一个接口,我们必须执行其它所有的方法即使它们不运行任何事件。这真令人讨厌。

为了解决这个问题,每个拥有超过一个方法的接收器接口都可拥有适配器,它们的名我们可以在上面的表格中看到。每个适配器为每个接口方法提供默认的方法。(WindowAdapter的默认方法不是windowClosing(),而是System.exit(0)方法。)此外我们所要做的就是从适配器处继承并重载唯一的需要变更的方法。例如,典型的WindowListener我们会像下面这样的使用。

  1. class MyWindowListener extends WindowAdapter {
  2. public void windowClosing(WindowEvent e) {
  3. System.exit(0);
  4. }
  5. }

适配器的全部宗旨就是使接收器的创建变得更加简便。 但所谓的“适配器”也有一个缺点,而且较难发觉。假定我们象上面那样写一个WindowAdapter

  1. class MyWindowListener extends WindowAdapter {
  2. public void WindowClosing(WindowEvent e) {
  3. System.exit(0);
  4. }
  5. }

表面上一切正常,但实际没有任何效果。每个事件的编译和运行都很正常——只是关闭窗口不会退出程序。您注意到问题在哪里吗?在方法的名字里:是WindowClosing(),而不是windowClosing()。大小写的一个简单失误就会造成一个崭新的方法。但是,这并非我们关闭窗口时调用的方法,所以当然没有任何效果。

13.16.3 用Java 1.1 AWT制作窗口和程序片

我们经常都需要创建一个类,使其既可作为一个窗口调用,亦可作为一个程序片调用。为做到这一点,只需为程序片简单地加入一个main()即可,令其在一个Frame(帧)里构建程序片的一个实例。作为一个简单的示例,下面让我们来看看如何对Button2New.java作一番修改,使其能同时作为应用程序和程序片使用:

  1. //: Button2NewB.java
  2. // An application and an applet
  3. import java.awt.*;
  4. import java.awt.event.*; // Must add this
  5. import java.applet.*;
  6. public class Button2NewB extends Applet {
  7. Button
  8. b1 = new Button("Button 1"),
  9. b2 = new Button("Button 2");
  10. TextField t = new TextField(20);
  11. public void init() {
  12. b1.addActionListener(new B1());
  13. b2.addActionListener(new B2());
  14. add(b1);
  15. add(b2);
  16. add(t);
  17. }
  18. class B1 implements ActionListener {
  19. public void actionPerformed(ActionEvent e) {
  20. t.setText("Button 1");
  21. }
  22. }
  23. class B2 implements ActionListener {
  24. public void actionPerformed(ActionEvent e) {
  25. t.setText("Button 2");
  26. }
  27. }
  28. // To close the application:
  29. static class WL extends WindowAdapter {
  30. public void windowClosing(WindowEvent e) {
  31. System.exit(0);
  32. }
  33. }
  34. // A main() for the application:
  35. public static void main(String[] args) {
  36. Button2NewB applet = new Button2NewB();
  37. Frame aFrame = new Frame("Button2NewB");
  38. aFrame.addWindowListener(new WL());
  39. aFrame.add(applet, BorderLayout.CENTER);
  40. aFrame.setSize(300,200);
  41. applet.init();
  42. applet.start();
  43. aFrame.setVisible(true);
  44. }
  45. } ///:~

内部类WLmain()方法是加入程序片的唯一两个元素,程序片剩余的部分则原封未动。事实上,我们通常将WL类和main()方法做一结小的改进复制和粘贴到我们自己的程序片里(请记住创建内部类时通常需要一个外部类来处理它,形成它静态地消除这个需要)。我们可以看到在main()方法里,程序片明确地初始化和开始,因为在这个例子里浏览器不能为我们有效地运行它。当然,这不会提供全部的浏览器调用stop()destroy()的行为,但对大多数的情况而言它都是可接受的。如果它变成一个麻烦,我们可以:

(1) 使程序片引用为一个静态类(以代替局部可变的main()),然后:

(2) 在我们调用System.exit()之前在WindowAdapter.windowClosing()中调用applet.stop()applet.destroy()

注意最后一行:

  1. aFrame.setVisible(true);

这是Java 1.1 AWT的一个改变。show()方法不再被支持,而setVisible(true)则取代了show()方法。当我们在本章后面部分学习Java Beans时,这些表面上易于改变的方法将会变得更加的合理。

这个例子同样被使用TextField修改而不是显示到控制台或浏览器状态行上。在开发程序时有一个限制条件就是程序片和应用程序我们都必须根据它们的运行情况选择输入和输出结构。

这里展示了Java 1.1 AWT的其它小的新功能。我们不再需要去使用有错误倾向的利用字符串指定BorderLayout定位的方法。当我们增加一个元素到Java 1.1版的BorderLayout中时,我们可以这样写:

  1. aFrame.add(applet, BorderLayout.CENTER);

我们对位置规定一个BorderLayout的常数,以使它能在编译时被检验(而不是对老的结构悄悄地做不合适的事)。这是一个显著的改善,并且将在这本书的余下部分大量地使用。

(2) 将窗口接收器变成匿名类

任何一个接收器类都可作为一个匿名类执行,但这一直有个意外,那就是我们可能需要在其它场合使用它们的功能。但是,窗口接收器在这里仅作为关闭应用程序窗口来使用,因此我们可以安全地制造一个匿名类。然后,main()中的下面这行代码:

  1. aFrame.addWindowListener(new WL());

会变成:

  1. aFrame.addWindowListener(
  2. new WindowAdapter() {
  3. public void windowClosing(WindowEvent e) {
  4. System.exit(0);
  5. }
  6. });

这有一个优点就是它不需要其它的类名。我们必须对自己判断是否它使代码变得易于理解或者更难。不过,对本书余下部分而言,匿名内部类将通常被使用在窗口接收器中。

(3) 将程序片封装到JAR文件里

一个重要的JAR应用就是完善程序片的装载。在Java 1.0版中,人们倾向于试法将它们的代码填入到单个的程序片类里,因此客户只需要单个的服务器就可适合下载程序片代码。但这不仅使结果凌乱,难以阅读(当然维护也然)程序,但类文件一直不能压缩,因此下载从来没有快过。

JAR文件将我们所有的被压缩的类文件打包到一个单个儿的文件中,再被浏览器下载。现在我们不需要创建一个糟糕的设计以最小化我们创建的类,并且用户将得到更快地下载速度。

仔细想想上面的例子,这个例子看起来像Button2NewB,是一个单类,但事实上它包含三个内部类,因此共有四个。每当我们编译程序,我会用这行代码打包它到一个JAR文件:

  1. jar cf Button2NewB.jar *.class

这是假定只有一个类文件在当前目录中,其中之一来自Button2NewB.java(否则我们会得到特别的打包)。

现在我们可以创建一个使用新文件标签来指定JAR文件的HTML页,如下所示:

  1. <head><title>Button2NewB Example Applet
  2. </title></head>
  3. <body>
  4. <applet code="Button2NewB.class"
  5. archive="Button2NewB.jar"
  6. width=200 height=150>
  7. </applet>
  8. </body>

与HTML文件中的程序片标记有关的其他任何内容都保持不变。

13.16.4 再研究一下以前的例子

为注意到一些利用新事件模型的例子和为学习程序从老到新事件模型改变的方法,下面的例子回到在本章第一部分利用事件模型来证明的一些争议。另外,每个程序包括程序片和应用程序现在都可以借助或不借助浏览器来运行。

(1) 文本字段

这个例子同TextField1.java相似,但它增加了显然额外的行为:

  1. //: TextNew.java
  2. // Text fields with Java 1.1 events
  3. import java.awt.*;
  4. import java.awt.event.*;
  5. import java.applet.*;
  6. public class TextNew extends Applet {
  7. Button
  8. b1 = new Button("Get Text"),
  9. b2 = new Button("Set Text");
  10. TextField
  11. t1 = new TextField(30),
  12. t2 = new TextField(30),
  13. t3 = new TextField(30);
  14. String s = new String();
  15. public void init() {
  16. b1.addActionListener(new B1());
  17. b2.addActionListener(new B2());
  18. t1.addTextListener(new T1());
  19. t1.addActionListener(new T1A());
  20. t1.addKeyListener(new T1K());
  21. add(b1);
  22. add(b2);
  23. add(t1);
  24. add(t2);
  25. add(t3);
  26. }
  27. class T1 implements TextListener {
  28. public void textValueChanged(TextEvent e) {
  29. t2.setText(t1.getText());
  30. }
  31. }
  32. class T1A implements ActionListener {
  33. private int count = 0;
  34. public void actionPerformed(ActionEvent e) {
  35. t3.setText("t1 Action Event " + count++);
  36. }
  37. }
  38. class T1K extends KeyAdapter {
  39. public void keyTyped(KeyEvent e) {
  40. String ts = t1.getText();
  41. if(e.getKeyChar() ==
  42. KeyEvent.VK_BACK_SPACE) {
  43. // Ensure it's not empty:
  44. if( ts.length() > 0) {
  45. ts = ts.substring(0, ts.length() - 1);
  46. t1.setText(ts);
  47. }
  48. }
  49. else
  50. t1.setText(
  51. t1.getText() +
  52. Character.toUpperCase(
  53. e.getKeyChar()));
  54. t1.setCaretPosition(
  55. t1.getText().length());
  56. // Stop regular character from appearing:
  57. e.consume();
  58. }
  59. }
  60. class B1 implements ActionListener {
  61. public void actionPerformed(ActionEvent e) {
  62. s = t1.getSelectedText();
  63. if(s.length() == 0) s = t1.getText();
  64. t1.setEditable(true);
  65. }
  66. }
  67. class B2 implements ActionListener {
  68. public void actionPerformed(ActionEvent e) {
  69. t1.setText("Inserted by Button 2: " + s);
  70. t1.setEditable(false);
  71. }
  72. }
  73. public static void main(String[] args) {
  74. TextNew applet = new TextNew();
  75. Frame aFrame = new Frame("TextNew");
  76. aFrame.addWindowListener(
  77. new WindowAdapter() {
  78. public void windowClosing(WindowEvent e) {
  79. System.exit(0);
  80. }
  81. });
  82. aFrame.add(applet, BorderLayout.CENTER);
  83. aFrame.setSize(300,200);
  84. applet.init();
  85. applet.start();
  86. aFrame.setVisible(true);
  87. }
  88. } ///:~

TextField t1的动作接收器被激活时,TextField t3就是一个需要报告的场所。我们注意到仅当我们按下enter键时,动作接收器才会为TextField所激活。

TextField t1附有几个接收器。T1接收器从t1复制所有文字到t2,强制所有字符串转换成大写。我们会发现这两个工作同是进行的,并且如果我们增加T1K接收器后我们再增加T1接收器,它就不那么重要:在文字字段内的所有的字符串将一直被强制变为大写。这看起来键盘事件一直在文字组件事件前被激活,并且如果我们需要保留t2的字符串原来输入时的样子,我们就必须做一些特别的工作。

T1K有着其它的一些有趣的活动。我们必须测试backspace(因为我们现在控制着每一个事件)并执行删除。caret必须被明确地设置到字段的结尾;否则它不会像我们希望的运行。最后,为了防止原来的字符串被默认的机制所处理,事件必须利用为事件对象而存在的consume()方法所“耗尽”。这会通知系统停止激活其余特殊事件的事件处理器。

这个例子同样无声地证明了设计内部类的带来的诸多优点。注意下面的内部类:

  1. class T1 implements TextListener {
  2. public void textValueChanged(TextEvent e) {
  3. t2.setText(t1.getText());
  4. }
  5. }

t1t2不属于T1的一部分,并且到目前为止它们都是很容易理解的,没有任何的特殊限制。这是因为一个内部类的对象能自动地捕捉一个引用到外部的创建它的对象那里,因此我们可以处理封装类对象的方法和内容。正像我们看到的,这十分方便(注释⑥)。

⑥:它也解决了“回调”的问题,不必为Java加入任何令人恼火的“方法指针”特性。

(2) 文本区域

Java 1.1版中Text Area最重要的改变就滚动条。对于TextArea的构造器而言,我们可以立即控制TextArea是否会拥有滚动条:水平的,垂直的,两者都有或者都没有。这个例子更正了前面Java 1.0版TextArea1.java程序片,演示了Java 1.1版的滚动条构造器:

  1. //: TextAreaNew.java
  2. // Controlling scrollbars with the TextArea
  3. // component in Java 1.1
  4. import java.awt.*;
  5. import java.awt.event.*;
  6. import java.applet.*;
  7. public class TextAreaNew extends Applet {
  8. Button b1 = new Button("Text Area 1");
  9. Button b2 = new Button("Text Area 2");
  10. Button b3 = new Button("Replace Text");
  11. Button b4 = new Button("Insert Text");
  12. TextArea t1 = new TextArea("t1", 1, 30);
  13. TextArea t2 = new TextArea("t2", 4, 30);
  14. TextArea t3 = new TextArea("t3", 1, 30,
  15. TextArea.SCROLLBARS_NONE);
  16. TextArea t4 = new TextArea("t4", 10, 10,
  17. TextArea.SCROLLBARS_VERTICAL_ONLY);
  18. TextArea t5 = new TextArea("t5", 4, 30,
  19. TextArea.SCROLLBARS_HORIZONTAL_ONLY);
  20. TextArea t6 = new TextArea("t6", 10, 10,
  21. TextArea.SCROLLBARS_BOTH);
  22. public void init() {
  23. b1.addActionListener(new B1L());
  24. add(b1);
  25. add(t1);
  26. b2.addActionListener(new B2L());
  27. add(b2);
  28. add(t2);
  29. b3.addActionListener(new B3L());
  30. add(b3);
  31. b4.addActionListener(new B4L());
  32. add(b4);
  33. add(t3); add(t4); add(t5); add(t6);
  34. }
  35. class B1L implements ActionListener {
  36. public void actionPerformed(ActionEvent e) {
  37. t5.append(t1.getText() + "\n");
  38. }
  39. }
  40. class B2L implements ActionListener {
  41. public void actionPerformed(ActionEvent e) {
  42. t2.setText("Inserted by Button 2");
  43. t2.append(": " + t1.getText());
  44. t5.append(t2.getText() + "\n");
  45. }
  46. }
  47. class B3L implements ActionListener {
  48. public void actionPerformed(ActionEvent e) {
  49. String s = " Replacement ";
  50. t2.replaceRange(s, 3, 3 + s.length());
  51. }
  52. }
  53. class B4L implements ActionListener {
  54. public void actionPerformed(ActionEvent e) {
  55. t2.insert(" Inserted ", 10);
  56. }
  57. }
  58. public static void main(String[] args) {
  59. TextAreaNew applet = new TextAreaNew();
  60. Frame aFrame = new Frame("TextAreaNew");
  61. aFrame.addWindowListener(
  62. new WindowAdapter() {
  63. public void windowClosing(WindowEvent e) {
  64. System.exit(0);
  65. }
  66. });
  67. aFrame.add(applet, BorderLayout.CENTER);
  68. aFrame.setSize(300,725);
  69. applet.init();
  70. applet.start();
  71. aFrame.setVisible(true);
  72. }
  73. } ///:~

我们发现只能在构造TextArea时能够控制滚动条。同样,即使TE AR没有滚动条,我们滚动光标也将被制止(可通过运行这个例子中验证这种行为)。

(3) 复选框和单选钮

正如早先指出的那样,复选框和单选钮都是同一个类建立的。单选钮和复选框略有不同,它是复选框安置到CheckboxGroup中构成的。在其中任一种情况下,有趣的ItemEvent事件为我们创建一个ItemListener项目接收器。

当处理一组复选框或者单选钮时,我们有一个不错的选择。我们可以创建一个新的内部类去为每个复选框处理事件,或者创建一个内部类判断哪个复选框被单击并注册一个内部类单独的对象为每个复选对象。下面的例子演示了两种方法:

  1. //: RadioCheckNew.java
  2. // Radio buttons and Check Boxes in Java 1.1
  3. import java.awt.*;
  4. import java.awt.event.*;
  5. import java.applet.*;
  6. public class RadioCheckNew extends Applet {
  7. TextField t = new TextField(30);
  8. Checkbox[] cb = {
  9. new Checkbox("Check Box 1"),
  10. new Checkbox("Check Box 2"),
  11. new Checkbox("Check Box 3") };
  12. CheckboxGroup g = new CheckboxGroup();
  13. Checkbox
  14. cb4 = new Checkbox("four", g, false),
  15. cb5 = new Checkbox("five", g, true),
  16. cb6 = new Checkbox("six", g, false);
  17. public void init() {
  18. t.setEditable(false);
  19. add(t);
  20. ILCheck il = new ILCheck();
  21. for(int i = 0; i < cb.length; i++) {
  22. cb[i].addItemListener(il);
  23. add(cb[i]);
  24. }
  25. cb4.addItemListener(new IL4());
  26. cb5.addItemListener(new IL5());
  27. cb6.addItemListener(new IL6());
  28. add(cb4); add(cb5); add(cb6);
  29. }
  30. // Checking the source:
  31. class ILCheck implements ItemListener {
  32. public void itemStateChanged(ItemEvent e) {
  33. for(int i = 0; i < cb.length; i++) {
  34. if(e.getSource().equals(cb[i])) {
  35. t.setText("Check box " + (i + 1));
  36. return;
  37. }
  38. }
  39. }
  40. }
  41. // vs. an individual class for each item:
  42. class IL4 implements ItemListener {
  43. public void itemStateChanged(ItemEvent e) {
  44. t.setText("Radio button four");
  45. }
  46. }
  47. class IL5 implements ItemListener {
  48. public void itemStateChanged(ItemEvent e) {
  49. t.setText("Radio button five");
  50. }
  51. }
  52. class IL6 implements ItemListener {
  53. public void itemStateChanged(ItemEvent e) {
  54. t.setText("Radio button six");
  55. }
  56. }
  57. public static void main(String[] args) {
  58. RadioCheckNew applet = new RadioCheckNew();
  59. Frame aFrame = new Frame("RadioCheckNew");
  60. aFrame.addWindowListener(
  61. new WindowAdapter() {
  62. public void windowClosing(WindowEvent e) {
  63. System.exit(0);
  64. }
  65. });
  66. aFrame.add(applet, BorderLayout.CENTER);
  67. aFrame.setSize(300,200);
  68. applet.init();
  69. applet.start();
  70. aFrame.setVisible(true);
  71. }
  72. } ///:~

ILCheck拥有当我们增加或者减少复选框时自动调整的优点。当然,我们对单选钮使用这种方法也同样的好。但是,它仅当我们的逻辑足以普遍的支持这种方法时才会被使用。如果声明一个确定的信号——我们将重复利用独立的接收器类,否则我们将结束一串条件语句。

(4) 下拉列表

下拉列表在Java 1.1版中当一个选择被改变时同样使用ItemListener去告知我们:

  1. //: ChoiceNew.java
  2. // Drop-down lists with Java 1.1
  3. import java.awt.*;
  4. import java.awt.event.*;
  5. import java.applet.*;
  6. public class ChoiceNew extends Applet {
  7. String[] description = { "Ebullient", "Obtuse",
  8. "Recalcitrant", "Brilliant", "Somnescent",
  9. "Timorous", "Florid", "Putrescent" };
  10. TextField t = new TextField(100);
  11. Choice c = new Choice();
  12. Button b = new Button("Add items");
  13. int count = 0;
  14. public void init() {
  15. t.setEditable(false);
  16. for(int i = 0; i < 4; i++)
  17. c.addItem(description[count++]);
  18. add(t);
  19. add(c);
  20. add(b);
  21. c.addItemListener(new CL());
  22. b.addActionListener(new BL());
  23. }
  24. class CL implements ItemListener {
  25. public void itemStateChanged(ItemEvent e) {
  26. t.setText("index: " + c.getSelectedIndex()
  27. + " " + e.toString());
  28. }
  29. }
  30. class BL implements ActionListener {
  31. public void actionPerformed(ActionEvent e) {
  32. if(count < description.length)
  33. c.addItem(description[count++]);
  34. }
  35. }
  36. public static void main(String[] args) {
  37. ChoiceNew applet = new ChoiceNew();
  38. Frame aFrame = new Frame("ChoiceNew");
  39. aFrame.addWindowListener(
  40. new WindowAdapter() {
  41. public void windowClosing(WindowEvent e) {
  42. System.exit(0);
  43. }
  44. });
  45. aFrame.add(applet, BorderLayout.CENTER);
  46. aFrame.setSize(750,100);
  47. applet.init();
  48. applet.start();
  49. aFrame.setVisible(true);
  50. }
  51. } ///:~

这个程序中没什么特别新颖的东西(除了Java 1.1版的UI类里少数几个值得关注的缺陷)。

(5) 列表

我们消除了Java 1.0中List设计的一个缺陷,就是List不能像我们希望的那样工作:它会与单击在一个列表元素上发生冲突。

  1. //: ListNew.java
  2. // Java 1.1 Lists are easier to use
  3. import java.awt.*;
  4. import java.awt.event.*;
  5. import java.applet.*;
  6. public class ListNew extends Applet {
  7. String[] flavors = { "Chocolate", "Strawberry",
  8. "Vanilla Fudge Swirl", "Mint Chip",
  9. "Mocha Almond Fudge", "Rum Raisin",
  10. "Praline Cream", "Mud Pie" };
  11. // Show 6 items, allow multiple selection:
  12. List lst = new List(6, true);
  13. TextArea t = new TextArea(flavors.length, 30);
  14. Button b = new Button("test");
  15. int count = 0;
  16. public void init() {
  17. t.setEditable(false);
  18. for(int i = 0; i < 4; i++)
  19. lst.addItem(flavors[count++]);
  20. add(t);
  21. add(lst);
  22. add(b);
  23. lst.addItemListener(new LL());
  24. b.addActionListener(new BL());
  25. }
  26. class LL implements ItemListener {
  27. public void itemStateChanged(ItemEvent e) {
  28. t.setText("");
  29. String[] items = lst.getSelectedItems();
  30. for(int i = 0; i < items.length; i++)
  31. t.append(items[i] + "\n");
  32. }
  33. }
  34. class BL implements ActionListener {
  35. public void actionPerformed(ActionEvent e) {
  36. if(count < flavors.length)
  37. lst.addItem(flavors[count++], 0);
  38. }
  39. }
  40. public static void main(String[] args) {
  41. ListNew applet = new ListNew();
  42. Frame aFrame = new Frame("ListNew");
  43. aFrame.addWindowListener(
  44. new WindowAdapter() {
  45. public void windowClosing(WindowEvent e) {
  46. System.exit(0);
  47. }
  48. });
  49. aFrame.add(applet, BorderLayout.CENTER);
  50. aFrame.setSize(300,200);
  51. applet.init();
  52. applet.start();
  53. aFrame.setVisible(true);
  54. }
  55. } ///:~

我们可以注意到在列表项中无需特别的逻辑需要去支持一个单击动作。我们正好像我们在其它地方所做的那样附加上一个接收器。

(6) 菜单

为菜单处理事件看起来受益于Java 1.1版的事件模型,但Java生成菜单的方法常常麻烦并且需要一些手工编写代码。生成菜单的正确方法看起来像资源而不是一些代码。请牢牢记住编程工具会广泛地为我们处理创建的菜单,因此这可以减少我们的痛苦(只要它们会同样处理维护任务!)。另外,我们将发现菜单不支持并且将导致混乱的事件:菜单项使用ActionListeners(动作接收器),但复选框菜单项使用ItemListeners(项目接收器)。菜单对象同样能支持ActionListeners(动作接收器),但通常不那么有用。一般来说,我们会附加接收器到每个菜单项或复选框菜单项,但下面的例子(对先前例子的修改)演示了一个联合捕捉多个菜单组件到一个单独的接收器类的方法。正像我们将看到的,它或许不值得为这而激烈地争论。

  1. //: MenuNew.java
  2. // Menus in Java 1.1
  3. import java.awt.*;
  4. import java.awt.event.*;
  5. public class MenuNew extends Frame {
  6. String[] flavors = { "Chocolate", "Strawberry",
  7. "Vanilla Fudge Swirl", "Mint Chip",
  8. "Mocha Almond Fudge", "Rum Raisin",
  9. "Praline Cream", "Mud Pie" };
  10. TextField t = new TextField("No flavor", 30);
  11. MenuBar mb1 = new MenuBar();
  12. Menu f = new Menu("File");
  13. Menu m = new Menu("Flavors");
  14. Menu s = new Menu("Safety");
  15. // Alternative approach:
  16. CheckboxMenuItem[] safety = {
  17. new CheckboxMenuItem("Guard"),
  18. new CheckboxMenuItem("Hide")
  19. };
  20. MenuItem[] file = {
  21. // No menu shortcut:
  22. new MenuItem("Open"),
  23. // Adding a menu shortcut is very simple:
  24. new MenuItem("Exit",
  25. new MenuShortcut(KeyEvent.VK_E))
  26. };
  27. // A second menu bar to swap to:
  28. MenuBar mb2 = new MenuBar();
  29. Menu fooBar = new Menu("fooBar");
  30. MenuItem[] other = {
  31. new MenuItem("Foo"),
  32. new MenuItem("Bar"),
  33. new MenuItem("Baz"),
  34. };
  35. // Initialization code:
  36. {
  37. ML ml = new ML();
  38. CMIL cmil = new CMIL();
  39. safety[0].setActionCommand("Guard");
  40. safety[0].addItemListener(cmil);
  41. safety[1].setActionCommand("Hide");
  42. safety[1].addItemListener(cmil);
  43. file[0].setActionCommand("Open");
  44. file[0].addActionListener(ml);
  45. file[1].setActionCommand("Exit");
  46. file[1].addActionListener(ml);
  47. other[0].addActionListener(new FooL());
  48. other[1].addActionListener(new BarL());
  49. other[2].addActionListener(new BazL());
  50. }
  51. Button b = new Button("Swap Menus");
  52. public MenuNew() {
  53. FL fl = new FL();
  54. for(int i = 0; i < flavors.length; i++) {
  55. MenuItem mi = new MenuItem(flavors[i]);
  56. mi.addActionListener(fl);
  57. m.add(mi);
  58. // Add separators at intervals:
  59. if((i+1) % 3 == 0)
  60. m.addSeparator();
  61. }
  62. for(int i = 0; i < safety.length; i++)
  63. s.add(safety[i]);
  64. f.add(s);
  65. for(int i = 0; i < file.length; i++)
  66. f.add(file[i]);
  67. mb1.add(f);
  68. mb1.add(m);
  69. setMenuBar(mb1);
  70. t.setEditable(false);
  71. add(t, BorderLayout.CENTER);
  72. // Set up the system for swapping menus:
  73. b.addActionListener(new BL());
  74. add(b, BorderLayout.NORTH);
  75. for(int i = 0; i < other.length; i++)
  76. fooBar.add(other[i]);
  77. mb2.add(fooBar);
  78. }
  79. class BL implements ActionListener {
  80. public void actionPerformed(ActionEvent e) {
  81. MenuBar m = getMenuBar();
  82. if(m == mb1) setMenuBar(mb2);
  83. else if (m == mb2) setMenuBar(mb1);
  84. }
  85. }
  86. class ML implements ActionListener {
  87. public void actionPerformed(ActionEvent e) {
  88. MenuItem target = (MenuItem)e.getSource();
  89. String actionCommand =
  90. target.getActionCommand();
  91. if(actionCommand.equals("Open")) {
  92. String s = t.getText();
  93. boolean chosen = false;
  94. for(int i = 0; i < flavors.length; i++)
  95. if(s.equals(flavors[i])) chosen = true;
  96. if(!chosen)
  97. t.setText("Choose a flavor first!");
  98. else
  99. t.setText("Opening "+ s +". Mmm, mm!");
  100. } else if(actionCommand.equals("Exit")) {
  101. dispatchEvent(
  102. new WindowEvent(MenuNew.this,
  103. WindowEvent.WINDOW_CLOSING));
  104. }
  105. }
  106. }
  107. class FL implements ActionListener {
  108. public void actionPerformed(ActionEvent e) {
  109. MenuItem target = (MenuItem)e.getSource();
  110. t.setText(target.getLabel());
  111. }
  112. }
  113. // Alternatively, you can create a different
  114. // class for each different MenuItem. Then you
  115. // Don't have to figure out which one it is:
  116. class FooL implements ActionListener {
  117. public void actionPerformed(ActionEvent e) {
  118. t.setText("Foo selected");
  119. }
  120. }
  121. class BarL implements ActionListener {
  122. public void actionPerformed(ActionEvent e) {
  123. t.setText("Bar selected");
  124. }
  125. }
  126. class BazL implements ActionListener {
  127. public void actionPerformed(ActionEvent e) {
  128. t.setText("Baz selected");
  129. }
  130. }
  131. class CMIL implements ItemListener {
  132. public void itemStateChanged(ItemEvent e) {
  133. CheckboxMenuItem target =
  134. (CheckboxMenuItem)e.getSource();
  135. String actionCommand =
  136. target.getActionCommand();
  137. if(actionCommand.equals("Guard"))
  138. t.setText("Guard the Ice Cream! " +
  139. "Guarding is " + target.getState());
  140. else if(actionCommand.equals("Hide"))
  141. t.setText("Hide the Ice Cream! " +
  142. "Is it cold? " + target.getState());
  143. }
  144. }
  145. public static void main(String[] args) {
  146. MenuNew f = new MenuNew();
  147. f.addWindowListener(
  148. new WindowAdapter() {
  149. public void windowClosing(WindowEvent e) {
  150. System.exit(0);
  151. }
  152. });
  153. f.setSize(300,200);
  154. f.setVisible(true);
  155. }
  156. } ///:~

在我们开始初始化节(由注解Initialization code:后的右大括号指明)的前面部分的代码同先前(Java 1.0版)版本相同。这里我们可以注意到项目接收器和动作接收器被附加在不同的菜单组件上。

Java 1.1支持“菜单快捷键”,因此我们可以选择一个菜单项目利用键盘替代鼠标。这十分的简单;我们只要使用重载菜单项构造器设置第二个参数为一个MenuShortcut(菜单快捷键事件)对象即可。菜单快捷键构造器设置重要的方法,当它按下时不可思议地显示在菜单项上。上面的例子增加了Control-EExit菜单项中。

我们同样会注意setActionCommand()的使用。这看似一点陌生因为在各种情况下“action command”完全同菜单组件上的标签一样。为什么不正好使用标签代替可选择的字符串呢?这个难题是国际化的。如果我们重新用其它语言写这个程序,我们只需要改变菜单中的标签,并不审查代码中可能包含新错误的所有逻辑。因此使这对检查文字字符串联合菜单组件的代码而言变得简单容易,当菜单标签能改变时“动作指令”可以不作任何的改变。所有这些代码同“动作指令”一同工作,因此它不会受改变菜单标签的影响。注意在这个程序中,不是所有的菜单组件都被它们的动作指令所审查,因此这些组件都没有它们的动作指令集。

大多数的构造器同前面的一样,将几个调用的异常增加到接收器中。大量的工作发生在接收器里。在前面例子的BL中,菜单交替发生。在ML中,“寻找ring”方法被作为动作事件(ActionEvent)的资源并对它进行转换送入菜单项,然后得到动作指令字符串,再通过它去贯穿串联组,当然条件是对它进行声明。这些大多数同前面的一样,但请注意如果Exit被选中,通过进入封装类对象的引用(MenuNew.this)并创建一个WINDOW_CLOSING事件,一个新的窗口事件就被创建了。新的事件被分配到封装类对象的dispatchEvent()方法,然后结束调用windowsClosing()内部帧的窗口接收器(这个接收器作为一个内部类被创建在main()里),似乎这是“正常”产生消息的方法。通过这种机制,我们可以在任何情况下迅速处理任何的信息,因此,它非常的强大。

FL接收器是很简单尽管它能处理特殊菜单的所有不同的特色。如果我们的逻辑十分的简单明了,这种方法对我们就很有用处,但通常,我们使用这种方法时需要与FooLBarLBazL一道使用,它们每个都附加到一个单独的菜单组件上,因此必然无需测试逻辑,并且使我们正确地辨识出谁调用了接收器。这种方法产生了大量的类,内部代码趋向于变得小巧和处理起来简单、安全。

(7) 对话框

在这个例子里直接重写了早期的ToeTest.java程序。在这个新的版本里,任何事件都被安放进一个内部类中。虽然这完全消除了需要记录产生的任何类的麻烦,作为ToeTest.java的一个例子,它能使内部类的概念变得不那遥远。在这点,内嵌类被嵌套达四层之深!我们需要的这种设计决定了内部类的优点是否值得增加更加复杂的事物。另外,当我们创建一个非静态的内部类时,我们将捆绑非静态类到它周围的类上。有时,单独的类可以更容易地被复用。

  1. //: ToeTestNew.java
  2. // Demonstration of dialog boxes
  3. // and creating your own components
  4. import java.awt.*;
  5. import java.awt.event.*;
  6. public class ToeTestNew extends Frame {
  7. TextField rows = new TextField("3");
  8. TextField cols = new TextField("3");
  9. public ToeTestNew() {
  10. setTitle("Toe Test");
  11. Panel p = new Panel();
  12. p.setLayout(new GridLayout(2,2));
  13. p.add(new Label("Rows", Label.CENTER));
  14. p.add(rows);
  15. p.add(new Label("Columns", Label.CENTER));
  16. p.add(cols);
  17. add(p, BorderLayout.NORTH);
  18. Button b = new Button("go");
  19. b.addActionListener(new BL());
  20. add(b, BorderLayout.SOUTH);
  21. }
  22. static final int BLANK = 0;
  23. static final int XX = 1;
  24. static final int OO = 2;
  25. class ToeDialog extends Dialog {
  26. // w = number of cells wide
  27. // h = number of cells high
  28. int turn = XX; // Start with x's turn
  29. public ToeDialog(int w, int h) {
  30. super(ToeTestNew.this,
  31. "The game itself", false);
  32. setLayout(new GridLayout(w, h));
  33. for(int i = 0; i < w * h; i++)
  34. add(new ToeButton());
  35. setSize(w * 50, h * 50);
  36. addWindowListener(new WindowAdapter() {
  37. public void windowClosing(WindowEvent e){
  38. dispose();
  39. }
  40. });
  41. }
  42. class ToeButton extends Canvas {
  43. int state = BLANK;
  44. ToeButton() {
  45. addMouseListener(new ML());
  46. }
  47. public void paint(Graphics g) {
  48. int x1 = 0;
  49. int y1 = 0;
  50. int x2 = getSize().width - 1;
  51. int y2 = getSize().height - 1;
  52. g.drawRect(x1, y1, x2, y2);
  53. x1 = x2/4;
  54. y1 = y2/4;
  55. int wide = x2/2;
  56. int high = y2/2;
  57. if(state == XX) {
  58. g.drawLine(x1, y1,
  59. x1 + wide, y1 + high);
  60. g.drawLine(x1, y1 + high,
  61. x1 + wide, y1);
  62. }
  63. if(state == OO) {
  64. g.drawOval(x1, y1,
  65. x1 + wide/2, y1 + high/2);
  66. }
  67. }
  68. class ML extends MouseAdapter {
  69. public void mousePressed(MouseEvent e) {
  70. if(state == BLANK) {
  71. state = turn;
  72. turn = (turn == XX ? OO : XX);
  73. }
  74. else
  75. state = (state == XX ? OO : XX);
  76. repaint();
  77. }
  78. }
  79. }
  80. }
  81. class BL implements ActionListener {
  82. public void actionPerformed(ActionEvent e) {
  83. Dialog d = new ToeDialog(
  84. Integer.parseInt(rows.getText()),
  85. Integer.parseInt(cols.getText()));
  86. d.show();
  87. }
  88. }
  89. public static void main(String[] args) {
  90. Frame f = new ToeTestNew();
  91. f.addWindowListener(
  92. new WindowAdapter() {
  93. public void windowClosing(WindowEvent e) {
  94. System.exit(0);
  95. }
  96. });
  97. f.setSize(200,100);
  98. f.setVisible(true);
  99. }
  100. } ///:~

由于“静态”的东西只能位于类的外部一级,所以内部类不可能拥有静态数据或者静态内部类。

(8) 文件对话框

这个例子是直接用新事件模型对FileDialogTest.java修改而来。

  1. //: FileDialogNew.java
  2. // Demonstration of File dialog boxes
  3. import java.awt.*;
  4. import java.awt.event.*;
  5. public class FileDialogNew extends Frame {
  6. TextField filename = new TextField();
  7. TextField directory = new TextField();
  8. Button open = new Button("Open");
  9. Button save = new Button("Save");
  10. public FileDialogNew() {
  11. setTitle("File Dialog Test");
  12. Panel p = new Panel();
  13. p.setLayout(new FlowLayout());
  14. open.addActionListener(new OpenL());
  15. p.add(open);
  16. save.addActionListener(new SaveL());
  17. p.add(save);
  18. add(p, BorderLayout.SOUTH);
  19. directory.setEditable(false);
  20. filename.setEditable(false);
  21. p = new Panel();
  22. p.setLayout(new GridLayout(2,1));
  23. p.add(filename);
  24. p.add(directory);
  25. add(p, BorderLayout.NORTH);
  26. }
  27. class OpenL implements ActionListener {
  28. public void actionPerformed(ActionEvent e) {
  29. // Two arguments, defaults to open file:
  30. FileDialog d = new FileDialog(
  31. FileDialogNew.this,
  32. "What file do you want to open?");
  33. d.setFile("*.java");
  34. d.setDirectory("."); // Current directory
  35. d.show();
  36. String yourFile = "*.*";
  37. if((yourFile = d.getFile()) != null) {
  38. filename.setText(yourFile);
  39. directory.setText(d.getDirectory());
  40. } else {
  41. filename.setText("You pressed cancel");
  42. directory.setText("");
  43. }
  44. }
  45. }
  46. class SaveL implements ActionListener {
  47. public void actionPerformed(ActionEvent e) {
  48. FileDialog d = new FileDialog(
  49. FileDialogNew.this,
  50. "What file do you want to save?",
  51. FileDialog.SAVE);
  52. d.setFile("*.java");
  53. d.setDirectory(".");
  54. d.show();
  55. String saveFile;
  56. if((saveFile = d.getFile()) != null) {
  57. filename.setText(saveFile);
  58. directory.setText(d.getDirectory());
  59. } else {
  60. filename.setText("You pressed cancel");
  61. directory.setText("");
  62. }
  63. }
  64. }
  65. public static void main(String[] args) {
  66. Frame f = new FileDialogNew();
  67. f.addWindowListener(
  68. new WindowAdapter() {
  69. public void windowClosing(WindowEvent e) {
  70. System.exit(0);
  71. }
  72. });
  73. f.setSize(250,110);
  74. f.setVisible(true);
  75. }
  76. } ///:~

如果所有的改变是这样的容易那将有多棒,但至少它们已足够容易,并且我们的代码已受益于这改进的可读性上。

13.16.5 动态绑定事件

新AWT事件模型给我们带来的一个好处就是灵活性。在老的模型中我们被迫为我们的程序动作艰难地编写代码。但新的模型我们可以用单一方法调用增加和删除事件动作。下面的例子证明了这一点:

  1. //: DynamicEvents.java
  2. // The new Java 1.1 event model allows you to
  3. // change event behavior dynamically. Also
  4. // demonstrates multiple actions for an event.
  5. import java.awt.*;
  6. import java.awt.event.*;
  7. import java.util.*;
  8. public class DynamicEvents extends Frame {
  9. Vector v = new Vector();
  10. int i = 0;
  11. Button
  12. b1 = new Button("Button 1"),
  13. b2 = new Button("Button 2");
  14. public DynamicEvents() {
  15. setLayout(new FlowLayout());
  16. b1.addActionListener(new B());
  17. b1.addActionListener(new B1());
  18. b2.addActionListener(new B());
  19. b2.addActionListener(new B2());
  20. add(b1);
  21. add(b2);
  22. }
  23. class B implements ActionListener {
  24. public void actionPerformed(ActionEvent e) {
  25. System.out.println("A button was pressed");
  26. }
  27. }
  28. class CountListener implements ActionListener {
  29. int index;
  30. public CountListener(int i) { index = i; }
  31. public void actionPerformed(ActionEvent e) {
  32. System.out.println(
  33. "Counted Listener " + index);
  34. }
  35. }
  36. class B1 implements ActionListener {
  37. public void actionPerformed(ActionEvent e) {
  38. System.out.println("Button 1 pressed");
  39. ActionListener a = new CountListener(i++);
  40. v.addElement(a);
  41. b2.addActionListener(a);
  42. }
  43. }
  44. class B2 implements ActionListener {
  45. public void actionPerformed(ActionEvent e) {
  46. System.out.println("Button 2 pressed");
  47. int end = v.size() -1;
  48. if(end >= 0) {
  49. b2.removeActionListener(
  50. (ActionListener)v.elementAt(end));
  51. v.removeElementAt(end);
  52. }
  53. }
  54. }
  55. public static void main(String[] args) {
  56. Frame f = new DynamicEvents();
  57. f.addWindowListener(
  58. new WindowAdapter() {
  59. public void windowClosing(WindowEvent e){
  60. System.exit(0);
  61. }
  62. });
  63. f.setSize(300,200);
  64. f.show();
  65. }
  66. } ///:~

这个例子采取的新手法包括:

(1) 在每个按钮上附着不少于一个的接收器。通常,组件把事件作为多转换处理,这意味着我们可以为单个事件注册许多接收器。当在特殊的组件中一个事件作为单一转换被处理时,我们会得到TooManyListenersException(即太多接收器异常)。

(2) 程序执行期间,接收器动态地被从按钮B2中增加和删除。增加用我们前面见到过的方法完成,但每个组件同样有一个removeXXXListener()(删除XXX接收器)方法来删除各种类型的接收器。

这种灵活性为我们的编程提供了更强大的能力。

我们注意到事件接收器不能保证在命令他们被增加时可被调用(虽然事实上大部分的执行工作都是用这种方法完成的)。

13.16.6 将事务逻辑与UI逻辑区分开

一般而言,我们需要设计我们的类如此以至于每一类做“一件事”。当涉及用户接口代码时就更显得尤为重要,因为它很容易地封装“您要做什么”和“怎样显示它”。这种有效的配合防止了代码的重复使用。更不用说它令人满意的从GUI中区分出我们的“事物逻辑”。使用这种方法,我们可以不仅仅更容易地重复使用事物逻辑,它同样可以更容易地重复使用GUI。

其它的争议是“动作对象”存在的完成分离机器的多层次系统。动作主要的定位规则允许所有新事件修改后立刻生效,并且这是如此一个引人注目的设置系统的方法。但是这些动作对象可以被在一些不同的应用程序使用并且因此不会被一些特殊的显示模式所约束。它们会合理地执行动作操作并且没有多余的事件。

下面的例子演示了从GUI代码中多么地轻松的区分事物逻辑:

  1. //: Separation.java
  2. // Separating GUI logic and business objects
  3. import java.awt.*;
  4. import java.awt.event.*;
  5. import java.applet.*;
  6. class BusinessLogic {
  7. private int modifier;
  8. BusinessLogic(int mod) {
  9. modifier = mod;
  10. }
  11. public void setModifier(int mod) {
  12. modifier = mod;
  13. }
  14. public int getModifier() {
  15. return modifier;
  16. }
  17. // Some business operations:
  18. public int calculation1(int arg) {
  19. return arg * modifier;
  20. }
  21. public int calculation2(int arg) {
  22. return arg + modifier;
  23. }
  24. }
  25. public class Separation extends Applet {
  26. TextField
  27. t = new TextField(20),
  28. mod = new TextField(20);
  29. BusinessLogic bl = new BusinessLogic(2);
  30. Button
  31. calc1 = new Button("Calculation 1"),
  32. calc2 = new Button("Calculation 2");
  33. public void init() {
  34. add(t);
  35. calc1.addActionListener(new Calc1L());
  36. calc2.addActionListener(new Calc2L());
  37. add(calc1); add(calc2);
  38. mod.addTextListener(new ModL());
  39. add(new Label("Modifier:"));
  40. add(mod);
  41. }
  42. static int getValue(TextField tf) {
  43. try {
  44. return Integer.parseInt(tf.getText());
  45. } catch(NumberFormatException e) {
  46. return 0;
  47. }
  48. }
  49. class Calc1L implements ActionListener {
  50. public void actionPerformed(ActionEvent e) {
  51. t.setText(Integer.toString(
  52. bl.calculation1(getValue(t))));
  53. }
  54. }
  55. class Calc2L implements ActionListener {
  56. public void actionPerformed(ActionEvent e) {
  57. t.setText(Integer.toString(
  58. bl.calculation2(getValue(t))));
  59. }
  60. }
  61. class ModL implements TextListener {
  62. public void textValueChanged(TextEvent e) {
  63. bl.setModifier(getValue(mod));
  64. }
  65. }
  66. public static void main(String[] args) {
  67. Separation applet = new Separation();
  68. Frame aFrame = new Frame("Separation");
  69. aFrame.addWindowListener(
  70. new WindowAdapter() {
  71. public void windowClosing(WindowEvent e) {
  72. System.exit(0);
  73. }
  74. });
  75. aFrame.add(applet, BorderLayout.CENTER);
  76. aFrame.setSize(200,200);
  77. applet.init();
  78. applet.start();
  79. aFrame.setVisible(true);
  80. }
  81. } ///:~

可以看到,事物逻辑是一个直接完成它的操作而不需要提示并且可以在GUI环境下使用的类。它正适合它的工作。区分动作记录了所有UI的详细资料,并且它只通过它的公共接口与事物逻辑交流。所有的操作围绕中心通过UI和事物逻辑对象来回获取信息。因此区分,轮流做它的工作。因为区分中只知道它同事物逻辑对象对话(也就是说,它没有高度的结合),它可以被强迫同其它类型的对象对话而没有更多的烦恼。 思考从事物逻辑中区分UI的条件,同样思考当我们调整传统的Java代码使它运行时,怎样使它更易存活。

13.16.7 推荐编码方法

内部类是新的事件模型,并且事实上旧的事件模型连同新库的特征都被它好的支持,依赖老式的编程方法无疑增加了一个新的混乱的因素。现在有更多不同的方法为我们编写讨厌的代码。凑巧的是,这种代码显现在本书中和程序样本中,并且甚至在文件和程序样本中同SUN公司区别开来。在这一节中,我们将看到一些关于我们会和不会运行新AWT的争执,并由向我们展示除了可以原谅的情况,我们可以随时使用接收器类去解决我们的事件处理需要来结束。因为这种方法同样是最简单和最清晰的方法,它将会对我们学习它构成有效的帮助。

在看到任何事以前,我们知道尽管Java 1.1向后兼容Java 1.0(也就是说,我们可以在1.1中编译和运行1.0的程序),但我们并不能在同一个程序里混合事件模型。换言之,当我们试图集成老的代码到一个新的程序中时,我们不能使用老式的action()方法在同一个程序中,因此我们必须决定是否对新程序使用老的,难以维护的方法或者升级老的代码。这不会有太多的竞争因为新的方法对老的方法而言是如此的优秀。

(1) 准则:运行它的好方法

为了给我们一些事物来进行比较,这儿有一个程序例子演示向我们推荐的方法。到现在它会变得相当的熟悉和舒适。

  1. //: GoodIdea.java
  2. // The best way to design classes using the new
  3. // Java 1.1 event model: use an inner class for
  4. // each different event. This maximizes
  5. // flexibility and modularity.
  6. import java.awt.*;
  7. import java.awt.event.*;
  8. import java.util.*;
  9. public class GoodIdea extends Frame {
  10. Button
  11. b1 = new Button("Button 1"),
  12. b2 = new Button("Button 2");
  13. public GoodIdea() {
  14. setLayout(new FlowLayout());
  15. b1.addActionListener(new B1L());
  16. b2.addActionListener(new B2L());
  17. add(b1);
  18. add(b2);
  19. }
  20. public class B1L implements ActionListener {
  21. public void actionPerformed(ActionEvent e) {
  22. System.out.println("Button 1 pressed");
  23. }
  24. }
  25. public class B2L implements ActionListener {
  26. public void actionPerformed(ActionEvent e) {
  27. System.out.println("Button 2 pressed");
  28. }
  29. }
  30. public static void main(String[] args) {
  31. Frame f = new GoodIdea();
  32. f.addWindowListener(
  33. new WindowAdapter() {
  34. public void windowClosing(WindowEvent e){
  35. System.out.println("Window Closing");
  36. System.exit(0);
  37. }
  38. });
  39. f.setSize(300,200);
  40. f.setVisible(true);
  41. }
  42. } ///:~

这是颇有点微不足道的:每个按钮有它自己的印出一些事物到控制台的接收器。但请注意在整个程序中这不是一个条件语句,或者是一些表示“我想要知道怎样使事件发生”的语句。每块代码都与运行有关,而不是类型检验。也就是说,这是最好的编写我们的代码的方法;不仅仅是它更易使我们理解概念,至少是使我们更易阅读和维护。剪切和粘贴到新的程序是同样如此的容易。

(2) 将主类作为接收器实现

第一个坏主意是一个通常的和推荐的方法。这使得主类(有代表性的是程序片或帧,但它能变成一些类)执行各种不同的接收器。下面是一个例子:

  1. //: BadIdea1.java
  2. // Some literature recommends this approach,
  3. // but it's missing the point of the new event
  4. // model in Java 1.1
  5. import java.awt.*;
  6. import java.awt.event.*;
  7. import java.util.*;
  8. public class BadIdea1 extends Frame
  9. implements ActionListener, WindowListener {
  10. Button
  11. b1 = new Button("Button 1"),
  12. b2 = new Button("Button 2");
  13. public BadIdea1() {
  14. setLayout(new FlowLayout());
  15. addWindowListener(this);
  16. b1.addActionListener(this);
  17. b2.addActionListener(this);
  18. add(b1);
  19. add(b2);
  20. }
  21. public void actionPerformed(ActionEvent e) {
  22. Object source = e.getSource();
  23. if(source == b1)
  24. System.out.println("Button 1 pressed");
  25. else if(source == b2)
  26. System.out.println("Button 2 pressed");
  27. else
  28. System.out.println("Something else");
  29. }
  30. public void windowClosing(WindowEvent e) {
  31. System.out.println("Window Closing");
  32. System.exit(0);
  33. }
  34. public void windowClosed(WindowEvent e) {}
  35. public void windowDeiconified(WindowEvent e) {}
  36. public void windowIconified(WindowEvent e) {}
  37. public void windowActivated(WindowEvent e) {}
  38. public void windowDeactivated(WindowEvent e) {}
  39. public void windowOpened(WindowEvent e) {}
  40. public static void main(String[] args) {
  41. Frame f = new BadIdea1();
  42. f.setSize(300,200);
  43. f.setVisible(true);
  44. }
  45. } ///:~

这样做的用途显示在下述三行里:

  1. addWindowListener(this);
  2. b1.addActionListener(this);
  3. b2.addActionListener(this);

因为Badidea1执行动作接收器和窗中接收器,这些程序行当然可以接受,并且如果我们一直坚持设法使少量的类去减少服务器检索期间的程序片载入的作法,它看起来变成一个不错的主意。但是:

(1) Java 1.1版支持JAR文件,因此所有我们的文件可以被放置到一个单一的压缩的JAR文件中,只需要一次服务器检索。我们不再需要为Internet效率而减少类的数量。

(2) 上面的代码的组件更加的少,因此它难以抓住和粘贴。注意我们必须不仅要执行各种各样的接口为我们的主类,但在actionPerformed()方法中,我们利用一串条件语句测试哪个动作被完成了。不仅仅是这个状态倒退,远离接收器模型,除此之外,我们不能简单地重复使用actionPerformed()方法因为它是指定为这个特殊的应用程序使用的。将这个程序例子与GoodIdea.java进行比较,我们可以正好捕捉一个接收器类并粘贴它和最小的焦急到任何地方。另外我们可以为一个单独的事件注册多个接收器类,允许甚至更多的模块在每个接收器类在每个接收器中运行。

(3) 方法的混合

第二个bad idea混合了两种方法:使用内嵌接收器类,但同样执行一个或更多的接收器接口以作为主类的一部分。这种方法无需在书中和文件中进行解释,而且我可以臆测到Java开发者认为他们必须为不同的目的而采取不同的方法。但我们却不必——在我们编程时,我们或许可能会倾向于使用内嵌接收器类。

  1. //: BadIdea2.java
  2. // An improvement over BadIdea1.java, since it
  3. // uses the WindowAdapter as an inner class
  4. // instead of implementing all the methods of
  5. // WindowListener, but still misses the
  6. // valuable modularity of inner classes
  7. import java.awt.*;
  8. import java.awt.event.*;
  9. import java.util.*;
  10. public class BadIdea2 extends Frame
  11. implements ActionListener {
  12. Button
  13. b1 = new Button("Button 1"),
  14. b2 = new Button("Button 2");
  15. public BadIdea2() {
  16. setLayout(new FlowLayout());
  17. addWindowListener(new WL());
  18. b1.addActionListener(this);
  19. b2.addActionListener(this);
  20. add(b1);
  21. add(b2);
  22. }
  23. public void actionPerformed(ActionEvent e) {
  24. Object source = e.getSource();
  25. if(source == b1)
  26. System.out.println("Button 1 pressed");
  27. else if(source == b2)
  28. System.out.println("Button 2 pressed");
  29. else
  30. System.out.println("Something else");
  31. }
  32. class WL extends WindowAdapter {
  33. public void windowClosing(WindowEvent e) {
  34. System.out.println("Window Closing");
  35. System.exit(0);
  36. }
  37. }
  38. public static void main(String[] args) {
  39. Frame f = new BadIdea2();
  40. f.setSize(300,200);
  41. f.setVisible(true);
  42. }
  43. } ///:~

因为actionPerformed()动作完成方法同主类紧密地结合,所以难以复用代码。它的代码读起来同样是凌乱和令人厌烦的,远远超过了内部类方法。不合理的是,我们不得不在Java 1.1版中为事件使用那些老的思路。

(4) 继承一个组件

创建一个新类型的组件时,在运行事件的老方法中,我们会经常看到不同的地方发生了变化。这里有一个程序例子来演示这种新的工作方法:

  1. //: GoodTechnique.java
  2. // Your first choice when overriding components
  3. // should be to install listeners. The code is
  4. // much safer, more modular and maintainable.
  5. import java.awt.*;
  6. import java.awt.event.*;
  7. class Display {
  8. public static final int
  9. EVENT = 0, COMPONENT = 1,
  10. MOUSE = 2, MOUSE_MOVE = 3,
  11. FOCUS = 4, KEY = 5, ACTION = 6,
  12. LAST = 7;
  13. public String[] evnt;
  14. Display() {
  15. evnt = new String[LAST];
  16. for(int i = 0; i < LAST; i++)
  17. evnt[i] = new String();
  18. }
  19. public void show(Graphics g) {
  20. for(int i = 0; i < LAST; i++)
  21. g.drawString(evnt[i], 0, 10 * i + 10);
  22. }
  23. }
  24. class EnabledPanel extends Panel {
  25. Color c;
  26. int id;
  27. Display display = new Display();
  28. public EnabledPanel(int i, Color mc) {
  29. id = i;
  30. c = mc;
  31. setLayout(new BorderLayout());
  32. add(new MyButton(), BorderLayout.SOUTH);
  33. addComponentListener(new CL());
  34. addFocusListener(new FL());
  35. addKeyListener(new KL());
  36. addMouseListener(new ML());
  37. addMouseMotionListener(new MML());
  38. }
  39. // To eliminate flicker:
  40. public void update(Graphics g) {
  41. paint(g);
  42. }
  43. public void paint(Graphics g) {
  44. g.setColor(c);
  45. Dimension s = getSize();
  46. g.fillRect(0, 0, s.width, s.height);
  47. g.setColor(Color.black);
  48. display.show(g);
  49. }
  50. // Don't need to enable anything for this:
  51. public void processEvent(AWTEvent e) {
  52. display.evnt[Display.EVENT]= e.toString();
  53. repaint();
  54. super.processEvent(e);
  55. }
  56. class CL implements ComponentListener {
  57. public void componentMoved(ComponentEvent e){
  58. display.evnt[Display.COMPONENT] =
  59. "Component moved";
  60. repaint();
  61. }
  62. public void
  63. componentResized(ComponentEvent e) {
  64. display.evnt[Display.COMPONENT] =
  65. "Component resized";
  66. repaint();
  67. }
  68. public void
  69. componentHidden(ComponentEvent e) {
  70. display.evnt[Display.COMPONENT] =
  71. "Component hidden";
  72. repaint();
  73. }
  74. public void componentShown(ComponentEvent e){
  75. display.evnt[Display.COMPONENT] =
  76. "Component shown";
  77. repaint();
  78. }
  79. }
  80. class FL implements FocusListener {
  81. public void focusGained(FocusEvent e) {
  82. display.evnt[Display.FOCUS] =
  83. "FOCUS gained";
  84. repaint();
  85. }
  86. public void focusLost(FocusEvent e) {
  87. display.evnt[Display.FOCUS] =
  88. "FOCUS lost";
  89. repaint();
  90. }
  91. }
  92. class KL implements KeyListener {
  93. public void keyPressed(KeyEvent e) {
  94. display.evnt[Display.KEY] =
  95. "KEY pressed: ";
  96. showCode(e);
  97. }
  98. public void keyReleased(KeyEvent e) {
  99. display.evnt[Display.KEY] =
  100. "KEY released: ";
  101. showCode(e);
  102. }
  103. public void keyTyped(KeyEvent e) {
  104. display.evnt[Display.KEY] =
  105. "KEY typed: ";
  106. showCode(e);
  107. }
  108. void showCode(KeyEvent e) {
  109. int code = e.getKeyCode();
  110. display.evnt[Display.KEY] +=
  111. KeyEvent.getKeyText(code);
  112. repaint();
  113. }
  114. }
  115. class ML implements MouseListener {
  116. public void mouseClicked(MouseEvent e) {
  117. requestFocus(); // Get FOCUS on click
  118. display.evnt[Display.MOUSE] =
  119. "MOUSE clicked";
  120. showMouse(e);
  121. }
  122. public void mousePressed(MouseEvent e) {
  123. display.evnt[Display.MOUSE] =
  124. "MOUSE pressed";
  125. showMouse(e);
  126. }
  127. public void mouseReleased(MouseEvent e) {
  128. display.evnt[Display.MOUSE] =
  129. "MOUSE released";
  130. showMouse(e);
  131. }
  132. public void mouseEntered(MouseEvent e) {
  133. display.evnt[Display.MOUSE] =
  134. "MOUSE entered";
  135. showMouse(e);
  136. }
  137. public void mouseExited(MouseEvent e) {
  138. display.evnt[Display.MOUSE] =
  139. "MOUSE exited";
  140. showMouse(e);
  141. }
  142. void showMouse(MouseEvent e) {
  143. display.evnt[Display.MOUSE] +=
  144. ", x = " + e.getX() +
  145. ", y = " + e.getY();
  146. repaint();
  147. }
  148. }
  149. class MML implements MouseMotionListener {
  150. public void mouseDragged(MouseEvent e) {
  151. display.evnt[Display.MOUSE_MOVE] =
  152. "MOUSE dragged";
  153. showMouse(e);
  154. }
  155. public void mouseMoved(MouseEvent e) {
  156. display.evnt[Display.MOUSE_MOVE] =
  157. "MOUSE moved";
  158. showMouse(e);
  159. }
  160. void showMouse(MouseEvent e) {
  161. display.evnt[Display.MOUSE_MOVE] +=
  162. ", x = " + e.getX() +
  163. ", y = " + e.getY();
  164. repaint();
  165. }
  166. }
  167. }
  168. class MyButton extends Button {
  169. int clickCounter;
  170. String label = "";
  171. public MyButton() {
  172. addActionListener(new AL());
  173. }
  174. public void paint(Graphics g) {
  175. g.setColor(Color.green);
  176. Dimension s = getSize();
  177. g.fillRect(0, 0, s.width, s.height);
  178. g.setColor(Color.black);
  179. g.drawRect(0, 0, s.width - 1, s.height - 1);
  180. drawLabel(g);
  181. }
  182. private void drawLabel(Graphics g) {
  183. FontMetrics fm = g.getFontMetrics();
  184. int width = fm.stringWidth(label);
  185. int height = fm.getHeight();
  186. int ascent = fm.getAscent();
  187. int leading = fm.getLeading();
  188. int horizMargin =
  189. (getSize().width - width)/2;
  190. int verMargin =
  191. (getSize().height - height)/2;
  192. g.setColor(Color.red);
  193. g.drawString(label, horizMargin,
  194. verMargin + ascent + leading);
  195. }
  196. class AL implements ActionListener {
  197. public void actionPerformed(ActionEvent e) {
  198. clickCounter++;
  199. label = "click #" + clickCounter +
  200. " " + e.toString();
  201. repaint();
  202. }
  203. }
  204. }
  205. public class GoodTechnique extends Frame {
  206. GoodTechnique() {
  207. setLayout(new GridLayout(2,2));
  208. add(new EnabledPanel(1, Color.cyan));
  209. add(new EnabledPanel(2, Color.lightGray));
  210. add(new EnabledPanel(3, Color.yellow));
  211. }
  212. public static void main(String[] args) {
  213. Frame f = new GoodTechnique();
  214. f.setTitle("Good Technique");
  215. f.addWindowListener(
  216. new WindowAdapter() {
  217. public void windowClosing(WindowEvent e){
  218. System.out.println(e);
  219. System.out.println("Window Closing");
  220. System.exit(0);
  221. }
  222. });
  223. f.setSize(700,700);
  224. f.setVisible(true);
  225. }
  226. } ///:~

这个程序例子同样证明了各种各样的发现和显示关于它们的信息的事件。这种显示是一种集中显示信息的方法。一组字符串去获取关于每种类型的事件的信息,并且show()方法对任何图像对象都设置了一个引用,我们采用并直接地写在外观代码上。这种设计是有意的被某种事件重复使用。

激活面板代表了这种新型的组件。它是一个底部有一个按钮的彩色的面板,并且它由利用接收器类为每一个单独的事件来引发捕捉所有发生在它之上的事件,除了那些在激活面板重载的老式的processEvent()方法(注意它应该同样调用super.processEvent())。利用这种方法的唯一理由是它捕捉发生的每一个事件,因此我们可以观察持续发生的每一事件。processEvent()方法没有更多的展示代表每个事件的字符串,否则它会不得不使用一串条件语句去寻找事件。在其它方面,内嵌接收类早已清晰地知道被发现的事件。(假定我们注册它们到组件,我们不需要任何的控件的逻辑,这将成为我们的目的。)因此,它们不会去检查任何事件;这些事件正好做它们的原材料。

每个接收器修改显示字符串和它的指定事件,并且调用重画方法repaint()因此将显示这个字符串。我们同样能注意到一个通常能消除闪烁的秘诀:

  1. public void update(Graphics g) {
  2. paint(g);
  3. }

我们不会始终需要重载update(),但如果我们写下一些闪烁的程序,并运行它。默认的最新版本的清除背景然后调用paint()方法重新画出一些图画。这个清除动作通常会产生闪烁,但是不必要的,因为paint()重画了整个的外观。

我们可以看到许多的接收器——但是,对接收器输入检查指令,但我们却不能接收任何组件不支持的事件。(不像BadTechnuque.java那样我们能时时刻刻看到)。

试验这个程序是十分的有教育意义的,因为我们学习了许多的关于在Java中事件发生的方法。一则它展示了大多数开窗口的系统中设计上的瑕疵:它相当的难以去单击和释放鼠标,除非移动它,并且当我们实际上正试图用鼠标单击在某物体上时开窗口的会常常认为我们是在拖动。一个解决这个问题的方案是使用mousePressed()鼠标按下方法和mouseReleased()鼠标释放方法去代替mouseClicked()鼠标单击方法,然后判断是否去调用我们自己的以时间和4个像素的鼠标滞后作用的“mouseReallyClicked()真实的鼠标单击”方法。

(5) 蹩脚的组件继承

另一种做法是调用enableEvent()方法,并将与希望控制的事件对应的模型传递给它(许多参考书中都曾提及这种做法)。这样做会造成那些事件被发送至老式方法(尽管它们对Java 1.1来说是新的),并采用象processFocusEvent()这样的名字。也必须要记住调用基类版本。下面是它看起来的样子。

  1. //: BadTechnique.java
  2. // It's possible to override components this way,
  3. // but the listener approach is much better, so
  4. // why would you?
  5. import java.awt.*;
  6. import java.awt.event.*;
  7. class Display {
  8. public static final int
  9. EVENT = 0, COMPONENT = 1,
  10. MOUSE = 2, MOUSE_MOVE = 3,
  11. FOCUS = 4, KEY = 5, ACTION = 6,
  12. LAST = 7;
  13. public String[] evnt;
  14. Display() {
  15. evnt = new String[LAST];
  16. for(int i = 0; i < LAST; i++)
  17. evnt[i] = new String();
  18. }
  19. public void show(Graphics g) {
  20. for(int i = 0; i < LAST; i++)
  21. g.drawString(evnt[i], 0, 10 * i + 10);
  22. }
  23. }
  24. class EnabledPanel extends Panel {
  25. Color c;
  26. int id;
  27. Display display = new Display();
  28. public EnabledPanel(int i, Color mc) {
  29. id = i;
  30. c = mc;
  31. setLayout(new BorderLayout());
  32. add(new MyButton(), BorderLayout.SOUTH);
  33. // Type checking is lost. You can enable and
  34. // process events that the component doesn't
  35. // capture:
  36. enableEvents(
  37. // Panel doesn't handle these:
  38. AWTEvent.ACTION_EVENT_MASK |
  39. AWTEvent.ADJUSTMENT_EVENT_MASK |
  40. AWTEvent.ITEM_EVENT_MASK |
  41. AWTEvent.TEXT_EVENT_MASK |
  42. AWTEvent.WINDOW_EVENT_MASK |
  43. // Panel can handle these:
  44. AWTEvent.COMPONENT_EVENT_MASK |
  45. AWTEvent.FOCUS_EVENT_MASK |
  46. AWTEvent.KEY_EVENT_MASK |
  47. AWTEvent.MOUSE_EVENT_MASK |
  48. AWTEvent.MOUSE_MOTION_EVENT_MASK |
  49. AWTEvent.CONTAINER_EVENT_MASK);
  50. // You can enable an event without
  51. // overriding its process method.
  52. }
  53. // To eliminate flicker:
  54. public void update(Graphics g) {
  55. paint(g);
  56. }
  57. public void paint(Graphics g) {
  58. g.setColor(c);
  59. Dimension s = getSize();
  60. g.fillRect(0, 0, s.width, s.height);
  61. g.setColor(Color.black);
  62. display.show(g);
  63. }
  64. public void processEvent(AWTEvent e) {
  65. display.evnt[Display.EVENT]= e.toString();
  66. repaint();
  67. super.processEvent(e);
  68. }
  69. public void
  70. processComponentEvent(ComponentEvent e) {
  71. switch(e.getID()) {
  72. case ComponentEvent.COMPONENT_MOVED:
  73. display.evnt[Display.COMPONENT] =
  74. "Component moved";
  75. break;
  76. case ComponentEvent.COMPONENT_RESIZED:
  77. display.evnt[Display.COMPONENT] =
  78. "Component resized";
  79. break;
  80. case ComponentEvent.COMPONENT_HIDDEN:
  81. display.evnt[Display.COMPONENT] =
  82. "Component hidden";
  83. break;
  84. case ComponentEvent.COMPONENT_SHOWN:
  85. display.evnt[Display.COMPONENT] =
  86. "Component shown";
  87. break;
  88. default:
  89. }
  90. repaint();
  91. // Must always remember to call the "super"
  92. // version of whatever you override:
  93. super.processComponentEvent(e);
  94. }
  95. public void processFocusEvent(FocusEvent e) {
  96. switch(e.getID()) {
  97. case FocusEvent.FOCUS_GAINED:
  98. display.evnt[Display.FOCUS] =
  99. "FOCUS gained";
  100. break;
  101. case FocusEvent.FOCUS_LOST:
  102. display.evnt[Display.FOCUS] =
  103. "FOCUS lost";
  104. break;
  105. default:
  106. }
  107. repaint();
  108. super.processFocusEvent(e);
  109. }
  110. public void processKeyEvent(KeyEvent e) {
  111. switch(e.getID()) {
  112. case KeyEvent.KEY_PRESSED:
  113. display.evnt[Display.KEY] =
  114. "KEY pressed: ";
  115. break;
  116. case KeyEvent.KEY_RELEASED:
  117. display.evnt[Display.KEY] =
  118. "KEY released: ";
  119. break;
  120. case KeyEvent.KEY_TYPED:
  121. display.evnt[Display.KEY] =
  122. "KEY typed: ";
  123. break;
  124. default:
  125. }
  126. int code = e.getKeyCode();
  127. display.evnt[Display.KEY] +=
  128. KeyEvent.getKeyText(code);
  129. repaint();
  130. super.processKeyEvent(e);
  131. }
  132. public void processMouseEvent(MouseEvent e) {
  133. switch(e.getID()) {
  134. case MouseEvent.MOUSE_CLICKED:
  135. requestFocus(); // Get FOCUS on click
  136. display.evnt[Display.MOUSE] =
  137. "MOUSE clicked";
  138. break;
  139. case MouseEvent.MOUSE_PRESSED:
  140. display.evnt[Display.MOUSE] =
  141. "MOUSE pressed";
  142. break;
  143. case MouseEvent.MOUSE_RELEASED:
  144. display.evnt[Display.MOUSE] =
  145. "MOUSE released";
  146. break;
  147. case MouseEvent.MOUSE_ENTERED:
  148. display.evnt[Display.MOUSE] =
  149. "MOUSE entered";
  150. break;
  151. case MouseEvent.MOUSE_EXITED:
  152. display.evnt[Display.MOUSE] =
  153. "MOUSE exited";
  154. break;
  155. default:
  156. }
  157. display.evnt[Display.MOUSE] +=
  158. ", x = " + e.getX() +
  159. ", y = " + e.getY();
  160. repaint();
  161. super.processMouseEvent(e);
  162. }
  163. public void
  164. processMouseMotionEvent(MouseEvent e) {
  165. switch(e.getID()) {
  166. case MouseEvent.MOUSE_DRAGGED:
  167. display.evnt[Display.MOUSE_MOVE] =
  168. "MOUSE dragged";
  169. break;
  170. case MouseEvent.MOUSE_MOVED:
  171. display.evnt[Display.MOUSE_MOVE] =
  172. "MOUSE moved";
  173. break;
  174. default:
  175. }
  176. display.evnt[Display.MOUSE_MOVE] +=
  177. ", x = " + e.getX() +
  178. ", y = " + e.getY();
  179. repaint();
  180. super.processMouseMotionEvent(e);
  181. }
  182. }
  183. class MyButton extends Button {
  184. int clickCounter;
  185. String label = "";
  186. public MyButton() {
  187. enableEvents(AWTEvent.ACTION_EVENT_MASK);
  188. }
  189. public void paint(Graphics g) {
  190. g.setColor(Color.green);
  191. Dimension s = getSize();
  192. g.fillRect(0, 0, s.width, s.height);
  193. g.setColor(Color.black);
  194. g.drawRect(0, 0, s.width - 1, s.height - 1);
  195. drawLabel(g);
  196. }
  197. private void drawLabel(Graphics g) {
  198. FontMetrics fm = g.getFontMetrics();
  199. int width = fm.stringWidth(label);
  200. int height = fm.getHeight();
  201. int ascent = fm.getAscent();
  202. int leading = fm.getLeading();
  203. int horizMargin =
  204. (getSize().width - width)/2;
  205. int verMargin =
  206. (getSize().height - height)/2;
  207. g.setColor(Color.red);
  208. g.drawString(label, horizMargin,
  209. verMargin + ascent + leading);
  210. }
  211. public void processActionEvent(ActionEvent e) {
  212. clickCounter++;
  213. label = "click #" + clickCounter +
  214. " " + e.toString();
  215. repaint();
  216. super.processActionEvent(e);
  217. }
  218. }
  219. public class BadTechnique extends Frame {
  220. BadTechnique() {
  221. setLayout(new GridLayout(2,2));
  222. add(new EnabledPanel(1, Color.cyan));
  223. add(new EnabledPanel(2, Color.lightGray));
  224. add(new EnabledPanel(3, Color.yellow));
  225. // You can also do it for Windows:
  226. enableEvents(AWTEvent.WINDOW_EVENT_MASK);
  227. }
  228. public void processWindowEvent(WindowEvent e) {
  229. System.out.println(e);
  230. if(e.getID() == WindowEvent.WINDOW_CLOSING) {
  231. System.out.println("Window Closing");
  232. System.exit(0);
  233. }
  234. }
  235. public static void main(String[] args) {
  236. Frame f = new BadTechnique();
  237. f.setTitle("Bad Technique");
  238. f.setSize(700,700);
  239. f.setVisible(true);
  240. }
  241. } ///:~

的确,它能够工作。但却实在太蹩脚,而且很难编写、阅读、调试、维护以及复用。既然如此,为什么还不使用内部接收器类呢?