Presentation is loading. Please wait.

Presentation is loading. Please wait.

Fundamental of Java Programming Abstract Window Toolkit

Similar presentations


Presentation on theme: "Fundamental of Java Programming Abstract Window Toolkit"— Presentation transcript:

1 Fundamental of Java Programming Abstract Window Toolkit
(630002) Unit – 5 Abstract Window Toolkit

2 Introduction The abstract component class was introduced in applets. This class is important from user point of view because in each and every user interface we need to have components. Various components of the package are as follows (According to figure)

3 Introduction Object Component Button Canvas CheckBox Choice Container
Panel Applet Window Dialog FileDialog Frame Label List Scrollbar TextComponent TextAra TextField

4 Introduction All the components that we have seen the previous figure are must be added to the container of the applet. For that applet has provided a special class called container. Various methods of the class are as follows : Method Description Component add(Component c) Adds c to the container and returns c Void addContainerListener(ContainerListener cl) Registers cl to receive container events Insets getInsets Returns the insets object for the container Void remove(Component c) Removes c from the container Void remoeContainerListener(ContainerListener cl) Unregister cl to receive the container events void setLayout(LayoutManager lm) Sets lm as the layout manager for the container

5 Labels A label is a string that appears on a graphical user interface. It can be changed by your program but cannot be changed by the user. Labels are very frequently used in programs. The most common example where we find the labels is before the text field to inform the user about the input that is expected. The constructors of the class are as follows : Label() Label(String str) Label(String str, int align)

6 Labels Here, str is the text for the label. The argument align is a constant that indicates if the label should be left justified, centered or right justified. The constants LEFT, CENTER and RIGHT will be used to set the value of the align. To get the information about the alignment we have two methods (1) int getAlignment() (2) void setAlignment(int align)

7 Labels The methods for reading and writing the text are as follows :
(1) String getText() (2) void setText(String str) ex\AWT\LabelDemo.java Exercise : Write an applet that displays appropriate msg according to the system time. E.g. good morning upto 12 noon, good afternoon upto 5 p.m. etc.

8 Buttons A Button is a component that simulates the appearance of a push button on an electronic instrument. When the user clicks the mouse inside its boundaries, the button changes appearance to provide feedback for the user. This class has two constructors are as follows (1) Button() (2) Button(String str) Here the str is the text for the button.

9 Buttons An action event is generated each time a button is pressed. The methods for registering and unregistering objects to receive action events generated by this component are as follows : void addActionListener(ActionListener al) void removeActionListener(ActionListener al) here al is the action listener. We can read and write labels on a button via this methods String getLabel() void setLabel(String str)

10 Buttons Here str is the string to be used as a label for the button. We have to implement java.awt.event.ActionListener interface which defines one method i.e. actionPerformed which is as follows : void actionPerformed(ActionEvent ae) Here ae is the action event. ex\AWT\ButtonEvents.java Exercise : Write an applet that contains one button with label start – change it to stop when user click on that and again change it to start on second click.

11 Canvases A canvas provides a rectangular area on which you can draw. This is valuable because you can create graphs and other diagrams on the canvas by using all the methods of Graphics class. This class has only one constructor i.e. canvas() ex\AWT\CanvasDemo.java

12 CheckBoxes A check box is a component that combines a label and a small box. Depending on the state of the option represented by that checkbox. There may be or may not be a check mark in the check box. The state of check box is changed by clicking the mouse on the box. This class has five constructors as follows : Checkbox() Checkbox(String str) Checkbox(String str, boolean state) Checkbox(String str, boolean state, CheckboxGroup grp) Checkbox(String str, CheckboxGroup grp, boolean state)

13 CheckBoxes Here the str is the text for the check box. If state is true, a check mark appears in the box. Otherwise the box is cleared. The last two forms of constructors uses a group of several checkboxes together. The parameter grp is the reference of the checkbox group. An item event is generated when the state of a checkbox changes. For that following are the methods that we have to register void addItemListener(ItemListener il) void removeItemListener(ItemListener il)

