现在的位置: 首页 > 综合 > 正文

JAVA图形编程入门(连载6)

2013年08月19日 ⁄ 综合 ⁄ 共 28329字 ⁄ 字号 评论关闭

556 Understanding Input Focus

556 了解输入焦点(InputFocus)

As was the case in the loan_cal.java applet, manyprograms contain multiple data-entry fields. In a program that has more thanone data-entry field, the typed text is only entered into one data entry fieldat a time. The input focus
decides which component receives keyboard events. Tomove the input focus from one component to another, the user can simply clickon a different component.

就象小应用程序loan_cal.java那样,许多程序含有多个数据输入字段(data-entry field)。在有多于一个数据输入字段的程序中,被输入的文本每次只进入一个数据输入字段。输入焦点用来决定哪一组件(component)接受键盘的输入。如果要把输入焦点从一个组件移到另一个组件,用户只需简单地点击不同位置的组件即可。

 

Java applets always provide some visual indicationthat shows which component has the input focus. On the Windows platform, ablinking vertical bar (the cursor) indicates that a TextField component has theinput focus. Likewise,
Java displays a dotted rectangle around a Buttoncomponent to indicate it has the input focus.

Java小应用程序总是提供某种显眼的记号来说明输入焦点在哪一组件上。在Windows平台上,一个闪烁的竖棒(光标)说明了输入焦点位于某个文本字段(TextField)组件上。同样,Java围绕Button组件显示了一个虚线框,表示输入焦点位于这一按钮上。

 

Although you can let the user change the inputfocus by clicking on the component, there may be times when you want yourapplet to set the input focus to a specific component. For example, you maywant to set the focus to the TextField
where the user entered an invalid entry.The Component class offers several methods for controlling and tracking theinput focus, as listed in Table 556.

用户通过点击某个组件可以改变输入焦点,但有时你希望你的小应用程序的输入焦点设在某个指定的组件上。例如,你希望把输入焦点设在用户输入了一个无效参数的文本字段上。Component类提供了几种控制输入焦点以及输入焦点导航的方法,如表556所列。

 

Method         purpose

方法           用途

--------------------------------------------------------------------------

gotFocus       Called when the component receives theinput focus

               当组件接受输入焦点时调用

lostFocus      Called when the component loses the inputfocus

               当组件离开输入焦点时调用

requestFocus   Requests the input focus for the component

               某组件请求输入焦点

nextFocus      Moves the input focus to the nextcomponent

               移动输入焦点至下一组件

-------------------------------------------------------------------------

Table 556Component class methods that manipulate the input focus.

表556 控制输入焦点的Component类方法

 

Note: The gotFocus and lostFocus methods are notyet fully implemented in the JDK version 1.0.2.

注: gotFocus方法与lostFocus方法在 1.0.2版JDK 中尚未完全实现。

 

557 Using tab Key to Move from One Input Field to theNext

557 使用tab键将输入焦点从一个字段移动到另一个字段

When a graphical user interface contains multipledata-input components, it is customary to let the user jump from one inputfield to another using the Tab key. This feature is especially useful when theuser must enter many text
entries. In other words, the user can enter data onall input fields without moving back and forth between the keyboard and themouse.

当一图形输入接口包含多种数据输入组件时,习惯上可以通过Tab键来转换输入。当用户必须打入多个文本参数时这个功能就显得尤为有用。换言之,用户可以在所有输入字段中直接打入数据而不必在键盘和鼠标之间频繁改换。

In Tip 556, you learned that you can control theinput focus by using the requestFocus and nextFocus methods. The following codefragment shows you how to use requestFocus and nextFocus methods to let a usercycle through input fields
when using the Tab key. Add this code to theloan_cal.java applet you created in Tip xxx to let the user move quickly fromone field to the next:

在TIP556中,你已知道通过requestFocus和nextFocus方法来控制输入焦点,以下的代码段向你展示了如何使用requestFocus和nextFocus方法让用户利用Tab键在各输入字段间周转循环。把下列代码加到你在TIPxxx里所创造的小应用程序loan_cal.java中让用户从一字段快速移到另一字段。

 

replace xxx

 

public booleankeyDown(Event evt, int key)

  {

    if ((char)key == \t)

      {

        Component current_field =(Component)evt.target;

 

        if (current_field != button)

          current_field.nextFocus();

        else

          apr_entry.requestFocus();

    

        return true;  

      }

    return false;

  }

 

When Java detects a Tab-key event, the appletcalls the nextFocus method to move the input focus to the next component. Whenthe Calculate button, which is the last component, has the input focus, theapplet calls requestFocus to
move the input focus back to the first data inputfield.

