Presentation is loading. Please wait.

Presentation is loading. Please wait.

Universidad Nacional de Colombia Facultad de Ingeniería Departamento de Sistemas ertificación en AVA.

Similar presentations


Presentation on theme: "Universidad Nacional de Colombia Facultad de Ingeniería Departamento de Sistemas ertificación en AVA."— Presentation transcript:

1 Universidad Nacional de Colombia Facultad de Ingeniería Departamento de Sistemas ertificación en AVA

2 11. COMPONENTS  Components in General  The Visual Components  The Container Components  The Menu Components

3 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 Container 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

4 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

5 One way to organize this fairly large number of classes is to divide them into categories: Visual components Container components Menu components

6 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

7 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

8 Example: a label blue foreground color and black background color will show up as blue text on a black background

9 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

10 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

11 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

12 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

13 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

14 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

15 Button Canvas Checkbox Choice FileDialog Label List ScrollPane Scrollbar TextArea TextField The Visual Components

16 To use one of the components in a GUI: 1. 1. create an instance by calling the appropriate constructor 2. add the component to a container

17 implements a push button 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

18 Applet Viewer: Visual.class Apply

19 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 Canvas

20 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

21 1. 1.Canvas canv = new Canvas(); 2. 2.canv.setBackground( Color.black ); 3. 3.canv.setSize( 100, 50 ); Applet Viewer: Visual.class

22 A check box is a two-state button The two states are true (checked) and false (not checked) Checkbox Checkbox( String label ) Checkbox( String label, boolean initialState )

23 Applet Viewer: Visual.class Use secure server 

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

25 1. 1.CheckboxGroup cbg = new CheckboxGroup(); 2. 2.add( new Checkbox( "Cinnamon", false, cbg ) ); 3. 3.add( new Checkbox( "Nutmeg", false, cbg ) ); 4. 4.add( new Checkbox( "All spice", true, cbg ) ); Applet Viewer: Visual.class CinnamonNutmegAllspice

26 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

27 A choice is a pull-down list Choice To create a choice: 1. 1. call the constructor, 2. 2. populate the choice by repeatedly calling addltem()

28 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

29 1. 1.Choice ch = new Choice(); 2. 2.ch.addltem( "Alligators" ); 3. 3.ch.addltem( "Crocodiles" ); 4. 4.ch.addItem( "Gila Monsters" ); 5. 5.ch.addltem( "Dragons" ); Applet Viewer: Visual.class Applet started. Alligators Crocodiles Gila Monsters Dragons Gila Monsters 0 Alligators0

30 Choices send Item events when they are selected

31 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 FileDialog

32 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

33 After the user has specified a file, the name of the file or its directory can be retrieved: String getFile() String getDirectory()

34 1. 1.FileDialog fidi = new FileDialog( f, "Choose!", FileDialog.LOAD ); 2. 2.fidi.setVisible( true ); 3. 3.System.out.println( fidi.getFile() );

35 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 )

36 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

37 Two methods support reading and setting the text of a label: String getText() void setText( String newText )

38 new Label( "I'm a label, Mabel" ); Applet Viewer: Visual.class Applet started. I'm a label, Mabel

39 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 )

40 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

41 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

42 1. 1.List list = new List( 4, true ); 2. 2.list.addltem( "Augustus" ); 3. 3.list. addltem( "Tiberius" ); 4. 4.list.addltem( "Caligula" ); 5. 5.list.addltem( "Claudius" ); 6. 6.list.addltem( "Nero" ); 7. 7.list.addltem( "Otho" ); 8. 8.list.addItem( "Galba" ); Applet started. Nero Otho Claudius Galba Applet Viewer: Vi...

43 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

44 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)

45 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

46 Constructors: ScrollPane(): ScrollPane(): constructs a scroll pane with default scroll bar behavior ScrollPane( int scrollbarPolicy ): constructs a scroll pane with the specified scroll bar behavior

47 If you use the second form of the constructor, then scrollbarPolicy should be one of: 1. 1. ScrollPane.SCROLLBARS_AS_NEEDED 2. 2. ScrollPane.SCROLLBARS_ALWAYS 3. 3. ScrollPane.SCROLLBARS_NEVER

48 1. 1.ScrollPane spane = new ScrollPane(); 2. 2.Button bigButton = new Button( "What big teeth you have, Grandmother" ); 3. 3.bigButton.setFont( new Font( "Serif", Font.ITALIC, 80 ) ); 4. 4.spane.add( bigButton ); Applet Otho What big teeth y Applet Viewer: Visual class Applet started.

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

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

51 For constructors that take an orientation parameter, this value should be one of: Scroll bar.HORIZONTAL Scroll bar.VERTICAL

52 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

53 Scrollbar sbar = new Scrollbar( Scrollbar.HORIZONTAL, 625, 25, 600, 700 ); Applet Applet Viewer: Visual class

54 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 TextArea