14 CheckBoxes We can read and write the state of checkbox by using the following methods : (1) boolean getState() void setState(boolean value) here if the value is true, a check mark is placed inside the box. Otherwise the box will be cleared. We can read and write the label of checkbox via following methods : String getLabel() void setLabel(String str)

15 CheckBoxes The java.awt.event.ItemListener interface defines one method that must be implemented by an item listener. void itemStateChanged(ItemEvent ie) here ie is the item event ex\AWT\CheckboxDemo.java Exercise : Write an applet that contains three check boxes and a 30 x 30 pixel canvas. The checkboxes are of red, green and blue. The color of canvas will be according to the selection of check boxes.

16 CheckBox Groups A CheckBox group is a set of check boxes. Only one of these may be set at any time. If the user clicks on one element in a checkbox group, that checkbox is set. Other members of the same group are automatically cleared. In otherwords, a checkbox with group is just like a radio button. We may get the selected member from the group by calling following method Checkbox getSelectedCheckbox()

17 CheckBox Groups We may also set a particular checkbox in a group via the following method void setSelectedCheckBox(Checkbox cb) here cb is the checkbox to be set. ex\AWT\CheckboxGroupDemo.java Exercise : Write an applet that contains three option buttons (CheckBoxes in group) and a 30 x 30 pixel canvas. The option buttons are of red, green and blue. The color of canvas will be according to the selection of option buttons.

18 Choices A Choice is a component that provides a type of menu (Combo Box). When user click on a choice, it displays all of the allowed selections. When the user selects one of those items, the choice menu will return into normal position and displays our selected choice. Choices are valuable because they need minimum amount of space on our display area. This class has only one constructor i.e. Choice()

19 Choices Various methods of the class are as follows : Method
Description void add(String str) Adds str as an item void addItem(String str) void addItemListener(ItemListener il) Register il to receive item events generated by this choice. String getIndex(int i) Returns the string at index i in the choice int getSelectedIndex() Returns the index of the selected item String getSelectedItem() Returns the selected item Object[] getSelectedObjects() Returns an array with one object,which is the selected item. void insert(String str, int i) Inserts str before the item at index i void removeAll() Removes all the items from the choice void removeItemListener(ItemListener li) Unregister il to receive item events. void select(int i) Selects the item at index I void select(String str) Select the item str.

20 Choices ex\AWT\ChoiceDemo.java Exercise :
Write an applet that contains a choice menu (Combo Box) with three options i.e. red, green and blue and a 30 x 30 pixel canvas. The color of canvas will be according to the selection of the choice from the combo box.

21 Text Fields and Text Areas
A Text Field allows a user to enter one line of text. A Text Area allows a user to enter multiple lines of text. Both of these components can also be used to display output. Both of them generates text events when a character is entered by the user. A text field also generates an action event when a user presses the Enter Key. Both the TextField and TextArea classes extends TextComponent.

22 Text Fields and Text Areas
The TextField class defines four constructors. TextField TextField(String str) TextField(int cols) TextField(String str, int cols) Here the str is the text for the field. The argument cols refers to the width of the field in no. of characters.

23 Text Fields and Text Areas
Various methods of the TextField class are as follows : Method Description void addActionListener(ActionListener al) Register al to receive action events generated by the component char getEchoChar() Returns the echo character for this component void setEchoChar(Char c) Sets the echo character for this component void removeActionListener(ActionListener al) Unregister al to receive action events generated by this component

24 Text Fields and Text Areas
The TextArea class gives us the facility to display our data in multiple lines. This class has five constructors : TextArea() TextArea(String str) TextArea(int r, int c) TextArea(String str, int r, int c) TextArea(String str, int r, int c, int scrollbars)

25 Text Fields and Text Areas
Here the str is the text to be displayed. The r and c arguments indicates the number of rows and columns in the component. The scrollbar argument indicates if horizontal and / or vertical scrollbars should be created. Its possible values are : SCROLLBARS_BOTH, SCROLLBARS_HORIZONTAL_ONLY, SCROLLBARS_VERTICAL_ONLY and SCROLLBARS_NONE