当Java探测到一个Tab键事件,小应用程序调用方法nextFocus把输入焦点移动到下一个组件。当输入焦点位于最后一个组件Calculate按钮上时,小应用程序调用requestFocus方法把输入焦点再移回到第一个数据输入字段。

 

558 Creating Frames

558 创建窗口框架(Frames)

Each of the previous applets placed all of theirgraphical-user interface elements inside the original applet window, which isinside an HTML page. There may be times, however, when you want to create aseparate pop-up window for
such elements. For example, you may want to create afloating tool palette for a drawing applet. In such cases, you can use theFrame class to create a pop-up window by performing these steps:

前面的每个小应用程序把它们的图形输入接口元素布置在原始小应用程序窗口中,这个窗口位于HTML页中。但有时你会想要为这些元素创建一个独立的弹出窗口。例如,你可能希望为作图程序创建一个浮动的工具条(pelette)。在这种情况下,你可利用Frame类通过以下步骤创建一个弹出窗口:

1.

Create a Frame object using the Frame class or asubclass of Frame. In many cases, you may want to create your own class andextend the Frame class to override some of the methods. You can use one of thefollowing constructors to
create a Frame object:

用Frame类或Frame类的子类来创建一个Frame对象。在很多情况下,你可能要创建自己的类或扩展Frame类来复盖某些方法。你可以用以下构造函数之一来创建Frame对象:

Frame();

Frame(String title);

 

The second form of the Frame constructor sets thedialog box title to the title parameter.

构造函数Frame的第二种形式把对话框的标题设置在参数title中。

 

2.

Call the resize method to set the Frame objectsinitial size. You may also add components to the Frame using the add method.Alternatively, you can call the pack method to let Java determine the properwindow size. If you use the
pack method, you should add all the components tothe Frame object first before calling pack.

调用resize方法把Frame对象设成为初始的大小。你也可以用add方法把组件加入Frame中。或者,你可以调用pack方法让Java来确定适当的窗口大小。如果你用pack方法,则你必须在调用之前, 先把所有的组件加入到对象Frame中。

 

3.

Call the show method to display the window.

The following applet, applet_frame.java,illustrates the process of using Frame objects. The applet creates a new pop-upwindow each time the user presses the New Frame button. Figure 558 illustratesthe programs output.

3. 调用show方法显示窗口

下面小应用程序applet_frame.java说明了Frame对象的使用过程。每当用户按下 NewFrame 按钮时,小应用程序便创建了一个新的弹出窗口。图558说明了程序的输出。

 

import java.applet.*;

import java.awt.*;

 

public classapplet_frame extends Applet {

 

   public void init()

     { 

       add(new Button("New Frame"));

     }

  

   public boolean action(Event evt, Object arg)

     {

       if (evt.target instanceof Button)

         {

           Frame f = new Frame();

           f.resize(200, 100);

           f.add("Center", newLabel("A Frame", Label.CENTER));

        

           f.show();

           return true;  // event processed 事件已处理

         }

      return false;      // event not processed 事件未处理

   }

 }

 

 

Figure 558 An applet with pop-up windows.

Figure 558 带有弹出窗口的小应用程序

 

559 Destroying a Frame Object Using the dispose Method

559 利用dispose方法消去一个Frame对象

 

One of the problems with using pop-upwindows, as discussed in the previous tip, is that you cannot close the window,even when you click on the Frame objects close button. To destroy a pop-upwindow that you create using a Frame,
you must call the dispose method. Thedispose method closes the Frame window and releases its resources. Thefollowing applet, frame_dispose.java, expands on the applet_frame.java appletyou created in Tip 558. The frame_dispose.java applet adds the PopupFrame
classand extends the Frame class. In addition, the applet overrides the handleEventmethod to track the WINDOW_DESTROY event and to dispose of the frame:

 

以上已提到, 利用弹出窗口的问题之一就是你不能关闭窗口,哪怕点击了Frame对象的

close 按钮。要消除你用Frame对象创立的弹出窗口,必须调用dispose方法。dispose

方法关闭了Frame窗口并释放了它的资源。以下的小应用程序frame_dispose.java扩展

了你在TIP558中创建的applet_frame.java小应用程序. Frame_dispose.java 小应用

程序增加了PopupFrame类并扩展了Frame类。另外,小应用程序复盖了handleEvent方

法以跟踪WINDOW_DESTROY事件并消毁Frame:

import java.applet.*;

import java.awt.*;

 

class PopupFrameextends Frame {

 

   public boolean handleEvent(Event evt)

