Home | Blog | Java | Jokes | Poems | Musings | Site Map | Kudos | Downloads | Useful Sites | Interesting | System Setup | Contact

Home Page

AKGBackup - The backup program



Section 8 : The java.awt Package

Write code using component, container, and LayoutManager classes of the java.awt package to present a GUI with specified appearance and resize behavior, and distinguish the responsibilities of layout managers from those of containers.






Javaís components are implemented by many subclasses of the java.awt.Component and java.awt.MenuComponent superclasses. There are several methods that are implemented by all the visual and container components, by virtue of inheritance from Component. The menu components extend from MenuComponent, so they do not inherit the same super class functionality.



Returns Dimension, which has public data members width and height.


void setBackground() and setForeground()

if you do not explicitly set a componentís foreground and background colors, the component uses the colors of its immediate container. Some components on some platforms resist having their colors changed.


void setFont(Font f)

if you do not explicitly set a componentís font, the component uses the font of its container.


void setEnabled(boolean flag)

if the argument is true, then the component has its normal appearance, otherwise the component is grayed out and does not respond to user inputs.


setSize(int x, int y), setSize(Dimension d), setBounds(x, y, width, height), setBounds(Rectangle r)

the size and position that you attempt to give a component is overruled by a layout manager. In fact, these two methods exist mostly for the use of layout managers. The major exception to this rule is the Frame class, which is not under the thumbs of a layout manager and is perfectly willing to have you set its size or bounds.


void setVisible(boolean flag)


The visible components


Button (generates ActionEvent)


Its constructors are:


  • Button()

  • Button(String label)


Some of the methods are:


  • String getActionCommand()

  • void setActionCommand()

  • String getLabel()

  • void setLabel()

  • EventListener[] getListeners(Class listenerType)

  • void processActionEvent(ActionEvent ae)

  • void processEvent(AWTEvent e)

  • void addActionListener(ActionListener l)

  • void removeActionListener(ActionListener l)



Canvas (generates Mouse, MouseMotion, and Key events)


Its constructors are:

  • Canvas()

  • Canvas(GraphicsConfiguration config)


A canvas is a component that has no default appearance or behavior. It represents a blank rectangular area of the screen onto which the application can draw or from which the application can trap input events from the user. You can subclass Canvas to create custom drawing regions, work areas, components and so on.

The default size of a canvas is uselessly small. One way to deal with this problem is to  use a layout manager that will resize the canvas. Another way is  to call setSize() on the canvas yourself. Canvases are a rare case where this will actually work.


An application must subclass Canvas to get useful functionality such as creating a custom component. The paint() method must be overridden in order to perform custom graphics on the canvas.


Checkbox  (generates Item event)


A checkbox is a two state button: true(checked) and false(unchecked).

Its constructors are:

  • Checkbox()

  • Checkbox(String label)

  • Checkbox(String label, boolean state)

  • Checkbox(String label, boolean state, CheckboxGroup group)

  • Checkbox(String label, CheckboxGroup group, boolean state)


The default state is false. If you pass null for group in 4th or 5th constructor, it will mean that the checkbox does not belong to any group.

Unlike many window systems which implement radio groups as components in their own right, in Java CheckboxGroup class is not a component. It is simply a non-visible class that organizes checkboxes. This means that Java imposes no restrictions on the spatial relationships among members of a checkbox group.


Some of its methods are:

  • CheckboxGroup getCheckboxGroup();   Returns null if there is none.

  • String getLabel();

  • void setLabel(String s);

  • EventListener[] getListeners(Class listenerType);

  • Object [] getSelectedObject();

  • void setCheckboxGroup(CheckboxGroup g); if this checkbox is already in a different group, it is first taken out of that group.  


Choice  (generates Item event)


A choice is a pull down list or pop-up menu of choices. The current choice is displayed as the title of the pop-up menu (choice). It provides only the no-args constructor. To create a choice, first call the constructor, and then populate the choice by repeatedly calling addItem(String s).


