Universidad nacional de colombia facultad de ingenier a departamento de sistemas
1 / 87

Universidad Nacional de Colombia Facultad de Ingeniería Departamento de Sistemas - PowerPoint PPT Presentation

  • Uploaded on
  • Presentation posted in: General

C. ertificación en. J. AVA. Universidad Nacional de Colombia Facultad de Ingeniería Departamento de Sistemas. Components in General The Visual Components The Container Components The Menu Components. 11. COMPONENTS. Objectives.

I am the owner, or an agent authorized to act on behalf of the owner, of the copyrighted work described.

Download Presentation

Universidad Nacional de Colombia Facultad de Ingeniería Departamento de Sistemas

An Image/Link below is provided (as is) to download presentation

Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author.While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server.

- - - - - - - - - - - - - - - - - - - - - - - - - - E N D - - - - - - - - - - - - - - - - - - - - - - - - - -

Presentation Transcript


ertificación en



Universidad Nacional de Colombia

Facultad de Ingeniería

Departamento de Sistemas

  • Components in General

  • The Visual Components

  • The Container Components

  • The Menu Components



  • Components are Java's building blocks for creating

  • graphical user interfaces. Some component types,

  • such as buttons and scroll bars, are used directly

  • for GUI control. Other kinds of components (those

  • that inherit from the abstract Container class) provide

  • spatial organization

  • GUIs are an important part of any program. Java's

  • Toolkit (AWT) provides extensive functionality.

  • This chapter reviews components

Components in General

Java's components are implemented by the many subclasses of the java.awt.Component and java.awt.MenuComponent superclasses

There are 19 non-superclass components in all, and you should know the basics of all the component classes

One way to organize this fairly large number of classes is to divide them into categories:

  • Visual components

  • Container components

  • Menu components

There are several methods that are implemented by all the visual and container components, by virtue of inheritance from java.awt.Component

(The menu components extend from java.awt.MenuComponent, so they do not inherit the same superclass functionality)


returns the size of a component

The return type is Dimension, which has public data members height and width

setForeground() and setBackground():

set the foreground and background colors of a component

Each method takes a single argument, which is an instance of java.awt.Color

Chapter 12 discusses how to use the Color class.

Generally the foreground color of a component is used for rendering text, and the background color is used for rendering the non-textual area of the component

Example: a label

blue foreground color and black background color will show up as blue text on a black background


The setFont() method determines the font that a component will use for rendering any text that it needs to display

The method takes a single argument, which is an instance of java.awt.Font

If you do not explicitly set a component's font, the component uses the font of its container, in the same way that the container's foreground and background colors are used if you do not explicitly call setForeground() or setBackground()

Thus, if you have an applet whose font is 48-point bold Serif, and you add a check box to the applet without calling setFont() on the check box, you will get a check box whose label appears in 48-point bold Serif


takes a single argument of type boolean

If this argument is true, then the component has its normal appearance

If the argument is false, then the component is grayed out and does not respond to user input

This method replaces the 1.0 methods enable() and disable(), which are deprecated

setSize() and setBounds():

set a component's geometry, or rather, they attempt to set geometry. They replace the deprecated 1.0 methods resize() and reshape()

setSize(): takes two int arguments:

width and height

an overloaded form takes a single dimension

setBounds(): takes four int arguments:

x, y, width, and height; an overloaded form takes a single rectangle

If you have tried calling these methods, you know that it is usually futile:

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 thumb of a layout manager and is perfectly willing to have you set its size or bounds


takes a boolean argument that dictates whether the component is to be seen on the screen

it only works for frames, unless you learn some techniques that are beyond the scope the Certification Exam

The Visual Components

  • Button

  • Canvas

  • Checkbox

  • Choice

  • FileDialog

  • Label

  • List

  • ScrollPane

  • Scrollbar

  • TextArea

  • TextField

  • To use one of the components in a GUI:

  • create an instance by calling the appropriate constructor

  • 2. add the component to a container


implements a push button

new Button( "Apply" );

This constructor takes a string parameter that specifies the text of the button's label

When a button is pushed, it sends an Action event

Applet Viewer: Visual.class



It is a component that has no default appearance or behavior

You can subclass Canvas to create custom drawing regions, work areas, components, and so on

Canvases receive input events from the mouse and the keyboard; it is up to the programmer to transform those inputs into a meaningful look and feel

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

  • Canvas canv = new Canvas();

  • canv.setBackground( Color.black );

  • canv.setSize( 100, 50 );

Applet Viewer: Visual.class


A check box is a two-state button

The two states are true (checked) and false (not checked) 

Checkbox( String label )

Checkbox( String label, boolean initialState )

Applet Viewer: Visual.class

Use secure server

If you do not specify an initial state, the default is false