     {

       if (evt.id == Event.WINDOW_DESTROY)

         dispose();

   

      return super.handleEvent(evt);

   }

}

 

public classframe_dispose extends Applet {

 

   public void init()

     {

       add(new Button("New Frame"));

     }

  

   public boolean action(Event evt, Object arg)

     {

       if (evt.target instanceof Button)

         {

           PopupFrame f = new PopupFrame();

           f.resize(200, 100);

           f.add("Center", newLabel("A Frame", Label.CENTER));

        

           f.show();

           return true;  // event processed事件已处理

         }

       return false;     // event not processed 事件未作处理

     }

 }

 

560 Creating a Java Application with GUI Using Frame

560 利用Frame创建一个带有GUI的Java应用程序

Up to now, you have been creating graphical userinterfaces for Java applets. Now, it is time to create a Java application witha graphical-user interface. To create a Java application with a window, youmust use the Frame class
or a subclass to create the applications top-levelwindow. The following application, java_app.java, is a simple program thatcreates an application window and then draws a few shapes within the window.Remember that since this program is a Java application,
you use the Javainterpreter java and not the appletviewer to run the application. Figure 560illustrates the applications output:

到目前为止,你一直在为Java小应用程序创建图形用户接口。现在已到了创建带有图形用户接口的Java应用程序的时候了。要建立一个使用窗口Java应用程序,你必须利用Frame类或其子类来创建应用程序的最高级的窗口。下面的应用程序java_app.java就是一个简单的例子,它创建了一个应用程序窗口并再在窗口中画了少量图形。要记住由于这是一个Java应用程序,你要用Java解释器java而不是用小应用程序观察器来运行这一应用程序。图560说明了应用程序的输出:

 

 

import java.awt.*;

  

public class java_appextends Frame {

 

   public java_app(String title)

     {

       super(title);

     }

 

   public static void main(String args[])

     {

       java_app application = newjava_app("java_app");

       application.resize(300, 150);

       application.show();

     }

  

   public boolean handleEvent(Event evt)

     {

       if (evt.id == Event.WINDOW_DESTROY)

         System.exit(0); // exit theapplication退出应用程序

     

       return super.handleEvent(evt);

     }

  

   public void paint(Graphics g)

     {

       // draw a few shapes 画几个图形

       g.setColor(Color.blue);

       g.fillOval(90, 50, 100, 80);

       g.setColor(Color.red);

       g.fillRoundRect(10, 10, 150, 70, 50,25);

       g.setColor(Color.green);

       g.fillRect(150, 20, 50, 50);

     }

 }

 

Figure 560 A simple Java application running withina window.

图 560 一个在窗口中运行的简单Java应用程序

 

For a standalone application such as the programjust shown, it is important that you provide a mechanism that lets the userquit the program. At the very least, you should track the WINDOW_DESTROY eventof the top-level window and
exit the program when the event occurs. If you donot do that, the only way to stop the program is to hit Ctrl-Alt-Del or Ctrl -Cwithin the DOS shell on a Windows-based system. On a Solaris system, you mayhave to resort to using the kill command to kill the
Java application process.

对于上面这样的一个独立的应用程序,为用户提供一个退出程序的机制是很重要的。无论如何你至少应该跟踪顶层窗口中的WINDOW_DESTROY事件并在事件发生时退出程序。如果你不这么办,中止程序的唯一办法,在基于Windows系统的应用程序中,就是按Ctrl_Alt_Del或Ctrl-C。而在Solaris系统中你可能必须借助于kill命令来中止Java应用程序的进程。

 

561 Default Layout Manager is Different Between Appletand Application

561 小应用程序和应用程序的缺省布局管理器(Default Layout Manager)不同

As you have learned, you can add AWT components toan applet using the add method. You can also add components to Frame objectsyou create for a Java application. One thing to remember is that the default layoutmanager for an applet
and an application are different. The default layoutmanager for an applet, as inherited from the Panel class, is FlowLayout. Thedefault layout manager for a Java application, as inherited from the Frameclass, is BorderLayout.

你已知道可以利用add方法在一小应用程序中加进AWT组件。你也可以在为Java应用程序创建的Frame对象中加入组件。要记住的一件事情是: 小应用程序的缺省布局管理器和应用程序的缺省布局管理器是不同的。小应用程序的缺省布局管理器,作为Panel类的一个继承类是FlowLayout。而应用程序的缺省布局管理器,作为Frame类的继承类,是BorderLayout。

 

To change the layout manager of a Frame, you usethe setLayout method the same way that you would with an applet, as shown inthe following application, flow_frame.java:

为了改变一个Frame的布局管理器,你可利用setLayout方法,这和小应用程序使用的一致,如以下应用程序flow_frame.java所示:

import java.awt.*;

  

public classflow_frame extends Frame {

 

   String items[] = {"Mercury","Venus", "Earth", "Mars", "Saturn"};

   Button button[] = new Button[5];

     

   public flow_frame(String title)

     {

       super(title);

       setLayout(new FlowLayout());

 

       for (int i = 0; i < items.length;i++)

         {

           button[i] = new Button(items[i]);

           add(button[i]);

         }

     }

 

   public static void main(String args[])

     {

       flow_frame application = newflow_frame("flow_frame");

       application.resize(250, 150);

       application.show();

     }

  

   public boolean handleEvent(Event evt)

     {

       if (evt.id == Event.WINDOW_DESTROY)

         System.exit(0); // exit theapplication

     

       return super.handleEvent(evt);

     }

 }

As you can see, the flow_frame.java applicationchanges the layout manager to FlowLayout and then uses the layout manager todisplay several buttons.

你可看出,应用程序flow_frame.java把布局管理器改为FlowLayout,然后利用布局管理器来显示几个按钮。

 

562 Building a Compound Interest CalculationApplication

562 编写一个计算复利的应用程序

Everything you learned about using AWT componentsand layout managers in a Java applet also applies to building a Java application.In Tip xxx, for example, you learned how to build a loan payment calculationapplet using various
AWT components. In a similar way, the savings_cal.javaapplication that follows combines various AWT components to build asavings-calculator application. The savings_cal.java application calculates theprojected savings for the specified monthly contribution,
interest rate, andlength of the savings. Figure 562 illustrates the applications output:

你所知道的有关Java小应用程序中AWT组件和布局管理器用法的每一桩事情也可用来编写Java应用程序。例如在TIP554中,你已知道怎样利用各种AWT组件编写一个计算利息的小应用程序。用类似的方法,以下的应用程序savings_cal.java是结合了各种AWT组件编写成的一个计算利息的应用程序。应用程序savings_cal.java为已知的月投入、利率、和储蓄期长,来计算计划储蓄。图562是应用程序的输出结果:

import java.awt.*;

  

public classsavings_cal extends Frame {

 

   TextField apr_entry = newTextField("",15);

   TextField years_entry = newTextField("",15);

   TextField payment_entry = newTextField("",15);

   Label total_amt = new Label("",Label.LEFT);

   Button button = newButton("Calculate");

 

   // Method for calculating monthly loanpayment 

     

   double calc_savings(double apr, double amt,int years)

     {

       int no_of_payments = years * 12;          // no of payments

       double monthly_rate = 1.0 + apr /1200.0; // rate + 1.0

       double total = 0;                    

  

       // Calculate the total saving

       for (int i = 0; i < no_of_payments;i++)

        {

          total += amt;

          total *= monthly_rate;

        }

 

       // Return total saved amount plus interest

       return(total);

     }

 

   public savings_cal(String title)

     {

       super(title);

       setLayout(new GridLayout(5,2,3,2));

       add(new Label("Interest Rate APR%:", Label.RIGHT));

       add(apr_entry);

       add(new Label("No. of Years:",Label.RIGHT));

       add(years_entry);

       add(new Label("Monthly Contribution$:", Label.RIGHT));

       add(payment_entry);

       add(new Label("Total Savings$:", Label.RIGHT));

       add(total_amt);

       add(new Label());

       add(button);

     }

 

   public static void main(String args[])

     {

       savings_cal application = newsavings_cal("savings_cal");

       application.pack();

       application.show();

     }

  

   public boolean action(Event evt, Object arg)

     {

       double apr, monthly_amt, total_saving;

       int years;

      

       if (evt.target == button)

         { // Collect the user entries

           apr =Double.valueOf(apr_entry.getText()).doubleValue();

           monthly_amt = Double.valueOf(

              payment_entry.getText()).doubleValue();

          years=Integer.valueOf(years_entry.getText()).intValue();

        

           // Calculate the total savings

           total_saving = calc_savings(apr,monthly_amt, years);

        

           // Set payment label to thecalculated result

          total_amt.setText(String.valueOf(total_saving));

           return true;  // event processed

         }

       return false;     // event not processed

     }

 

   public boolean handleEvent(Event evt)

     {

       if (evt.id == Event.WINDOW_DESTROY)

         System.exit(0); // exit theapplication

     

       return super.handleEvent(evt);

     }

 }

 

 

Figure 562 A Savings calculator application.

图562 一个省钱的计算器应用程序

 

563 Changing Your Cursor

563 改变光标

