Universidad Nacional de Universidad Nacional de ColombiaColombia
Facultad de IngenieríaFacultad de Ingeniería
Departamento de SistemasDepartamento de Sistemas
ertificación enertificación en
AVAAVA
11. 11. COMPONENTSCOMPONENTS
Components in GeneralComponents in General
The Visual ComponentsThe Visual Components
The Container Components The Container Components
The Menu ComponentsThe Menu Components
ObjectivesObjectives
• 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 ContainerContainer class) providespatial organization • GUIs are an important part of any program. Java's Toolkit (AWT) provides extensive functionality. This chapter reviews components
Components in General 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)
getSize()
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
setFont():
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
setEnabled():
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
setVisible(): 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
• Button• Canvas• Checkbox• Choice• FileDialog• Label• List• ScrollPane• Scrollbar• TextArea• TextField
The Visual ComponentsThe Visual Components
To use one of the components in a GUI:
1. create an instance by calling the appropriate constructor
2. add the component to a container
implements a push button
ButtonButton
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
Apply
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
CanvasCanvas
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
1. Canvas canv = new Canvas();2. canv.setBackground( Color.black );3. 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)
CheckboxCheckbox
Checkbox( String label )Checkbox( String label, boolean initialState )
Applet Viewer: Visual.class
Use secure server
boolean getState()void setState( boolean state )
If you do not specify an initial state, the default is false
Two methods support reading and setting the state of a check box:
1. CheckboxGroup cbg = new CheckboxGroup();2. add( new Checkbox( "Cinnamon", false, cbg ) );3. add( new Checkbox( "Nutmeg", false, cbg ) );4. add( new Checkbox( "All spice", true, cbg ) );
Applet Viewer: Visual.class
Cinnamon Nutmeg Allspice
Checkbox getSelectedCheckbox()void setSelectedCheckbox (Checkbox newSelection)
Two methods support reading and setting the currently selected member of the group
Check boxes send Item events when they are selected
A choice is a pull-down list
ChoiceChoice
To create a choice:
1. call the constructor, 2. 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
1. Choice ch = new Choice();2. ch.addltem( "Alligators" );3. ch.addltem( "Crocodiles" );4. ch.addItem( "Gila Monsters" );5. ch.addltem( "Dragons" );
Applet Viewer: Visual.class
Applet started.
Alligators
Crocodiles
Gila MonstersDragons
Gila Monsters 0 Alligators0
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
FileDialogFileDialog
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)
FileDialog(Frame parent, String title, int mode)
The most useful FileDialog constructor
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()
1. FileDialog fidi = new FileDialog( f, "Choose!",
FileDialog.LOAD );2. fidi.setVisible( true );3. System.out.println( fidi.getFile() );
The simplest AWT component
Labels do not respond to user input, and they do not send out any events
Constructors:
LabelLabel
• 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
Applet started.
I'm a label, Mabel
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
Constructors:
ListList
• 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
1. List list = new List( 4, true );2. list.addltem( "Augustus" );3. list. addltem( "Tiberius" );4. list.addltem( "Caligula" );5. list.addltem( "Claudius" );6. list.addltem( "Nero" );7. list.addltem( "Otho" );8. list.addItem( "Galba" );
Applet started.
Nero
Otho
Claudius
Galba
Applet Viewer: Vi...
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
ScrollPaneScrollPane
Constructors:
• ScrollPane():ScrollPane(): constructs a scroll pane with default scroll bar behavior
• ScrollPane( int scrollbarPolicy ):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:
1. ScrollPane.SCROLLBARS_AS_NEEDED2. ScrollPane.SCROLLBARS_ALWAYS3. ScrollPane.SCROLLBARS_NEVER
1. ScrollPane spane = new ScrollPane();2. Button bigButton = new Button( "What big teeth you
have, Grandmother" );3. bigButton.setFont( new Font( "Serif", Font.ITALIC, 80 ) );4. spane.add( bigButton );
Applet
OthoWhat big teeth y
Applet Viewer: Visual class
Applet started.
The scroll bar component that adjusts lists and scroll panes is available as a component in its own right
Scrollbar Scrollbar
Constructors:
1.1. Scrollbar(): Scrollbar():constructs a vertical scroll bar 2.2. Scrollbar( int orientation ): Scrollbar( int orientation ): constructs a scroll bar with the specified orientation 3.3. Scrollbar( int orientation, int initialValue, Scrollbar( int orientation, int initialValue, int sliderSize, int minValue, int sliderSize, int minValue, int maxValue ):int maxValue ): constructs a scroll bar with the specified parameters
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
Scrollbar sbar = new Scrollbar( Scrollbar.HORIZONTAL, 625, 25, 600, 700 );
Applet
Applet Viewer: Visual class
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
TextField and TextAreaTextField and TextArea
Constructors for TextField
1.1. TextField(): TextField(): constructs an empty text field 2.2. TextField( int nCols ): TextField( int nCols ): constructs an empty text field with the specified number of columns 3.3. TextField( String text ): TextField( String text ): constructs a text field whose initial content is text 4.4. TextField( String text, int nCols ): TextField( String text, int nCols ): constructs a text field whose initial content istext, with the specified number of columns
Constructors for TextArea
1.1. TextArea(): TextArea(): constructs an empty text area
2.2. TextArea( int nRows, int nCols ): TextArea( int nRows, int nCols ): constructs an empty text area with the specified number of rows and columns
3.3. TextArea( String text): TextArea( String text): constructs a text area whose initial content is text
4.4. TextArea( String text, int nRows, int nCols ): 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.5. TextArea( String text, int nRows, int nCols, TextArea( String text, int nRows, int nCols, int scrollbarPolicy ):int scrollbarPolicy ): same as above, but the scroll bar placement policy is determined by the last parameter, which should be one of the following: • TextArea.SCROLLBARS_BOTH• TextArea.SCROLLBARS_NONE• TextArea.SCROLLBARS_HORIZONTAL_ONLY• TextArea.SCROLLBARS_VERTICAL_ONLY
the number-of-columns parameter: 1. 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
TextField TextArea
TextComponent
Object
Component
1 .1 . String getSelectedText(): String getSelectedText():returns the currently selected text2.2. String getText(): String getText():returns the text contents of the component3.3. void setEditable( boolean editable ): void setEditable( boolean editable ): if editable is true, permits the user to edit the component4.4. void setText( String text ): void setText( String text ): sets the text contents of the component
Both classes inherit some functionality from their common superclass, TextComponent
1. TextField tf1 = new TextField( 5 );2. tf1.setFont( new Font( "Serif", Font.PLAIN, 24 ) );3. tf1.setText( "12345" );4. TextField tf2 = new TextField( 5 );5. tf2.setFont( new Font("SansSerif , Font.PLAIN, 24 ) );6. tf2.setText( "12345" );7. TextField tf3 = new TextField( 5 );8. tf3.setFont( new Font( "Monospaced", Font.PLAIN, 24 ) );9. tf3.setText( "12345" );
1234
Applet Viewer: Vi...
1234
1234
1. TextArea ta1 = new TextArea( 6, 5 );2. ta1.setFont( new Font( "Serif", Font.PLAIN, 24 ) );3. ta1.setText( "Serif\n12345\nabcde\niiiiiiiiii\nWWWWW" );4. TextArea ta2 = new TextArea( 6, 5 );5. ta2.setFont( new Font( "SansSerif", Font.PLAIN, 24 ) );6. ta2.setText( "Sans\n12345\nabcde\niiiiiiiiii\nWWWWW" );7. TextArea ta3 = new TextArea( 6, 5 );8. ta3.setFont(new Font( "Monospaced", Font.PLAIN, 24 ) );9. ta3.setText( "Mono\n12345\nabcde\niiiiiiiiii\nWWWWW" );
Applet started.
Serif1234abcdeiiiiiiiiWWW
Sans1234abcdeiiiiiiiiWWW
Mono1234abcdeiiiiiWWW
Applet Viewer: Vi...
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
The Container Components The Container Components
Inheritance of Applet, Frame and Panel
Applet Frame
Component
Container
Panel Window
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
AppletApplet
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
FrameFrame
Constructors
1.1. Frame(): Frame():constructs a frame with an empty title bar
2.2. Frame( String title ): 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
1. // Construct and display2. Frame f = new Frame( "This is a frame" );3. f.setBounds( 10, 10, 500, 350 );4. f.setVisible( true );5. 6. // delay 7. try {8. Thread.sleep( 30*1000 ); 9. } catch ( InterruptedException e ) { }10. 11.// Remove and dispose 12.f.setVisible( false ); 13.f.dispose();
Applets and frames serve as top-level or outermost GUI components
Panels provide an intermediate level of spatial organization for GUIs
Panel Panel
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
DialogDialog
Java supports two kinds of menu:
1. pull-down2. pop-up
The certification exam does not cover pop-up menus
The Menu ComponentsThe Menu Components
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.1. CreateCreate aa menu barmenu bar and attach it to the and attach it to the frameframe
2.2. Create Create andand populatepopulate the menuthe menu3.3. AttachAttach the menu to the menu barthe 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 itemsMenu items• Check-box menu itemsCheck-box menu items• SeparatorsSeparators• MenusMenus
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.
1. Frame frame;2. MenuBar bar;3. Menu fileMenu, subMenu, helpMenu;4. 5. // create frame and install menu bar 6. frame = new Frame( 'Menu demo" );7. frame.setSize( 400, 300 );8. bar = new MenuBar(); 9. frame.setMenuBar( bar );10. 11.// create submenu12.subMenu = new Menu( "Pull me" ); 13.subMenu.add( new Menultem( "Sub-This" ) ); 14.subMenu.add( new Menultem( "Sub-That" ) );15. 16.// create and add file menu.17.fileMenu = new Menu( "File" );18.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 );24. 25. // create help menu26. helpMenu = new Menu( "Help" ); 27. helpMenu.add( new Menultem( "Contents..." ) ); 28. helpMenu.add( new Menultem( "About this program..." ) ); 29. bar.setHelpMenu( helpMenu );30. 31. // now that the frame is completely built, display it 32. frame.setVisible( true );
Menu demo
NewOpen
Print Preview Mode
Pull me Sub-This
File Help
Sub-That
Frame with file menu and submenuFrame with file menu and submenu
Menu demo
About this program ...
Contents ...
HelpFile
Frame with help menuFrame with help menu
Top Related