Two methods support reading and setting the state of a check box:

boolean getState()

void setState( boolean state )

  • CheckboxGroup cbg = new CheckboxGroup();

  • add( new Checkbox( "Cinnamon", false, cbg ) );

  • add( new Checkbox( "Nutmeg", false, cbg ) );

  • add( new Checkbox( "All spice", true, cbg ) ); 

Applet Viewer: Visual.class




Two methods support reading and setting the currently selected member of the group

Checkbox getSelectedCheckbox()

void setSelectedCheckbox (Checkbox newSelection)

Check boxes send Item events when they are selected


A choice is a pull-down list

  • To create a choice:

  • call the constructor,

  • populate the choice by repeatedly calling addltem()

Next figure shows two choices, both of which present the same options

The choice on the left is in its normal state; the choice on the right has been mouse-clicked

  • Choice ch = new Choice();

  • ch.addltem( "Alligators" );

  • ch.addltem( "Crocodiles" );

  • ch.addItem( "Gila Monsters" );

  • ch.addltem( "Dragons" );

Applet Viewer: Visual.class

Gila Monsters 0




Gila Monsters


Applet started.

Choices send Item events when they are selected


The FileDialog class represents a file open or file save dialog

The appearance of these dialogs varies greatly 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 button

 The most useful FileDialog constructor  

FileDialog(Frame parent, String title, int mode)

The dialog's parent is the frame over which the dialog will appear

The title string appears in the dialog's title bar (on most platforms)

  • The mode should be

  • FileDialog.LOAD or

  • FileDialog.SAVE

After the user has specified a file, the name of the file or its directory can be retrieved: 

String getFile()

String getDirectory()

  • FileDialog fidi = new FileDialog( f, "Choose!", FileDialog.LOAD );

  • fidi.setVisible( true );

  • System.out.println( fidi.getFile() );


The simplest AWT component

Labels do notrespond to user input, and they do not send out any events


  • Label()

  • Label( String text )

  • Label( String text, int alignment )

The default alignment for labels is to the left

To set the alignment, use the third form of the constructor and pass in one of the following:

  • Label.LEFT

  • • Label.CENTER

  • • Label.RIGHT

 Two methods support reading and setting the text of a label:

String getText()

void setText( String newText )

new Label( "I'm a label, Mabel" );

Applet Viewer: Visual.class

I'm a label, Mabel

Applet started.


A list is a collection of text items, arranged vertically

If a list contains more items than it can display, it acquires a vertical scroll bar


  • List()

  • List( int nVisibleRows )

  • List( int nVisibleRows, boolean bMultiSelectOk )

The number of visible rows (parameter nVisibleRows) dictates the height of a list

The first version of the constructor does not specify a number of visible rows, so presumably the height of such list will be dictated by a layout manager

 If the version of the third constructor is used and multiSelectOk is true, then the list supports multiple selection

If multiple selection is not enabled, then selecting a new item causes the old selected item to be deselected

  • List list = new List( 4, true );

  • list.addltem( "Augustus" );

  • list. addltem( "Tiberius" );

  • list.addltem( "Caligula" );

  • list.addltem( "Claudius" );

  • list.addltem( "Nero" );

  • list.addltem( "Otho" );

  • list.addItem( "Galba" );

Applet Viewer: Vi...





Applet started.

  • The List class provides a large number of support methods

  • void addItem( String text ):

  • adds an item to the bottom of the list

  • void addItem( String text, int index ):

  • inserts an item at the specified index

  • String getltem( int index ):

  • returns the item with the specified index

  • int getltemCount():

  • returns the number of items in the list

  • int getRows():

  • returns the number of visible lines in the list

  • int getSelectedlndex():

  • returns the index of the currently selected item (the list should be in single-selection mode)

  • int[] getSelectedlndexes():

  • returns an array containing the index of every currently selected item (the list should be in multiple-selection mode)

  • String getSelectedltem():

  • returns a string that reflects the cur­rently selected item (the list should be in single-selection mode)

  • String[] getSelectedltems(): returns an array containing a string for every currently selected item (the list should be in multiple-selection mode)


It was introduced in Java 1.1

A scroll pane can contain a single component, which may be taller or wider than the scroll pane itself

If the contained component is larger than the scroll pane, then the default behavior of the scroll pane is to acquire horizontal and/or vertical scroll bars as needed


  • ScrollPane():

  • constructs a scroll pane with default scroll

  • bar behavior

  • ScrollPane( int scrollbarPolicy ):

  • constructs a scroll pane with the specified

  • scroll bar behavior