As you may have noticed, the default cursor in aFrame object is an arrow. Depending on your applets purpose, there may be timeswhen you will want to use a different cursor. For example, you may want tochange to a cross-hair cursor
in a CAD drawing application. Although thecurrent version of Javas AWT does not let you create your own cursor, you canselect a cursor from a set of predefined cursors. To change a Frame objectscursor, you use the Frame class setCursor method, the format of
which is asfollows:

你可能已注意到在一Frame对象中的缺省光标是一箭头。根据你的小应用程序的用途,你有时可能希望使用不同的光标。例如,在一个CAD绘图程序中你会希望使用十字光标。目前的各种Java开发工具还不能让你创建自己的光标,但可以让你在预定义的一组光标中进行选择。为了改变Frame对象所用光标,你可使用Frame类的setCursor方法,它的格式如下:

void setCursor(intcursorType);

 

You set the cursorType parameter to one of the variablesdefined within the Frame class, such as Frame.WAIT_CURSOR. For example, thefollowing statement selects the cross-hair cursor:

其中参数cursorType可设成在Frame类中已定义的某个变量,诸如 Frame.WAIT_CURSOR等。例如以下语句选用了十字光标:

setCursor(Frame.CROSSHAIR_CURSOR);

 

The following application, cursor.java, lets youset the cursor using a Choice list. Figure 563 displays the programs output:

下列的应用程序cursor.java可让你利用一个选择清单来设置光标。图563显示了程序的输出结果:

import java.awt.*;

  

public class cursorextends Frame {

 

   String items[] = {"DEFAULT","CROSSHAIR","TEXT","WAIT",

     "SW_RESIZE","SE_RESIZE","NW_RESIZE","NW_RESIZE",

     "NE_RESIZE","N_RESIZE","S_RESIZE","W_RESIZE","E_RESIZE",

     "HAND", "MOVE"};

 

   int cursors[]={ Frame.DEFAULT_CURSOR,Frame.CROSSHAIR_CURSOR,

                   Frame.TEXT_CURSOR,Frame.WAIT_CURSOR,

                   Frame.SW_RESIZE_CURSOR,Frame.SE_RESIZE_CURSOR,

                   Frame.NW_RESIZE_CURSOR,Frame.NW_RESIZE_CURSOR,

                   Frame.NE_RESIZE_CURSOR,Frame.N_RESIZE_CURSOR,

                   Frame.S_RESIZE_CURSOR,Frame.W_RESIZE_CURSOR,

                   Frame.E_RESIZE_CURSOR,Frame.HAND_CURSOR,

                   Frame.MOVE_CURSOR };

 

   Choice choice = new Choice();

     

   public cursor(String title)

     {

        super(title);

 

        for (int i = 0; i < items.length; i++)

          choice.addItem(items[i]);

     

        add("North", choice);

     }

 

   public static void main(String args[])

     {

       cursor application = newcursor("cursor");

       application.resize(250, 150);

       application.show();

     }

  

   public boolean action(Event evt, Object arg)

     {

       if (evt.target instanceof Choice)

         { 

          setCursor(cursors[choice.getSelectedIndex()]);

           return true;    // event processed

         }

        return false;      // event not processed

     }

  

   public boolean handleEvent(Event evt)

     {

       if (evt.id == Event.WINDOW_DESTROY)

         System.exit(0); // exit theapplication

     

       return super.handleEvent(evt);

     }

 }

 

 

Figure 563 An Application frame with a non-defaultcursor.

图563 使用非缺省光标的应用程序框架

 

 

564 Setting the Frame Title

564 设置框架标题

As you know, it is customary for a Windows-basedapplication to display its name at the top of the window, and for an applicationthat displays files to display the name of the current file along withapplication name. By default,
Frame objects use the title Untitled. To assign atitle to a Frame object, use the following form of the Frame constructormethod:

你已知道在Windows应用程序中习惯于把程序的名称显示在窗口的顶部,并为显示文件的应用程序显示当前文件名和应用程序名。在缺省时,Frame对象使用标题Untitled。为了把一个标题赋给Frame对象,你可使用以下形式的Frame构造函数方法:

Frame(String title);

 

If you want to change the title after the applethas constructed the Frame, use the setTitle method, the format of which is as follows:

如果你要在小应用程序已构造了Frame之后来改变标题,则可利用setTitle 方法,它的格式如下:

void setTitle(Stringtitle);

 

For example, the following statements use thesetTitle method to rename a Frame object:

例如,以下语句利用 setTitle 方法重新命名了Frame对象:

Frame f;

f.setTitle(My JavaApplication);

 

565 Changing Icon Image

565 改变图标的图象