26 Text Fields and Text Areas
There is one method which allows us to add text to the end of the component i.e. void append(String str) here str is the string that is to be appended to the component. Another method which allows us to insert text in the component at required place. void insert(String str, int index) here the str is the string to be inserted immediately before the character at position index.

27 Text Fields and Text Areas
We may replace a subset of the characters in this component with this method : void replaceRange(String str, int start, int end) Here the str is the string to replace, the range of characters between the position start and end. Both TextFields and TextAreas classes are subclasses of TextComponent

28 TextComponent Various methods of the TextComponent class are as follows : Method Description void addTextListener(TextListener tl) Registers tl to receive text events generated by this component String getSelectedText() Returns a string with any text that has been selected by the user. int getSelectionEnd() Returns the index of the last character of selected text int getSelectionStart() Returns the index of the first character of selected text String getText() Returns a string with the content of this component boolean isEditable() Returns true if the component is editable otherwise returns false.

29 TextComponent Various methods of the TextComponent class are as follows : Method Description void removeTextListener(TextListener tl) Unregisters tl to receive text events generated by this component void select(int start,int end) Selects the text from start to end void selectAll() Selectes all of the text in this component void setEditable(boolean flag) If flag is true, the component is in editing form otherwise, it cannot be edited. void setSelectionEnd(int end) Ends the selected text at index end void setSelectionStart(int start) Starts the selected text at index start void setText(String str) Sets the text of the component to str. ex\AWT\TextFieldAreaDemo.java

30 TextComponent Exercise :
Write an applet that contains a label with the string “Name”. A 20 character text field initialized to your name, a label with string “Password” and a 20 character text field that is initially empty. Allow the user to change either of the fields. The echo character for password field should be “*”

31 Lists A List is a component that allows a user to select one or more items. If the list is not large enough to display all of the allowed selections, scrollbars are automatically provided so a user may scan through the entire list. An action event will be generated when a user double-clicks on an item in a list. An item event is generated when a user selects or deselects one of the entries.

32 Lists This class defines three constructors as follows : List()
List(int rows) List(inr rows, boolean multiple) Here, rows is the number of items that are visible to a user. This determines the size of the component. If multiple is true, a user may select multiple entries in a list. Otherwise, only one item may be selected.

33 Lists Various methods of the class are as follows : Method Description
void add(String str) Adds str as an item void add(String str, int i) Adds str as an item at index i void addActionListener(ActionListener al) Registers al to receive action events generated by the list void addItemListener(ItemListener il) Registers il to receive item events generated by the list void deselect(int i) Deselects the item at index i String getItem(int i) Returns the item at index I int getItemCount() Returns the total no. of items String[] getItems() Returns an array of strings that contains all items int getSelectedIndex() Returns the index of the selected item int[] getSelectedIndexes() Returns an int array containing the indexes of selected items

34 Lists Various methods of the class are as follows : Method Description
String getSelectedItem() Returns the selected item String[] getSelectedItems() Returns an array of objects that contains the selected items Object[] getSelectedObjects() boolean isMultipleMode() Returns true if multiple items may be selected otherwise returns false void remove(String str) Removes str from the list void remove(int i) Removes the item at index i void removeAll() Removes all the items from the list void removeActionListener(ActionListener al) Unregister al to receive action events generated by this list void removeItemListener(ItemListener il) Unregister il to receive item events generated by the list

35 Lists Various methods of the class are as follows :
Description void select(int i) Selects the item at index i void setMultipleMode(boolean flag) If flag is true, a user may select multiple items otherwise only one item may be selected. ex\AWT\ListDemo.java Exercise : Write an applet that contains a single selection list and a 30x30 pixel canvas. The item in the list are the 13 different default colors. The list selection determine the color of the canvas.