If you use the second form of the constructor, then scrollbarPolicy should be one of:




  • ScrollPane spane = new ScrollPane();

  • Button bigButton = new Button( "What big teeth you have, Grandmother" );

  • bigButton.setFont( new Font( "Serif", Font.ITALIC, 80 ) );

  • spane.add( bigButton );

Applet Viewer: Visual class


What big teeth y


Applet started.


The scroll bar component that adjusts lists and scroll panes is available as a component in its own right


1. Scrollbar():

constructs a vertical scroll bar

2. Scrollbar( int orientation ):

constructs a scroll bar with the specified


3. Scrollbar( int orientation, int initialValue,

int sliderSize, int minValue,

int maxValue ):

constructs a scroll bar with the specified


For constructors that take an orientation parameter, this value should be one of:

  • Scroll bar.HORIZONTAL

  • Scroll bar.VERTICAL

In the third form of the constructor, the sliderSize parameter is a bit confusing

The Java terminology for the piece of the scroll bar that slides is the slider, which in itself is confusing because in some window systems the entire component is called a slider

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

Applet Viewer: Visual class


Scrollbar sbar = new Scrollbar( Scrollbar.HORIZONTAL,

625, 25, 600, 700 );

TextField and TextArea

The TextField and TextArea classes implement one-dimensional and two-dimensional components for text input, display, and editing

Both classes have a variety of constructors, which offer the option of specifying or not specifying an initial string or a size

The constructors that do not specify size are for use with layout managers that will enforce a size

Constructors for TextField

1. TextField():

constructs an empty text field

2. TextField( int nCols ):

constructs an empty text field with the

specified number of columns

3. TextField( String text ):

constructs a text field whose initial content

is text

4. TextField( String text, int nCols ):

constructs a text field whose initial content is

text, with the specified number of columns

Constructors for TextArea

1. TextArea():

constructs an empty text area

2. TextArea( int nRows, int nCols ):

constructs an empty text area with the specified

number of rows and columns

3. TextArea( String text):

constructs a text area whose initial content is text

4. TextArea( String text, int nRows, int nCols ):

constructs a text area whose initial content is

text, with the specified number of rows and columns

Constructors for TextArea ...

  • 5. TextArea( String text, int nRows, int nCols,

  • int scrollbarPolicy ):

  • same as above, but the scroll barplacement policy is

  • determined by the last parameter,

  • which should be one of the following:





  • the number-of-columns parameter:

  • the number of columns is a measure of width in terms of columns of text, as rendered in a particular font

  • A 25-column text area with a tiny font will be very narrow, while a 5-column text area with a huge font will be extremely wide

  • 2.There is the problem of proportional fonts

  • For a fixed-width font, it is obvious what the column width should be

  • For a proportional font, the column width is taken to be the average of all the font's character widths

what happens when a user types beyond the rightmost character column in one of these components?

The visible text scrolls to the left

The insertion point remains in place, at the rightmost column

The component now contains more text than it can display, so scrolling is required

Text areas support scroll bars. Text fields can be scrolled by using the  and  keys







Inheritance of TextField and TextArea

Both classes inherit some functionality from

their common superclass, TextComponent

1 . String getSelectedText():

returns the currently selected text

2. String getText():

returns the text contents of the component

3. void setEditable( boolean editable ):

if editable is true, permits the user to edit the


4. void setText( String text ):

sets the text contents of the component