When a frame is minimized, Java displays an iconimage. By default, the icon image is a Java coffee cup. To differentiate oneminimized application from another, you may want to change the Frame objectsicon image. To set a new icon
image, use the Frame class setIconImage method:

当一窗口框架被最小化时,Java将显示一个图标图象。缺省时, 图标图象是一个Java咖啡杯。为了将各种最小化的应用程序区别开来,你可能要改变Frame对象的图标图象。为了设置一个新的图标图象,你可利用Frame类中的 setIconImage 方法:

voidsetIconImage(Image image);

 

For example, the following statements assign a newicon image to a Frame object:

例如,以下语句将一个新的图标图象new_icon赋给了Frame对象:

Image new_icon;

// Statements tocreate the icon here

Frame f;

f.setIconImage(new_icon);  // Assign the icon

 

Note: Under Java version 1.0.2on the Windows 95 platform, the setIconImage method has no effect on the icon.However, the method does work properly under Solaris.

注意,在 Windows 95平台上的 1.0.2版Java下,setIconImage 方法对图标没有作用。但在Solaris平台上是确实能够工作的。

 

566 Adding a Pull-down Menu to Your Frame

566 在窗口框架中加入下拉菜式选单

A pull-down menu is a common element in mostgraphical user interfaces. Pull-down menus provide a familiar interface betweendifferent applications and greatly reduce the users learning curve for a newapplication. When users see
a File menu Open option within an application, theywill automatically know that option lets them load an existing file into theapplication. To create a pull-down menu within a Java program, perform thefollowing steps:

在大多数图形用户接口中,下拉式选单是一种很普通的构件。下拉式选单在不同的应用程序之间提供了人们都熟悉的一种界面,大大减少了用户学习各种新软件时所走的弯路。当用户看到一个File选单的Open选项时,他们就自动知道选项可以将已存在的文件装入应用程序中。为了在Java程序中创建一个下拉选单,需执行下列步骤:

1.

Create a MenuBar object by using the MenuBarconstructor, and set the object as the Frame objects menubar using thesetMenuBar method:

1. 利用构造函数MenuBar创建一个MenuBar对象(选单条),然后利用方法setMenuBar把对象设为Frame对象的选单条:

MenuBar menubar = newMenuBar();

setMenuBar(menubar);

2.

Create your menus by using the Menu constructor,and then add the menus to the menu-bar using the Menu class add method:

2. 利用构造函数Menu创建你的各种选单,然后用Menu类的add方法把这些选单加进选单

条中:

Menu file_menu = newMenu(File);

Menu edit_menu = newMenu(Edit);

menubar.add(file_menu);

menubar.add(edit_menu);

3.

Create and add items to each menu. The menu itemscan be a MenuItem object, a CheckboxMenuItem object, a separator, or submenus.You create MenuItem objects using the MenuItem constructor, and you add theobject to the menu using
the Menu class add method:

3.在每一个选单中加入项。选单项可以是一个 MenuItem 对象、一个CheckboxMenuItem对象、一个隔离符(separator)、或者一个子选单(submenus)。

file_menu.add(newMenuItem(Open));

file_menu.add(newMenuItem(Save));

edit_menu.add(newMenuItem(Cut));

 

Another form of the Menu class add method createsa MenuItem for the specified label and adds it to the menu in one step:

Menu类add方法的另一形式用来为指定的标记创建选单项,并用一步将其加入选单中:

void add(Stringlabel);

 

In this way, you can add the same menu items tothe menus shown previously by using the following statements:

采用这一方式,你同样可以在选单中加入前面所示的那些项,为此要以下的语句:

file_menu.add(Open);

file_menu.add(Save);

edit_menu.add(Cut);

 

Subsequent tips in this section will show you howto create Checkbox menu items, separators, and submenus. The followingapplication, menu_test.java, illustrates the process of adding a pull-down menuto a Java application. Figure
566 illustrates the programs output.

本节以下的一些TIP将向你展示怎样创建Checkbox选单项、隔离符、和子选单。以下的应用程序menu_test.java示范了在Java应用程序中加入下拉式选单的过程。图566 说明了程序的输出.

import java.awt.*;

 

public class menu_testextends Frame {

 

   MenuBar menubar = new MenuBar();

   Menu file = new Menu("File",true);

   Menu edit = new Menu("Edit",true);

 

   public menu_test(String title)

     {

       super(title);

       setMenuBar(menubar);

       menubar.add(file);

       menubar.add(edit);

       file.add("New");

       file.add("Open");

       file.add("Save");

       edit.add("Cut");

       edit.add("Copy");

       edit.add("Paste");

     }

 

