您的位置:寻梦网首页编程乐园Java天地Core JavaJava Lecture Notes

previous.gif
 (3087 bytes) next.gif
 (2959 bytes)


Extend Index Extend Page # 4

Using AWT objects together

One object is placed inside another, or attached to another, by using the add() method. Objects can be added inside other objects which in turn are inside other objects, giving a nested structure.

The overal layour is controlled by the Layout Manager (discussed later in this unit).

This example shows how a Menu object (labelled 'File') is created, and menu items 'Open', 'Save' and 'Exit' placed inside it.

Menu fileMenu = new Menu("File");

MenuItem openMenuItem = new MenuItem ("Open");

MenuItem saveMenuItem = new MenuItem ("Save");

MenuItem exitMenuItem = new MenuItem ("Exit");

FileMenu.add(openMenuItem);

FileMenu.add(saveMenuItem);

FileMenu.add(exitMenuItem);

This menu cannot be placed in an applet because a Menu must be part of a MenuBar. So we need to create a MenuBar and put the menu in that:

MenuBar menuBar = new MenuBar();

menuBar.add(fileMenu);

Now we can put the menu in an window. In the window's constructor, we would write:

add(menuBar);

If we want an applet to contain a text field and a list box we could write in the applet's constructor:

TextField textField = new TextField();

List list = new List();

add(textField);

add(list);

The positions of the text field and the list box will depend on the size of the applet in which they are being placed. If there is room to show them side-by-side, the standard layout manager will place them like this. However, if there is not room it will place one above the other. Each AWT object that can contain other objects is assisted by a layour manager whose job it is to keep the objects in an orderly arrangement.

Take another look at the application:               FrameMenu1.java

Back to top

basicline.gif (170 bytes)