36 Scrollbars A scrollbar is a component that allows a user to select any integer value within a range defined by a minimum and maximum. A scrollbar contains a slider that may be dragged to continuously vary its value. Alternatively, the user may click on one of the buttons at either end of the scrollbar or in the area between the slider and the buttons. These operations also modify its value.

37 Scrollbars This class defines following constructors : Scrollbar()
Scrollbar(int orientation) Scrollbar(int orientation, int value, int width, int min, int max) Here, orientation indicates if the scrollbar is oriented horizontally or vertically. It is assigned the value HORIZONTAL or VERTICAL. The argument value represents the initial value of the scrollbar. The width of the slider is width. The range of scrollbar is determined by the min and max.

38 Scrollbars Various methods of the class are as follows :
Description void addAdjustmentListener(AdjustmentListener al) Registers al to receive adjustment events generated by this scrollbar. int getValue() Returns the value of the scrollbar void setValue(int i) Sets the value of scrollbar to i. void removeAdjustmentListener(AdjustmentListener al) Unregister al to receive adjustment events generated by the scrollbar. ex\AWT\ScrollbarDemo.java Exercise : Write an applet that contains three scrollbars and a 30x30 pixel canvas. The values of scrollbars will determine the color of canvas.

39 Layout Managers Layout managers provide significant benefits. First, it is not necessary to calculate the coordinates at which an element should be placed. This time-consuming and error-prone work is done for you. Second if an applet is resized, the layout manager dynamically adjust the placement of the elements. Third, components typically have different sizes on different platforms. Therefore it is not possible to specify one set of coordinates that will be suitable in all environments.

40 Layout Managers The layout manager handles this task for you. It is one of the approach of java libraries to support platform independence. It is also possible for us to specify a position and size for each component but this is harmful because then our applet will no longer platform-independent. A layout manager is associated with each Container object. The methods to get and set this association are as follows : LayoutManager getLayout(); void setLayout(LayoutManager lm)

41 FlowLayout class FlowLayout is the default layout manager for an applet. This class places the components in a row that is centered in the available space. If the components cannot fit in the current row, another row will be started. This class has three constructors which are as follows: (1) FlowLayout() (2) FlowLayout(int align) (3) FlowLayout(int align, int hgap, int vgap)

42 FlowLayout class Here, the align indicates how the components are aligned in a row. The horizontal and vertical gap in pixels between will be set through hgap and vgap The FlowLayout class also defines three constants that can be used as alignment i.e. LEFT, CENTER and RIGHT. ex\AWT\FlowLayoutDemo.java Exercise : Change the pixels of vgap and hgap and find the changes in the output.

43 BorderLayout Class The BorderLayout class allows a programmer to specify the placement of a component. This is done by using geographic terms i.e. “North”, “South”, “East”, “West” or “Center”. The components are placed around the periphery with the sizes they require. The components in the center uses the remaining space. This class has two constructors are as follows : (1) BorderLayout() (2) BorderLayout(int hgap, int vgap)

44 BorderLayout Class The first form uses no gaps between the components. The second form allows you to set the horizontal and vertical gaps between the components with the help of hgap and vgap. With BorderLayout class gives a different form of add method used which is as follows : void add(Component c, Object o) Here c is the component to be added to the applet and the obj is the string that identifies its position through one of the geographic terms. ex\AWT\BorderLayoutDemo.java

45 GridLayout and insets The GridLayout class automatically arranges components in grid. All components are created with equal size. This class has three constructors which are as follows : (1) GridLayout() (2) GridLayout(int r, int c) (3) GridLayout(int r, int c, int hgap, int vgap) Here r and c are the no. of rows and columns in the grid. The hgap and vgap are the horizontal and vertical gap respectively.

46 Insets class The Insets class encapsulates information about the top, left, bottom and right margins around the boundary of a container. It provides this constructor : Insets(int top, int left, int bottom, int right) Here each of the argument represents a border of given pixels. In order to specify the insets for a container, we can override the method getInsets() which will return the Insets object. ex\AWT\GridLayoutDemo.java