   public static void main(String args[])

     {

       menu_test application = newmenu_test("menu_test");

       application.resize(250, 125);

       application.show();

     }

  

   public boolean handleEvent(Event evt)

     {

       if (evt.id == Event.WINDOW_DESTROY)

         System.exit(0);

 

       return super.handleEvent(evt);

     }

 }

 

 

Figure 566 An Application with a pull-down menu.

图556 使用下拉式选单的一个应用程序

Keep in mind that you can only add pull-down menusto a Frame class object or subclass of the Frame class. Therefore, you cannotadd a pull-down menu to an applet window directly.

要记住你只能把下拉选单加入Frame类对象或Frame类的子对象。因此,你不能把下拉选单直接加入小应用程序窗口中。

 

567 Tracking Menu Item Events

567 跟踪选单项事件

In the previous Tip, you learned how to create amenu within a Java program. For your program to respond when the user selects amenu item, you must be able to detect the menu item events. As it turns out,Java generates an action
event each time the user selects a menu item. You canintercept the action event by overriding the action method. Add the followingcode segment to the menu_test.java applet that you created in Tip

566 to detect menu item events:

在上一TIP中你已知怎样在一Java程序中创建一个选单。为了使你的程序在用户选择了一个选单项时能作出响应,你必须了解程序怎样来检测选单项事件。事实上, 每当用户选择了一个选单项时,Java产生一个Action事件。你可利用action方法来接受这一Action事件。请把以下的代码段加入TIP566所创建的小应用程序中来检测选单项事件:

public booleanaction(Event evt, Object arg)

  {

    if (evt.target instanceof MenuItem)

      {

        if (arg.equals(Open))

          System.out.println(File openselected!);

        else if(arg.equals(Save))

          System.out.println(File saveselected!);

 

        // repeat comparison for other menuitems        

           重复为其它选单项进行比较

        return true;   // event processed 事件已处理

      }

    return false;      // event not processed 事件未作处理

}

The action methods second parameter, arg, containsthe label of the selected menu item. You can use this parameter to determinewhich menu item the user selected.

以上程序中,action方法的第二个参数arg包含被选的选单项的标记,你可利用此参数来确定用户选择的是哪一个选单项。

 

568 Using a Separator Line to Break Up Menu Items

568 利用分隔线来分开不同种类的选单项

When your programs use Menu objects, it is goodpractice to add separator lines to break up menu items. For example, within aFile menu, you may want to separate the Open and Save options from theprinting-related items. Adding a
separator to a menu is similar to adding aMenuItem object. You create a MenuItem labeled - to make a menu separator andthen add the item to the menu using the add method, as shown:

当你的程序使用Menu对象时,一种好的作法是加入分隔线来分开选单项。例如,在一File 选单中,你可以要求把Open 和 Save 选项与打印输出有关的各种选项分隔开来。在选单中加入分隔线和在选单中加入选单项对象的做法是类似的。为了造出一个选单分隔符,你要创建一个标着'-'的选单项,然后用add方法把此项加进选单中,如:

Menu menu;

menu.add(newMenuItem(-));

 

However, a simpler way to create and add menuseparators is to use the Menu class addSeparator method, as shown:

但是,创建选单分隔线并在选单中加入选单分隔线的一种更简便的方法是利用Menu类的addSeparator 方法,如下所示:

Menu menu;

menu.addSeparator();

 

The following application, separator.java, addsseveral separators to its pull-down menus. Figure 568 illustrates the programsoutput:

以下的应用程序separator.java在下拉式选单中加入了几根分隔线。图568表示程序的输出:

 

import java.awt.*;

 

public class separatorextends Frame {

 

   MenuBar menubar = new MenuBar();

   Menu file = new Menu("File",true);

 

   publicseparator(String title)

     {

       super(title);

       setMenuBar(menubar);

       menubar.add(file);

       file.add("New");

       file.add("Open");

       file.add("Close");

       file.addSeparator();

       file.add("Save");

       file.add("Save As");

       file.addSeparator();

       file.add("Print");

       file.add("Printer Setup");

       file.addSeparator();

       file.add("Quit");

     }

 

   public static void main(String args[])

     {

       separator application = new separator("separator");

       application.resize(250, 125);

       application.show();

     }

  

   public boolean handleEvent(Event evt)

     {

       if (evt.id == Event.WINDOW_DESTROY)

         System.exit(0);

     

       return super.handleEvent(evt);

     }

 }

 

 

Figure 568 A Menu with separators.

图568 带分隔线的选单

 

569 How to Create Submenus

569 怎样创建子选单