Applet Viewer: Vi...

  • TextField tf1 = new TextField( 5 );

  • tf1.setFont( new Font( "Serif", Font.PLAIN, 24 ) );

  • tf1.setText( "12345" );

  • TextField tf2 = new TextField( 5 );

  • tf2.setFont( new Font("SansSerif , Font.PLAIN, 24 ) );

  • tf2.setText( "12345" );

  • TextField tf3 = new TextField( 5 );

  • tf3.setFont( new Font( "Monospaced", Font.PLAIN, 24 ) );

  • tf3.setText( "12345" );




  • TextArea ta1 = new TextArea( 6, 5 );

  • ta1.setFont( new Font( "Serif", Font.PLAIN, 24 ) );

  • ta1.setText( "Serif\n12345\nabcde\niiiiiiiiii\nWWWWW" );

  • TextArea ta2 = new TextArea( 6, 5 );

  • ta2.setFont( new Font( "SansSerif", Font.PLAIN, 24 ) );

  • ta2.setText( "Sans\n12345\nabcde\niiiiiiiiii\nWWWWW" );

  • TextArea ta3 = new TextArea( 6, 5 );

  • ta3.setFont(new Font( "Monospaced", Font.PLAIN, 24 ) );

  • ta3.setText( "Mono\n12345\nabcde\niiiiiiiiii\nWWWWW" );

Applet Viewer: Vi...
















Applet started.

The Container Components

  • Containers are components capable of holding other components within their boundaries

  • Applet

  • Frame

  • Panel

  • Dialog

  • Technically, ScrollPane is also a container, because it inherits from the Container superclass, but it does not present the issues that the other three







Inheritance of Applet, Frame and Panel


The only issue that needs attention here is the problem of resizing

Applets, by virtue of inheriting from Component, have setSize() and setBounds() methods.

Applets only exist in browsers. Changing the size of an applet is permitted or forbidden by the applet's browser, and during the development cycle you cannot know which brand of browser will be running your applet

The easiest browser for development is the applet viewer, which 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, remember to delete the setSize() call before final delivery and set the size in your HTML tag.


A frame is an independent window, decorated by the underlying window system and capable of being moved around on the screen independent of other GUI windows

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


1. Frame():

constructs a frame with an empty title bar

2. Frame( String title ):

constructs a frame with the specified title

When a frame is constructed, it has no size and is not displayed on the screen

To give a frame a size, call one of the inherited methods setSize() or setBounds()

If you call setBounds(), the x and y parameters tell the frame where it will appear on the screen. Once a frame has been given a size, you can display it by calling setVisible( true )

To remove an unwanted frame from the screen, you can call setVisible( false )

This does not destroy the frame or damage it in any way; you can always display it again by calling setVisible( true )

When you are finished with a frame, you need to recycle its non-memory resources

Memory will be harvested by the garbage collector

Non-memory resources are system-dependent; suffice it to say that it takes a lot to connect a Java GUI to an underlying window system

On a UNIX/Motif platform, for example, a frame's non-memory resources would include at least one file descriptor and X window

  • // Construct and display

  • Frame f = new Frame( "This is a frame" );

  • f.setBounds( 10, 10, 500, 350 );

  • f.setVisible( true );

  • // delay

  • try {

  • Thread.sleep( 30*1000 );

  • } catch ( InterruptedException e ) { }

  • // Remove and dispose

  • f.setVisible( false );

  • f.dispose();


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

This process is recursive:

the components that you add to panels can themselves be panels, and so on, to whatever depth of containment you like


A dialog is a pop-up window that accepts user input

Dialogs may optionally be made modal

The Dialog class is the superclass of the FileDialog class. The default layout manager for this class is border layout

The Menu Components

  • Java supports two kinds of menu:

  • pull-down

  • pop-up

  • The certification exam does not cover pop-up menus

Pull-down menus are accessed via a menu bar, which may contain multiple menus

Menu bars may only appear in frames

Therefore pull-down menus also may only appear in frames

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

1.Createamenu barand attach it to the frame

2.Create andpopulatethe menu

3.Attachthe menu to the menu bar

To create a menu bar, just construct an instance of the MenuBar class

To attach it to a frame, pass it into the frame's setMenuBar() method.

There are four kinds of element that can be mixed and matched to populate a menu:

  • Menu items

  • Check-box menu items

  • Separators

  • Menus

A menu item is an ordinary textual component available on a menu

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 generate Action events 

A check-box menu item looks like a menu item with a check box to the left of its label. When a check-box menu item is selected, the check box changes its state

CheckboxMenuItem( String text )

where text is the label of the item

A check-box menu item is very much like a check box that happens to live in a menu;

you can read and set an item's state by calling getState() and setState() just as you would with a plain check box.

Check-box menu items generate Item events.

  • Frame frame;

  • MenuBar bar;

  • Menu fileMenu, subMenu, helpMenu;

  • // create frame and install menu bar

  • frame = new Frame( 'Menu demo" );

  • frame.setSize( 400, 300 );

  • bar = new MenuBar();

  • frame.setMenuBar( bar );

  • // create submenu

  • subMenu = new Menu( "Pull me" );

  • subMenu.add( new Menultem( "Sub-This" ) );

  • subMenu.add( new Menultem( "Sub-That" ) );

  • // create and add file menu.

  • fileMenu = new Menu( "File" );

  • fileMenu.add( new MenuItem( "New" ) );

18. fileMenu.add( new MenuItem( "New" ) );

19. fileMenu.add( new Menultem( "Open" ) );

20. fileMenu.addSeparator();

21. fileMenu.add(

new CheckboxMenuItem( "Print Preview Mode" ) );

22. fileMenu.add( subMenu );

23. bar.add( fileMenu );


25. // create help menu

26. helpMenu = new Menu( "Help" );

27. helpMenu.add( new Menultem( "Contents..." ) );

28. helpMenu.add( new Menultem( "About this program..." ) );

29. bar.setHelpMenu( helpMenu );


31. // now that the frame is completely built, display it

32. frame.setVisible( true );

Menu demo





Print Preview Mode

Pull me



Frame with file menu and submenu

Menu demo



About this program ...

Contents ...

Frame with help menu

  • Login