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

of 87 /87
Universidad Nacional de Universidad Nacional de Colombia Colombia Facultad de Ingeniería Facultad de Ingeniería Departamento de Sistemas Departamento de Sistemas ertificación ertificación en en AVA AVA

Embed Size (px)

description

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. - PowerPoint PPT Presentation

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

  • Universidad Nacional de ColombiaFacultad de IngenieraDepartamento de Sistemasertificacin enAVA

  • 11. COMPONENTS Components in General The Visual Components The Container Components The Menu Components

  • Objectives 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) providespatial 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 componentsContainer componentsMenu 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

  • ButtonCanvasCheckboxChoiceFileDialogLabelListScrollPaneScrollbarTextAreaTextFieldThe Visual Components

  • 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 buttonButtonnew 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

  • 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 feelCanvas

  • 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

  • A check box is a two-state button

    The two states are true (checked) and false (not checked)CheckboxCheckbox( String label )Checkbox( String label, boolean initialState )

  • 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:

  • Checkbox getSelectedCheckbox()void setSelectedCheckbox (Checkbox newSelection)Two methods support reading and setting the currently selected member of the groupCheck boxes send Item events when they are selected

  • A choice is a pull-down listChoiceTo 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

  • 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 buttonFileDialog

  • The dialog's parent is the frame over which the dialog will appearThe 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()

  • The simplest AWT component

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

    Constructors:Label 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 )

  • 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:List 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

  • The List class provides a large number of support methodsvoid 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 currently 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 neededScrollPane

  • Constructors: 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.SCROLLBARS_AS_NEEDED ScrollPane.SCROLLBARS_ALWAYS ScrollPane.SCROLLBARS_NEVER

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

  • Constructors: 1. Scrollbar():constructs a vertical scroll bar 2. Scrollbar( int orientation ): constructs a scroll bar with the specified orientation 3. Scrollbar( int orientation, int initialValue, int sliderSize, int minValue, 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.HORIZONTALScroll 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

  • 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 sizeTextField and TextArea

  • 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 istext, with the specified number of columns

  • Constructors for TextArea1. 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 bar placement policy is determined by the last parameter, which should be one of the following:TextArea.SCROLLBARS_BOTHTextArea.SCROLLBARS_NONETextArea.SCROLLBARS_HORIZONTAL_ONLYTextArea.SCROLLBARS_VERTICAL_ONLY

  • 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 wide2. There is the problem of proportional fonts

    For a fixed-width font, it is obvious what the column width should beFor 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

  • 1 . String getSelectedText():returns the currently selected text2. String getText():returns the text contents of the component3. void setEditable( boolean editable ): if editable is true, permits the user to edit the component4. void setText( String text ): sets the text contents of the component Both classes inherit some functionality from their common superclass, TextComponent

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

    AppletFramePanelDialog

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

  • 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 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 componentsFrame

  • Constructors1. 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

  • Applets and frames serve as top-level or outermost GUI components

    Panels provide an intermediate level of spatial organization for GUIsPanel

  • 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 layoutDialog

  • Java supports two kinds of menu:

    pull-downpop-up

    The certification exam does not cover pop-up menusThe 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. Create a menu bar and attach it to the frame2. Create and populate the menu3. Attach the menu to the menu barTo 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 itemsCheck-box menu itemsSeparatorsMenus

  • A menu item is an ordinary textual component available on a menuMenuItem( 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 stateCheckboxMenuItem( 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 with file menu and submenu

  • Frame with help menu