In Tip 568, you learned that you can organize menuitems into groups using separator lines. In addition, you can also use submenusto organize menu items. Submenus are particularly useful when you have a largenumber of menu items.
Within a menu, the submenus choices are hidden unless theuser selects the submenu option. To create a submenu, you add a Menu object toan existing Menu object. For example, the following application, submenu.java,creates a submenu under the File menu. Figure
568 illustrates the programsoutput.

在TIP568中,你已知道可以利用分隔线将选单中的项分成为组(group)。另外,你也可以用子选单的形式来组织选单的项。当你的选单有大量的选单项时子选单特别有用。在一选单中,子选单的选择在用户尚未选择这个子选单选项之前是不出现的。为了创建一个子选单,你可在一个已存在的Menu对象中加入Menu对象。例如,以下的应用程序submenu.java在File选单中创建了一个子选单。图568是该程序的输出。

import java.awt.*;

 

public class submenuextends Frame {

 

   MenuBar menubar = new MenuBar();

   Menu file = new Menu("File",true);

   Menu save_menu = new Menu("Save",true);

 

   public submenu(String title)

     {

       super(title);

       setMenuBar(menubar);

       menubar.add(file);

       file.add("New");

       file.add("Open");

       file.add("Close");

       file.add(save_menu);

       save_menu.add("Save Current");

       save_menu.add("Save As");

       save_menu.add("Save All");

       file.addSeparator();

       file.add("Quit");

     }

 

   public static void main(String args[])

     {

       submenu application = newsubmenu("submenu");

       application.resize(250, 125);

       application.show();

     }

  

   public boolean handleEvent(Event evt)

     {

       if (evt.id == Event.WINDOW_DESTROY)

         System.exit(0);

 

      return super.handleEvent(evt);

     }

 }

 

 

Figure 569 An application with submenus.

图567 使用子选单的应用程序

 

570 Adding a Checkbox Item to a Menu

570 在选单中加入检测框 

Several of the previous tips have examined how youuse menus within Java programs. In addition to displaying a simple labeled menuitem, you can also display menu items that have check marks. To display a menuitem with a check mark,
you first use the CheckboxMenuItem constructor methodto create a checkbox menu item. Next, you add the item to the menu using theadd method:

以上几个TIP考察了怎样在Java程序中使用选单。除了显示简单的选单项之外,你还可以显示具有check marks(检测记号)的选单项。为了显示具有check marks 的选单项,你首先要利用构造函数CheckboxMenuItem来创建一个Checkbox选单项。然后,你再利用add方法把此项加入选单中:

 

Menu menu;

menu.add(newCheckboxMenuItem(check item));

 

The check mark on the checkbox menu item toggleseach time the user selects the item. The following application, check_menu.java,creates a checkbox menu item, as shown in Figure 569:

每当用户选择Checkbox选单项上的check mark项时, 该项就会翻转. 以下的应用程序check_menu.java创建了一个Checkbox选单项,如图569所示:

{图569 还是 图570?}

 

import java.awt.*;

 

public classcheck_menu extends Frame {

 

   MenuBar menubar = new MenuBar();

   Menu font_menu = new Menu("Font",true);

 

   public check_menu(String title)

     {

        super(title);

        setMenuBar(menubar);

        menubar.add(font_menu);

        font_menu.add(newCheckboxMenuItem("Bold"));

        font_menu.add(newCheckboxMenuItem("Italic"));

        font_menu.add(newCheckboxMenuItem("Underline"));

     }

 

   public static void main(String args[])

     {

        check_menu application = newcheck_menu("check_menu");

        application.resize(250, 125);

        application.show();

     }

  

   public boolean handleEvent(Event evt)

     {

       if (evt.id == Event.WINDOW_DESTROY)

         System.exit(0);

     

       return super.handleEvent(evt);

     }

}

 

 

Figure 570 An application using checkbox menuitems.

图570 使用检测框选单项的一个应用程序

 

571 Getting and Setting a Checkbox Menu Item State

571 获取和设置检测框选单项的状态

As you learned in the previous tip, the user cantoggle a checkbox menu items state by selecting the menu item. To find outwhether the menu item is checked or not, call the CheckboxMenuItem classgetState method, whose method is
shown here:

在以上TIP中你已知道,用户可以通过选择检测框的选单项来使检测框选单项的状态翻转。为了查出这种选单项是否已被用户选中或未选中,可调用CheckboxMenuItem类的 getState 方法,它的格式如下:

boolean getState();

 

The getState method returns true if the menu itemis checked, and false otherwise.In a similar way, there may be times when youwant to set th

抱歉!评论已关闭.