Some of its methods are:


  1. void add(String item)

  2. void addItem(String item)

  3. String getItem(int index)

  4. int getItemCount()

  5. int getSelectedIndex()

  6. String getSelectedItem()

  7. Object [] getSelectedObjects()

  8. void insert(String item, int index)

  9. void remove(int position)

  10. void remove(String item)

  11. void removeAll()

  12. void select(int index)

  13. void select(String item)




This class extends Dialog. It represents a file open or file save dialog. The appearance of these dialogs vary from platform to platform. A file dialog is modal. This means that input from the dialogís parent frame will be directed exclusively to the dialog, as long as the dialog remains visible on the screen. The dialog is automatically removed when the user specifies a file or clicks the Cancel buttons.


Its constructors are:

  1. FileDialog(Frame parent)

  2. FileDialog(Frame parent, String title)

  3. FileDialog(Frame parent, String title, int mode)

First and second constructors are for loading a file. If the value of mode in the third constructor is FileDialog.LOAD, then the file dialog is finding a file to read. If the value is FileDialog.SAVE, the file dialog is finding a place to write a file.




Labels do not respond to user inputs, and they do not send any events. The default alignment for the labels is to the left.


List (on selection ItemEvent, on double-clicking ActionEvent is generated)


A list is a collection of text items, arranged vertically. If a list contains more items than it can display it acquires a vertical scrollbar. The constructors are:

  • List()

  • List(int rows)

  • List(int rows, boolean multiselect)


Some of its methods are:

  1. void add(String text)

  2. void add(String text, int index)

  3. String getItem(int index)

  4. int getItemCount()

  5. int getRows()

  6. int getSelectedIndex()

  7. int [] getSelectedIndexes()

  8. String getSelectedItem()

  9. String [] getSelectedItems()

  10. void remove(int position)

  11. void remove(String item)

  12. void removeAll()

  13. void replaceItem(String newValue, int index)

  14. void select(int index)

  15. void setMultipleMode(boolean flag)


ScrollPane  (extends Container. Generates Mouse and MouseMotion events)


A scrollPane can contain a single component, which may be taller or wider than the scroll pane itself ( then it acquires scrollbars). The initial size of this container is 100x100, but can be reset using setSize(). There are two constructors:

  • ScrollPane()

  • ScrollPane(int scrollbarPolicy)


scrollbarPolicy should be one of the following:



    3. ScrollPane.SCROLLBARS_NEVER


Scrollbar  (Adjustment event)


There are three constructors:

  • Scrollbar()

  • Scrollbar(int orientation)

  • Scrollbar(int orientation, int initial value, int sliderSize, int minValue, int maxValue)


Orientation can  be one of the following:

  • Scrollbar.HORIZONTAL

  • Scrollbar.VERTICAL


The defaults are:

Orientation Ė vertical, unit increment Ė 1, block increment Ė 10, value Ė 0 which controls the location of the scrollbar bubble, minimum Ė 0, maximum Ė 100.


The piece of the scroll bar that slides is called slider. The slider size parameter controls the size of the slider, but not in pixel units. The units of slider size parameter are the units defined by the spread between the minimum and maximum value of the scroll bar.


TextField and TextArea  (TextEvents, ActionEvents on receipt of Enter keystroke)


Both classes extend from TextComponent, which extends Component. Constructors are:


TextField ()

TextField (int nColumns)

TextField (String text)

TextField (String text, int nColumns)


TextArea ()

TextArea (int rows, int columns)

TextArea (String text)

TextArea (String text, int rows, int columns)

TextArea (String text, int rows, int columns, int scrollBarPolicy)


The last parameter should be one of the following:






For both classes , there are some surprising issues to the number of columns parameter. First, vColumns is a measure of width in terms of columns if text, as rendered in a particular font. Next, there is the problem of proportional font. For a fixed width font, the column width is obvious. For a proportional font, the column width is average of all the fontís character widths. Some of the space is taken up by leading and inter-character white space. So, five column wide component may not show five characters.


A final issue arises when a user types beyond the rightmost column. The visible text scrolls to the left. The insertion point remains in place, at the rightmost column.

Text areas support scroll bars, text fields can be scrolled by using the arrow keys.


The common methods inherited by these from TextComponent:


  • String getSelectedText()

  • String getText()

  • void setEditable(boolean editable)

  • void setText(String text)

  • boolean isEditable()

  • void selectAll()


Additional methods for text field are:


  • boolean echoCharSet()

  • int getColumns()

  • char getEchoChar() // gets the character that is to be used for encoding.

        // If the character is 0, user input is echoed unchanged.

  • void setColumns(int number)

  • void setEchoChar(char c)


Additional methods for text area are:


  • int getColumns()

  • void insert(String s, int position)

  • void setColumns(int number)

  • void setRows(int number)

  • void append(String s)



The container components




Applets, by virtue of inheriting from Component, have setSize() and setBounds() methods. They only exist in browsers. Changing the size of an applet is permitted or forbidden by the browser, and during the development cycle you cannot know the browser which will be running the applet. Appletviewer allows resizing of applets. It is common for an applet to have a temporary setSize() call in its init() method, because this provides an easy way to play with different sizes. If you use this technique, you should delete the setSize() call before final delivery, and set size in your html pages.




A frame is an independent, top level window with a title bar and a border, decorated by the underlying window system and capable of being moved around on the screen independent of other GUI windows. Its size includes the size of the window. The dimensions of the border can be obtained by getInsets() method, but since these dimensions are platform dependent, a valid insets value cannot be obtained until the frame is made displayable by calling either pack() or show().


Any application that requires a GUI must use one or more frames to contain desired components.

The constructors are:

  • Frame()

  • Frame(String title)


When a frame is constructed it has no size and is not displayed on the screen. To give a size, call one of inherited methods setSize() or setBounds(). To display it, call setVisible(true). To remove an unwarranted frame from the screen, call setVisible(false). This does not destroy the frame or damage it; you can display it again by setVisible(true).


When you are finished with a frame, you need to recycle its non-memory resources, which are system dependent; suffice it to say that it takes a lot to connect a Java GUI to an underlying window system. To release the non-memory resources of a frame, just call its dispose() method.


When a frame is displayed in an applet, it normally carries a warning. The rationale behind it is that the applet might have been loaded from the internet, so any sensitive information entered into the frameís components might possibly be transmitted to parties of dubious moral fiber.


Some of the methods are:

  1. Image getIconImage()

  2. void setIconImage(Image image)

  3. MenuBar getMenuBar()

  4. String getTitle()

  5. boolean isResizable()

  6. void setResizable(boolean flag)

  7. void setMenuBar(MenuBar m)

  8. void setTitle(String s)


If image parameter is null, then image is set to platform dependent default image.





Applets and frames serve as top-level or outermost GUI components. Panels provide an intermediate level of spatial organization for GUIs. You are free to add all the components of a GUI directly into an applet or a frame, but you can provide additional levels of grouping by adding components to panels and adding panels to a top level applet or frame.


Constructors are:

  • Panel()

  • Panel(LayoutManager)





It is a pop up window with a title bar and a border, that accepts user input. It must have a frame or another dialog defined as its owner when it is constructed. When owner is hidden or minimized, the dialog is automatically hidden and is visible again with the owner. Dialogs may optionally be made modal or modeless(default). A modal dialog is one which blocks input to all other top level windows in the app context, except for the windows created with the dialog as their owner. The Dialog class is the superclass of the FileDialog class. The default layout manager for this class is BorderLayout.



  1. Dialog(Dialog owner)

  2. Dialog(Dialog owner, String title)

  3. Dialog(Dialog owner, String title, boolean modal)

  4. Dialog(Frame owner)

  5. Dialog(Frame owner, String title)

  6. Dialog(Frame owner, boolean modal)

  7. Dialog(Frame owner, String title, boolean modal)