47 Panels The Panel class extends Container. It appears as a rectangular area in which other components are arranged. A layout manager is associated with a panel and determines the placement of those components. You can set the layout manager that is used for a panel. It is also possible to nest the panel within other panels. This can be done because a Panel object is also a Component. Here we can use different layout managers to arrange different areas of the display.

48 Panels ex\AWT\PanelDemo.java Exercise :
Create an applet whose display is organized as one row and two columns. The first column contains three radio buttons labeled red, green and blue. The second column contains four checkboxes with your favorite fruit names

49 Windows and Frames The window class extends Container and provides a separate window without a tile or menu bar. This class has two subclasses, Frame and Dialog, that are commonly used in applets and windows based applications. This class has only one constructor i.e. Window(Frame parent) Here the parent is the owner of this window.

50 Windows and Frames We have register / unregister various window events via this method. void addWindowListener(WindowListener wl) void removeWindowListener(WindowListener wl) Here the wl is the window listener object A new window is initially invisible. To make it appear, invoke the show() method as follows : void show() Finally when you finish using a window, you should relinquish its resources by calling dispose() like void dispose()

51 Windows and Frames A window object generates events when a window is activated, closed, closing, deactivated, deiconified (invoked when a window is changed from a minimized to a normal state), iconified (invoked when a window is changed from a normal to a minimized state), or opened. A java.awt.event.WindowEvent object is created to describe this event. The WindowListener interface provides us various methods to handle window events which are as follows :

52 Windows and Frames void windowActivated(WindowEvent we)
void windowClosed(WindowEvent we) void windowClosing(WindowEvent we) void windowDeactivted(WindowEvent we) void windowDeiconified(WindowEvent we) void windowIconified(WindowEvent we) void windowOpened(WindowEvent we) Here the we is the WindowEvent objecte generated by the source. The windowActivated() and windowDeactivated() methods are called when the window is activated or deactivated.

53 Windows and Frames The windowClosing() method is called when a user requests that a window to be closed. The windowClosed() method is called after a Window object has been closed through setVisible() or destroy() methods. The windowDeiconified() and windowIconified() methods are called after a window is deiconified or iconified. The windowOpened() method is called when a window is initially opened.

54 Windows and Frames The Frame class extends Window and provids title and menu bar. This is equivalent to what you have seen as a standard window in graphical user interface. It has following constructors (1) Frame() (2) Frame(String title) Here title is the string to be displayed in the title bar. We can also have menubar with following methods (1) MenuBar getMenuBar() (2) void setMenuBar(MenuBar mb)

55 Windows and Frames We may get and set the title with the help of following methods. (1) String getTitle() (2) void setTitle(String str) here, str is the string that is used in the title bar of the frame. ex\AWT\FrameApplicationDemo.java ex\AWT\FrameAppetDemo.java Exercise : Expand the above FrameAppetDemo so that it count no. of frames and display that no. in title bar

56 Menus and MenuBars A Frame may contain a menu bar. This represents a set of options for the user. When the mouse is clicked on an option a drop down list of sub options appears. Each of these sub options may also have sub options associated with it. Some sub options may be checkable. i.e. a check mark will be appeared when we select that particular option. In the following figure we can see the actual relationship among the classes that provides this functionality.

57 Menus and MenuBars Object MenuComponent MenuBar MenuItem Menu
CheckboxMenuItem

58 Menus and MenuBars Here, the MenuComponent class is the superclass of all other classes. The Font used for a menu-related string may be set via its setFont() method as below : void setFont(Font f) here f is the font to be used. The MenuBar class encapsulates the functionality of a menu bar. It has this constructor : Menubar()

59 Menus and MenuBars There is one method called add() which allows the Menu objectes to be added to the menu bar. Menu add(Menu m) Here m is the Menu to be added to the MenuBar. The Menu class encapsulates the functionality of a drop-down set of menu items. Its constructor is : Menu (String str) Here str is the string to be displayd.

