![]() |
Java Control Fundamentals
This article continues our exploration of the Abstract Window Toolkit (AWT). It examines the standard controls defined by Java. Controls are components that allow a user to interact with your application in various ways—for example; a commonly used control is the push button.
The AWT supports the following types of controls:-
Adding and Removing ControlsTo include a control in a window, you must add it to the window. To do this, you must first create an instance of the desired control and then add it to a window by calling add( ), which is defined by Container. The add( ) method has several forms. Component add(Component compObj) Here, compObj is an instance of the control that you want to add. A reference to compObj is returned. Once a control has been added, it will automatically be visible whenever its parent window is displayed. Sometimes you will want to remove a control from a window when the control is no longer needed. To do this, call remove( ). This method is also defined by Container. It has this general form: void remove(Component obj) Here, obj is a reference to the control you want to remove. You can remove all controls by calling removeAll( ). Responding to ControlsExcept for labels, which are passive controls, all controls generate events when they are accessed by the user. For example, when the user clicks on a push button, an event is sent that identifies the push button. In general, your program simply implements the appropriate interface and then registers an event listener for each control that you need to monitor. Once a listener has been installed, events are automatically sent to it. LabelsThe easiest control to use is a label. A label is an object of type Label, and it contains a string, which it displays. Labels are passive controls that do not support any interaction with the user. Label defines the following constructors:
The second version creates a label that contains the string specified by str. This string is left-justified. The third version creates a label that contains the string specified by str using the alignment specified by how. The value of how must be one of these three constants: Label.LEFT, Label.RIGHT, or Label.CENTER. You can set or change the text in a label by using the setText( ) method. You can obtain the current label by calling getText( ). These methods are shown here:
For setText( ), str specifies the new label. For getText( ), the current label is returned. You can set the alignment of the string within the label by calling setAlignment( ). To obtain the current alignment, call getAlignment( ). The methods are as follows:
The following example creates three labels and adds them to an applet:- Code:
import java.awt.*;http://www.go4expert.com/images/arti.../controlsA.jpg Using ButtonsThe most widely used control is the push button. A push button is a component that contains a label and that generates an event when it is pressed. Push buttons are objects of type Button. Button defines these two constructors:
The first version creates an empty button. The second creates a button that contains str as a label. After a button has been created, you can set its label by calling setLabel( ). You can retrieve its label by calling getLabel( ). These methods are as follows:
Handling ButtonsEach time a button is pressed, an action event is generated. This is sent to any listeners that previously registered an interest in receiving action event notifications from that component. Each listener implements the ActionListener interface. That interface defines the actionPerformed( ) method, which is called when an event occurs. An ActionEvent object is supplied as the argument to this method. It contains both a reference to the button that generated the event and a reference to the string that is the label of the button. Example: Here is an example that creates three buttons labeled “Yes,” “No,” and “Undecided.” Each time one is pressed, a message is displayed that reports which button has been pressed. In this version, the label of the button is used to determine which button has been pressed. The label is obtained by calling the getActionCommand( ) method on the ActionEvent object passed to actionPerformed( ). Code:
import java.awt.*;http://www.go4expert.com/images/arti.../controlsB.jpg Check BoxesA check box is a control that is used to turn an option on or off. It consists of a small box that can either contain a check mark or not. There is a label associated with each check box that describes what option the box represents. You change the state of a check box by clicking on it. Check boxes can be used individually or as part of a group. Check boxes are objects of the Checkbox class. Checkbox supports these constructors:
The first form creates a check box whose label is initially blank. The state of the check box is unchecked. The second form creates a check box whose label is specified by str. The state of the check box is unchecked. The third form allows you to set the initial state of the check box. If on is true, the check box is initially checked otherwise, it is cleared. The fourth and fifth forms create a check box whose label is specified by str and whose group is specified by cbGroup. If this check box is not part of a group, then cbGroup must be null. (Check box groups are described soon in this article) The value of on determines the initial state of the check box. To retrieve the current state of a check box, call getState( ). To set its state, call setState(). You can obtain the current label associated with a check box by calling getLabel( ). To set the label, call setLabel( ). These methods are as follows:
Handling Check BoxesEach time a check box is selected or deselected, an item event is generated. This is sent to any listeners that previously registered an interest in receiving item event notifications from that component. Each listener implements the ItemListener interface. That interface defines the itemStateChanged( ) method. An ItemEvent object is supplied as the argument to this method. It contains information about the event (for example, whether it was a selection or deselection). Example: The following program creates four check boxes. The initial state of the first box is checked. The status of each check box is displayed. Each time you change the state of a check box, the status display is updated. Code:
import java.awt.*;http://www.go4expert.com/images/arti.../controlsC.jpg CheckboxGroupIt is possible to create a set of mutually exclusive check boxes in which one and only one check box in the group can be checked at any one time. These check boxes are often called radio buttons, because they act like the station selector on a car radio—only one station can be selected at any one time. To create a set of mutually exclusive check boxes, you must first define the group to which they will belong and then specify that group when you construct the check boxes. Check box groups are objects of type CheckboxGroup. Only the default constructor is defined, which creates an empty group. You can determine which check box in a group is currently selected by calling getSelectedCheckbox( ). You can set a check box by calling setSelectedCheckbox( ). These methods are as follows:
Here, which is the check box that you want to be selected. The previously selected check box will be turned off. Example: Here is a program that uses check boxes that are part of a group: Code:
import java.awt.*;http://www.go4expert.com/images/arti.../controlsD.jpg Choice ControlsThe Choice class is used to create a pop-up list of items from which the user may choose. Thus, a Choice control is a form of menu. When inactive, a Choice component takes up only enough space to show the currently selected item. When the user clicks on it, the whole list of choices pops up, and a new selection can be made. Each item in the list is a string that appears as a left-justified label in the order it is added to the Choice object. Choice only defines the default constructor, which creates an empty list. To add a selection to the list, call add( ). It has this general form: void add(String name) Here, name is the name of the item being added. Items are added to the list in the order in which calls to add( ) occur. To determine which item is currently selected, you may call either getSelectedItem( ) or getSelectedIndex( ). These methods are shown here:
The getSelectedItem( ) method returns a string containing the name of the item. getSelectedIndex( ) returns the index of the item. The first item is at index 0. By default, the first item added to the list is selected. To obtain the number of items in the list, call getItemCount( ). You can set the currently selected item using the select( ) method with either a zero-based integer index or a string that will match a name in the list. These methods are shown here:
Given an index, you can obtain the name associated with the item at that index by calling getItem( ), which has this general form: String getItem(int index) Here, index specifies the index of the desired item. Handling Choice ListsEach time a choice is selected, an item event is generated. This is sent to any listeners that previously registered an interest in receiving item event notifications from that component. Each listener implements the ItemListener interface. That interface defines the itemStateChanged( ) method. An ItemEvent object is supplied as the argument to this method. Example:- Here is an example that creates two Choice menus. One selects the operating system. The other selects the browser. Code:
import java.awt.*;ListsThe List class provides a compact, multiple-choice, scrolling selection list. Unlike the Choice object, which shows only the single selected item in the menu, a List object can be constructed to show any number of choices in the visible window. It can also be created to allow multiple selections. List provides these constructors:
The first version creates a List control that allows only one item to be selected at any one time. In the second form, the value of numRows specifies the number of entries in the list that will always be visible (others can be scrolled into view as needed). In the third form, if multipleSelect is true, then the user may select two or more items at a time. If it is false, then only one item may be selected. To add a selection to the list, call add( ). It has the following two forms:
Here, name is the name of the item added to the list. The first form adds items to the end of the list. The second form adds the item at the index specified by index. Indexing begins at zero. You can specify –1 to add the item to the end of the list. For lists that allow only single selection, you can determine which item is currently selected by calling either getSelectedItem( ) or getSelectedIndex( ). These methods are shown here:
To obtain the number of items in the list, call getItemCount( ). You can set the currently selected item by using the select( ) method with a zero-based integer index. These methods are shown here:
String getItem(int index) Here, index specifies the index of the desired item. Handling ListsTo process list events, you will need to implement the ActionListener interface. Each time a List item is double-clicked, an ActionEvent object is generated. Its getActionCommand( ) method can be used to retrieve the name of the newly selected item. Also, each time an item is selected or deselected with a single click, an ItemEvent object is generated. Its getStateChange( ) method can be used to determine whether a selection or deselection triggered this event. getItemSelectable( ) returns a reference to the object that triggered this event. Example: Here is an example that converts the Choice controls in the preceding section into List components, one multiple choice and the other single choice: Code:
import java.awt.*;http://www.go4expert.com/images/arti...controls2A.jpg Scroll BarsScroll bars are used to select continuous values between a specified minimum and maximum. Scroll bars may be oriented horizontally or vertically. A scroll bar is actually a composite of several individual parts. Each end has an arrow that you can click to move the current value of the scroll bar one unit in the direction of the arrow. The current value of the scroll bar relative to its minimum and maximum values is indicated by the slider box (or thumb) for the scroll bar. The slider box can be dragged by the user to a new position. The scroll bar will then reflect this value. In the background space on either side of the thumb, the user can click to cause the thumb to jump in that direction by some increment larger than 1. This action translates into some form of page up and page down. Scroll bars are encapsulated by the Scrollbar class. Scrollbar defines the following constructors:
The second and third forms allow you to specify the orientation of the scroll bar. If style is Scrollbar.VERTICAL, a vertical scroll bar is created. If style is Scrollbar.HORIZONTAL, the scroll bar is horizontal. In the third form of the constructor, the initial value of the scroll bar is passed in initialValue. The number of units represented by the height of the thumb is passed in thumbSize. The minimum and maximum values for the scroll bar are specified by min and max. If you construct a scroll bar by using one of the first two constructors, then you need to set its parameters by using setValues( ), shown here, before it can be used: void setValues(int initialValue, int thumbSize, int min, int max) The parameters have the same meaning as they have in the third constructor just described. To obtain the current value of the scroll bar, call getValue( ). It returns the current setting. To set the current value, call setValue( ). These methods are as follows:
You can also retrieve the minimum and maximum values via getMinimum( ) and getMaximum( ), shown here:
By default, 1 is the increment added to or subtracted from the scroll bar each time it is scrolled up or down one line. You can change this increment by calling setUnitIncrement( ). By default, page-up and page-down increments are 10. You can change this value by calling setBlockIncrement( ). These methods are shown here:
Handling Scroll BarsTo process scroll bar events, you need to implement the AdjustmentListener interface. Each time a user interacts with a scroll bar, an AdjustmentEvent object is generated. Its getAdjustmentType( ) method can be used to determine the type of the adjustment. The types of adjustment events are as follows: BLOCK_DECREMENT--A page-down event has been generated. BLOCK_INCREMENT--A page-up event has been generated. TRACK--An absolute tracking event has been generated. UNIT_DECREMENT--The line-down button in a scroll bar has been pressed. UNIT_INCREMENT--The line-up button in a scroll bar has been pressed. Example: The following example creates both a vertical and a horizontal scroll bar. The current settings of the scroll bars are displayed. If you drag the mouse while inside the window, the coordinates of each drag event are used to update the scroll bars. An asterisk is displayed at the current drag position. Code:
import java.awt.*;http://www.go4expert.com/images/arti...controls2B.jpg TextFieldThe TextField class implements a single-line text-entry area, usually called an edit control. Text fields allow the user to enter strings and to edit the text using the arrow keys, cut and paste keys, and mouse selections. TextField is a subclass of TextComponent. TextField defines the following constructors:
The second form creates a text field that is numChars characters wide. The third form initializes the text field with the string contained in str. The fourth form initializes a text field and sets its width. TextField (and its superclass TextComponent) provides several methods that allow you to utilize a text field. To obtain the string currently contained in the text field, call getText( ). To set the text , call setText( ). These methods are as follows:
The user can select a portion of the text in a text field. Also, you can select a portion of text under program control by using select( ). A program can obtain the currently selected text by calling getSelectedText( ). These methods are shown here:
getSelectedText( ) returns the selected text. The select( ) method selects the characters beginning at startIndex and ending at endIndex–1. You can control whether the contents of a text field may be modified by the user by calling setEditable( ). You can determine editability by calling isEditable( ). These methods are shown here:
There may be times when you will want the user to enter text that is not displayed, such as a password. You can disable the echoing of the characters as they are typed by calling setEchoChar( ). This method specifies a single character that the TextField will display when characters are entered (thus, the actual characters typed will not be shown). You can check a text field to see if it is in this mode with the echoCharIsSet( ) method. You can retrieve the echo character by calling the getEchoChar( ) method. These methods are as follows:
Handling a TextFieldSince text fields perform their own editing functions, your program generally will not respond to individual key events that occur within a text field. However, you may want to respond when the user presses ENTER. When this occurs, an action event is generated. Example: Here is an example that creates the classic user name and password screen: Code:
import java.awt.*;http://www.go4expert.com/images/arti...controls2C.jpg TextAreaSometimes a single line of text input is not enough for a given task. To handle these situations, the AWT includes a simple multiline editor called TextArea. Following are the constructors for TextArea:
In the fifth form you can specify the scroll bars that you want the control to have. sBars must be one of these values:
TextArea is a subclass of TextComponent. Therefore, it supports the getText( ), setText( ), getSelectedText( ), select( ), isEditable( ), and setEditable( ) methods. TextArea adds the following methods:
The append( ) method appends the string specified by str to the end of the current text. insert( ) inserts the string passed in str at the specified index. To replace text, call replaceRange( ). It replaces the characters from startIndex to endIndex–1, with the replacement text passed in str. Text areas are almost self-contained controls. Your program incurs virtually no management overhead. Text areas only generate got-focus and lost-focus events. Normally, your program simply obtains the current text when it is needed. Example: The following program creates a TextArea control: Code:
import java.awt.*;http://www.go4expert.com/images/arti...controls2D.jpg |
Re: Java Control Fundamentals
Really nice articles.
|
Re: Java Control Fundamentals
Quote:
|
Re: Java Control Fundamentals
If you liked this article do nominate this article for Article of the month - May 2010
|
Re: Java Control Fundamentals
Nice article, I got lot of knowledge reading with this.
|
Re: Java Control Fundamentals
I would take cps 113 because it seems that this class teaches you basic class structure, data types, and program structure. Both Java and VB stem from the understanding of cps113's concepts. And also to be easier to program in C you would to understand basic structures of all programs. If you don't prefer that then cps 121 would be my next choice because it's similar to C, it's just more slated towards GUI's than C is but syntax is the same. VB is a simple language because it's drag and drop components onto a field to created a form then program what each button/lable/box does in the BASIC programming language which is .. well... err... very basic lol
|
Re: Java Control Fundamentals
nice article.....:-)
|
Re: Java Control Fundamentals
Awesome article but I think it was too much lengthy it could have been possible to split it in multiple parts and introduce each different control in a separate post. It would be helpful if it was in such way because suppose if someone wanted to know just about TextArea... he doesn't have to scroll all the area.
|
Re: Java Control Fundamentals
send to my email
|
| All times are GMT +5.5. The time now is 09:31. |