55 Constructors for TextField 1. TextField(): 1. TextField(): constructs an empty text field 2. TextField( int nCols ): 2. TextField( int nCols ): constructs an empty text field with the specified number of columns 3. TextField( String text ): 3. TextField( String text ): constructs a text field whose initial content is text 4. TextField( String text, int nCols ): 4. TextField( String text, int nCols ): constructs a text field whose initial content is text, with the specified number of columns

56 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

57 Constructors for TextArea... 5. 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

58 the number-of-columns parameter: 1. 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

59 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

60 Inheritance of TextField and TextArea TextField TextArea Text Component Object Component

61 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 component 4. void setText( String text ): sets the text contents of the component Both classes inherit some functionality from their common superclass, TextComponent

62 1. 1.TextField tf1 = new TextField( 5 ); 2. 2.tf1.setFont( new Font( "Serif", Font.PLAIN, 24 ) ); 3. 3.tf1.setText( "12345" ); 4. 4.TextField tf2 = new TextField( 5 ); 5. 5.tf2.setFont( new Font("SansSerif, Font.PLAIN, 24 ) ); 6. 6.tf2.setText( "12345" ); 7. 7.TextField tf3 = new TextField( 5 ); 8. 8.tf3.setFont( new Font( "Monospaced", Font.PLAIN, 24 ) ); 9. 9.tf3.setText( "12345" ); 1234 Applet Viewer: Vi... 1234

63 1. 1.TextArea ta1 = new TextArea( 6, 5 ); 2. 2.ta1.setFont( new Font( "Serif", Font.PLAIN, 24 ) ); 3. 3.ta1.setText( "Serif\n12345\nabcde\niiiiiiiiii\nWWWWW" ); 4. 4.TextArea ta2 = new TextArea( 6, 5 ); 5. 5.ta2.setFont( new Font( "SansSerif", Font.PLAIN, 24 ) ); 6. 6.ta2.setText( "Sans\n12345\nabcde\niiiiiiiiii\nWWWWW" ); 7. 7.TextArea ta3 = new TextArea( 6, 5 ); 8. 8.ta3.setFont(new Font( "Monospaced", Font.PLAIN, 24 ) ); 9. 9.ta3.setText( "Mono\n12345\nabcde\niiiiiiiiii\nWWWWW" );

64 Applet started. Serif 1234 abcde iiiiiiii WWW Sans 1234 abcde iiiiiiii WWW Mono 1234 abcde iiiii WWW Applet Viewer: Vi...

65 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

66 Inheritance of Applet, Frame and Panel Applet Frame Component Container PanelWindow

67 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 Applet

68 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.

69 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 Frame

70 Constructors 1. Frame(): constructs a frame with an empty title bar 2. Frame( String title ): constructs a frame with the specified title

71 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 )

72 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

73 1. 1.// Construct and display 2. 2.Frame f = new Frame( "This is a frame" ); 3. 3.f.setBounds( 10, 10, 500, 350 ); 4. 4.f.setVisible( true ); 5. 5. 6. 6.// delay 7. 7.try { 8. 8.Thread.sleep( 30*1000 ); 9. 9.} catch ( InterruptedException e ) { } 10. 10. 11. 11.// Remove and dispose 12. 12.f.setVisible( false ); 13. 13.f.dispose();

74 Applets and frames serve as top-level or outermost GUI components Panels provide an intermediate level of spatial organization for GUIs Panel

75 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

76 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 Dialog

77 Java supports two kinds of menu: 1. 1.pull-down 2. 2.pop-up The certification exam does not cover pop- up menus The Menu Components

78 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

79 To create a frame with a menu bar containing a pull-down menu: 1.Create a menu bar and attach it to the frame 1. Create a menu bar and attach it to the frame 2. Create and populate the menu 3. Attach the 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.

80 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

81 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

82 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

83 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.

84 1. 1.Frame frame; 2. 2.MenuBar bar; 3. 3.Menu fileMenu, subMenu, helpMenu; 4. 4. 5. 5.// create frame and install menu bar 6. 6.frame = new Frame( 'Menu demo" ); 7. 7.frame.setSize( 400, 300 ); 8. 8.bar = new MenuBar(); 9. 9.frame.setMenuBar( bar ); 10. 10. 11. 11.// create submenu 12. 12.subMenu = new Menu( "Pull me" ); 13. 13.subMenu.add( new Menultem( "Sub-This" ) ); 14. 14.subMenu.add( new Menultem( "Sub-That" ) ); 15. 15. 16. 16.// create and add file menu. 17. 17.fileMenu = new Menu( "File" ); 18. 18.fileMenu.add( new MenuItem( "New" ) );

85 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 menu 26. 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 );

86 Menu demo New Open Print Preview Mode Pull meSub-This FileHelp Sub-That Frame with file menu and submenu

87 Menu demo About this program... Contents... HelpFile Frame with help menu


Download ppt "Universidad Nacional de Colombia Facultad de Ingeniería Departamento de Sistemas ertificación en AVA."

Similar presentations


Ads by Google