60 Menus and MenuBars In MenuItem also we have one method called add() to add MenuItems to the menu MenuItem add(MenuItem mi) void add(String str) Here mi is the MenuItem to be added to the menu and str is a string to be added to the menu. The MenuItem class encapsulates an item in a menu. Its constructor is MenuItem(String str) here str is the string to be displayed.

61 Menus and MenuBars All the menu items will generate actions events when they are selected or deselected for that we need to register ActionListener like : void addActionListener(ActionListener al) void removeActionListener(ActionListener al) here al is the action listener. We can also enable or disable any menuitem with the help of following method void setEnabled(boolean flag) if the flag is true then menu item is enabled otherwise disabled.

62 Menus and MenuBars The CheckBoxMenuItem class allows us to create Menu Item with checkbox for that constructors are : CheckboxMenuItem(String str) CheckboxMenuItem(String str, boolean flag) Here str is the string to be displayed for the checkbox menu item. If flag is true, the item is checked otherwise not checked. CheckboxMenuItem will generate item events when they are selected or deselected.

63 Menus and MenuBars We have two methods to register and unregister listener like : (1) void addItemListener(ItemListener il) (2) void removeItemListener(ItemListener il) here il is the item listener To find / replace the state of the check box menu item we have two methods like : boolean getState() void setState(boolean flag) if flag is true then checkbox menu item is set otherwise it is cleared.

64 Menus and MenuBars ex\AWT\MenuDemo.java Exercise :
Develop a menu like Microsoft Word’s File Menu with Help menu.

65 Dialog and FileDialog Dialogs are commonly presented in graphic user interface to display information or obtain input. A model dialog does not permit a user to make another window in the application active until it has been closed. A modeless dialog allows a user to switch to another window in the application before closing the dialog.

66 Dialog and FileDialog The Dialog class extends Window. It provides a window in which all of the user interface components will be used as it is. This class has four constructors : Dialog(Frame parent) Dialog(Frame parent, boolean flag) (3) Dialog(Frame parent, String title) (4) Dialog(Frame parent, String title, boolean flag) Here the parent is the reference to the owner of the dialog. The dialog is model if the flag is true otherwise it is modeless.

67 Dialog and FileDialog The show() method of the class is useful to make a dialog visible. void show() The FileDialog class extends Dialog and provides a dialog that allows a user to select a file for reading and writing. This is very useful for applications that need to save data to a file and later retrieve that data. This class defines two int constants named LOAD and SAVE. These will determine that the file dialog is used to select a file for reading or writing.

68 Dialog and FileDialog This class has three constructors :
(1) FileDialog(Frame parent) (2) FileDialog(Frame parent, String str) (3) FileDialog(Frame parent, String str, int rw) Here parent is the frame that creates this dialog. The title bar will be defined by the str. The final argument indicates if this file dialog identifies a file for loading or saving. if rw is LOAD, a file will be identified for reading. If rw is SAVE, a file is for writing. The first two forms will create a file dialog for LOAD a file.

69 Dialog and FileDialog ex\AWT\MessageDialog.java
ex\AWT\FileDialogApplication.java Exercise : (1) Write an application that creates a frame with one button. Each time the button is pressed, a model dialog box appears that displays a random color in 100 x 100 pixel canvas in the dialog box. In that dialog box we have ok button to close it.

70 Dialog and FileDialog Exercise :
(2) Construct an application that displays a button and a 0 x 50 pixel canvas. Label the button as “Color Dialog” and fill the canvas with red color by default. When the user press the above button it will display a model dialog box with 3 scrollbars and an ok button. When user change the value of scrollbar and press ok then that dialog box will disappear and the color of canvas will be according to the values of all the three (RGB) scrollbars.

71 Dialog and FileDialog Exercise :
(3) Write an application that creates a frame with one button. Each time the button is pressed, a model dialog box appears that displays the current date. Write an applet that displays a calendar for the current month and year. Develop an applet for calculator

72 Thank You


Download ppt "Fundamental of Java Programming Abstract Window Toolkit"

Similar presentations


Ads by Google