All the seven constructors construct an initially invisible Dialog.


Methods are:

  • void dispose()

  • String getTitle()

  • void setTitle(String s)

  • void hide()

  • boolean isModal()

  • boolean isResizable()

  • void setModal(boolean flag)

  • void setResizable(boolean flag)

  • void show()


Note : pack() defined in Window causes the window to be sized to fit the preferred size and layout of its subcomponents. If the window and / or its owner are not yet displayable, both are made displayable before calculating the preferred size. The window will be validated after the preferred size is calculated.


The Menu components


There are two types pop up and pull down. Pull down menus are accessed via a menu bar, which may contain multiple menus. Menu bars may appear only in frames.

To create a frame with a menu bar containing a pull down menu:

  • Create a menu bar and attach it to frame.

  • Create and populate the menu.

  • Attach the menu to the menu bar.

To create a menu bar, instantiate MenuBar class. To attach it to frame, pass it into the frameís setMenuBar().

To create a menu, instantiate Menu class. The most common constructor takes a string that is the menuís label. There are four kinds of elements that can be mixed and matched to populate a menu:

  • MenuItems

    • A menu item is an ordinary textual component available on a menu. The basic constructor is

MenuItem(String text) where text is the label of the menu item.

A menu item is very much like a button that happens to live in a menu. Like buttons, menu items generates action events.

  • Checkbox MenuItems

    • A checkbox menu item looks like a menu item with a checkbox to the left of its label. When a checkbox menu item is selected, the checkbox changes its state. The basic constructor is CheckboxMenuItem (String label);. You can read and set an itemís state by calling getState() and setState(). These generate ItemEvents.

  • Separators

    • A separator is just a horizontal mark used for visually dividing a menu into sections. To add a separator to a menu, call the menuís addSeparator() method().

  • Menus

    • When you add a menu to another menu, the first menuís label appears in the second menu, with a pull-right icon. Pulling the mouse to the right causes the sub-menu to appear.


After a menu is fully populated, you attach it to a menu bar by calling menu barís add() method. If you want the menu to appear in the Help menu position to the right of all other menus, call instead setHelpMenu().


The hierarchy of java.awt package is like this:



  • Layout Mangers (Layout classes)

  • CheckboxGroup

  • Graphics

  • GraphicsEnvironment

  • GridBagConstraints

  • Font

  • Image

  • Insets

  • Toolkit

  • Component

    • Button

    • Canvas

    • Checkbox

    • Choice

    • Container

      • Panel

        • Applet

      • Window

        • Dialog

          • FileDialog

          • JDialog

        • Frame

      • ScrollPane

    • Label

    • List

    • Scrollbar

    • TextComponent

      • TextArea

      • TextField

  • MenuComponent

    • MenuBar

    • MenuItem

      • CheckboxMenuItem

      • Menu

        • PopupMenu


  • EventObject

    • AWTEvent

      • ActionEvent

      • AdjustmentEvent

      • ComponentEvent

        • ContainerEvent

        • FocusEvent

        • InputEvent

          • MouseEvent

          • KeyEvent

        • PaintEvent

        • WindowEvent

      • ItemEvent

      • TextEvent


section8-1-1 | section8-1-2 | section8-1-3 | section8-2

Sections : 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11







Home | Blog | Java | Jokes | Poems | Musings | Site Map | Kudos | Downloads | Useful Sites | Interesting | System Setup | Contact  


 Number of Pages viewed on this site since January' 2003 : Hit Counter eXTReMe Tracker

For any queries, comments or suggestions, write to me .

This site never compromises your privacy, please read this site's privacy policy.