AWT Controls, Layout Managers and Menus -


User can interact with the application using AWT controls, for example user can input any message using TextField control.
Layout Managers defines layouts using which controls are automatically positions within container. In this chapter we will use Applet as Container. By default Applet has FlowLayout.
Menu Bars are used to provide a drop down menu from which user can make a choice.

AWT Controls -

AWT have the following control classes -
  • Label
  • TextField
  • Button
  • Checkbox
  • RadioButton
  • TextArea
  • Choice (Drop Down List)
  • List
  • ScrollBar
All these classes are child (subclasses) of Component class.

Adding and Removing a Control in Container -

Container class provides add() method to add components in container.
There are several versions of add() available. The most commonly used is -
Component add(Component component_Obj)
Where component_Obj is the object of the component you want to add to the container.
If a control is no longer needed, you can remove that control from container using the remove() method of Container class. It also have several form, the most commonly used is -
void remove(Component Component_Obj)
Where Component_Obj is the object of component you want to remove.
If you want to remove all the controls from Container, you can use the removeAll() method. It has the following syntax -
void removeAll()

Label -

Labels are used to display text messages within containers. It is a passive control i.e. user cannot interact with this and also these is no event specified for Labels. Label text cannot be edited by users.
It has the following constructors -
  • Lable() throws HeadlessException
    Creates a blank Label i.e with no text
            
  • Lable(String text_message) throws HeadlessException
    Creates a Label with the specified text_message. The alignment of text_message will be left justified.
    
            
  • Lable(String text_message, int text_alignment) throws HeadlessException
    Creates a Label with the specified text_message and alignment. text_alignment can have one of the following 
    values - Label.LEFT,  Lable.RIGHT, Lable.CENTER, these are the static int fields.
    
Note -
All the constructors throws HeadlessException, it is a subclass of RuntimeException (i.e. a unchecked exception) and added in 1.4 version of jdk. It is thrown when code that is dependent on a keyboard, display, or mouse is called in an environment that does not support a keyboard, display, or mouse.

Methods of Label -

  • setText() - It is used to set the text of a blank label or to change the existing text of any label. It has the following syntax -
        public void setText(String text_message)    
        
  • getText() - It is used to get the current text of any label. It has the following syntax -
        public String getText()     
        
  • setAlignment() - It is used to set the alignment of the label text. It has the following syntax -
        public void setAlignment(int text_alignment)     
        
  • setAlignment() - It is used to set the alignment of the label text. It has the following syntax -
        public void setAlignment(int text_alignment)  
         text_alignment can have one of the following values - Label.LEFT,  Lable.RIGHT, Lable.CENTER.   
        
  • getAlignment() -It is used to get the Label current alignment value. It has the following syntax -
        public int getAlignment()  
         

Example -

import java.awt.*;
import java.applet.*;
public class Text extends Applet
{
    public void init()
    {
    Label l1 = new Label();
    l1.setText("UserName:");
    l1.setAlignment(Label.CENTER);  // label text will be in centre of label.
    Label l2 = new Label("Password:");  // label text will be left justified within label by default.
    Label l3 = new Label("Email_ID:",Label.RIGHT);   // label of text will be right justified within label.
    add(l1);
    add(l2);
    add(l3);

    }
}     

Output -


Note the position of labels in Applet window. They are placed one after another until complete width of the container filled and then on the next line; this type of layout is used by FlowLayout that is default Layout for Applets. Details of FlowLayout will be covered later.

TextField -

TextField is a text box in which user can enter a single line of text. It is normally used to take text input from users.
It has the following constructors -
  • TextField() throws HeadlessException
    It creates a text field with the default size.
    
  • TextField(String text_message) throws HeadlessException
    It creates a text field with specified text_message. 
    
  • TextField(int no_of_columns) throws HeadlessException
    It creates a text field with size specified as no_of_columns. 
    
  • TextField(String text_message, int no_of_columns) throws HeadlessException
    It creates a text field with the specified text_message and size of text field.
    

Methods of TextField -

TextField and its parent class TextComponent has several methods but the most commonly used are as follows -
  • setText() - It is used to specify the text of text field. It has the following syntax -
    public void settext(String text_message)
    Where text_message is the text you want to display in text field.
         
  • getText() - It us used to get the text specified in text field. It has the following syntax -
    public String getText()
    It returns the text of text filed in the form of String.
         
  • isEditable() - It is used to check whether the given text field is editable by user or not. It has the following syntax -
    public boolean isEdiatble()
    It returns true if the text field is user editable and false otherwise.
         
  • setEditable() - It is used to specify whether user can edit the text within text field or not. It has the following syntax -
    public void setEdiatble(boolean val)
    val is set to true then the text field can be edited by user and if the val is set to false then user can not edit the text of the text field.
         
  • setBackground() - It is used to set the background color of text field. It has the following syntax -
    public void setBackground(Color color)
    color  can have any value of color supported by java.     
    We can also get the background color of text filed by using the following method -
    public Color getBackground()
  • setEchoChar() - It is used to re-place the text you entered in the text field with a specified character. It is normally required when you entered some confidential data in text field that you do not want to show to others for example when you enter password. It has the following syntax -
    public void setEchoChar(char ch))
    It will replace all the text you will enter your text field with specified character ch.
    
    You can also get the echo character used by using the following method -
    public char getEchoChar()
    

Example -

import java.awt.*;
import java.applet.*;
public class Test extends Applet
{
    public void init()
    {
    Label l1 = new Label("UserName:");
    Label l2 = new Label("Password:");
    Label l3 = new Label("EmailID:");
    TextField t1 = new TextField(10);  // text field with 10 columns size
    TextField t2 = new TextField(20);  // text field with 20 columns size
    t2.setEchoChar('*');
    TextField t3 = new TextField("Enter Email ID here"); //text field with specified text
    add(l1);
    add(t1);
    add(l2);
    add(t2);
    add(l3);
    add(t3);

    }
}
    

Output -


Note- Right now positions of controls is not properly managed, We will learn that in Layout Managers.

Button -

It is a simple push button that is used to perform some action when user clicks on it. When user click on button it generate event to perform some action. It has following 2 constructors -
  • Button() throws HeadlessException
    It creates a button with no label (text) on it.
                
  • Button(String text_label) throws HeadlessException
    It creates a button with specified text label.
                

Button Methods -

It has several methods, some most commonly used are as follows -
  • setLabel() - It is used to set the label of button to the specified text label. It has the following syntax -
    public void setLabel(String text_label)
  • getLabel() - It is used to get the button label. It has the following syntax -
    public String getLabel()

Example -

import java.awt.*;
import java.applet.*;
public class Test extends Applet
{
    public void init()
    {
    Label l1 = new Label("UserName:");
    Label l2 = new Label("Password:");
    Label l3 = new Label("EmailID:");
    TextField t1 = new TextField(10);  // text field with 10 columns size
    TextField t2 = new TextField(20);  // text field with 20 columns size
    t2.setEchoChar('*');
    TextField t3 = new TextField("Enter Email ID here"); //text field with specified text
    Button b1 = new Button();
    b1.setLabel("Submit");
    Button b2 = new Button("Cancel");
    add(l1);
    add(t1);
    add(l2);
    add(t2);
    add(l3);
    add(t3);
    add(b1);
    add(b2);

    }
}
    

Output -


Checkbox -

A checkbox control is represented by a small box that can be in one of the two states ? checked (or on or true) or unchecked (or off or false). When a user clicks on a checkbox it changes states from checked to unchecked or unchecked to checked depending upon its current state. There is a label associated with each checkbox that describe what option the checkbox represents.
It has total 5 constructors out of which 2 are used to create Radio Buttons that we will cover next. Remaining 3 constructors are as follows -
  • public Checkbox() throws HeadlessException - 
    It creates checkbox that is not having any label associated with it. 
    The state of checkbox will be unchecked by default.
    
  •  public Checkbox(String label) throws HeadlessException - 
    It creates a checkbox with the specified label. The state of checkbox will be unchecked by default.
    
  • public Checkbox(String label, boolean state) - 
    It creates a check box with the specified label and state. State can have values true or false, true means 
    checked state and false means unchecked state.
    

Checkbox Methods

It has several methods, some most commonly used are as follows-
  • setLabel() - It is used to set the label of a check box. It has the following syntax -
    public void setLabel(String label)    
    
  • getLabel() - It is used to get the label of checkbox. It has following syntax -
    public String getLabel()   
    
  • setState() - It is used to set the state of checkbox to checked (true) or unchecked (false). It has the following syntax -
    public void setState(boolean state)   
    
  • gestate() - It is used to get the state of any particular check box. It has the following syntax -
    public boolean getState()  
    

Example -

import java.awt.*;
import java.applet.*;
public class Test extends Applet
{
    public void init()
    {
    Label l1 = new Label("Computer Skills:-");
    Checkbox c1 = new Checkbox();
    c1.setLabel("C Language");
    Checkbox c2 = new Checkbox("Java");  // by default state will be false i.e. unchecked
    c2.setState(true);
    Checkbox c3 = new Checkbox("Android", true);
    Checkbox c4 = new Checkbox("SalesForce", false);
    add(l1);
    add(c1);
    add(c2);
    add(c3);
    add(c4);

    }
}    

Output -


RadioButton -

There is no separate class for creating radio buttons. They are created using Checkbox and CheckboxGroup classes. Radio buttons are a set of checkbox buttons exist in a group created by CheckboxGroup. CheckboxGroup class is used to group together a set of Checkbox Buttons.
CheckboxGroup has only one constructor defined -
public CheckboxGroup()
It creates an empty CheckboxGroup object.        

Difference between Checkbox and Radio Button-

Radio Buttons are a set of mutually exclusive checkbox buttons in which we can select only one button at a time; where as in case of checkbox we can select any number of checkbox at a time.
Checkbox are represented by a small square box shape, whereas Radio buttons are represented by small circle shape (that is like buttons of a radio that are used to switch from one radio station to another).
We can create radio buttons by using the remaining 2 constructor of Checkbox class -
  • public Checkbox(String label, boolean state, CheckboxGroup group) throws HeadlessException
    It creates a radio button with the specified label, state and in the specified group (group is an object of CheckboxGroup class).  
    
  • 2-	public Checkbox(String label, CheckboxGroup group, boolean state) throws HeadlessException
    Exactly similar to first one except that the position of CheckboxGroup and state has interchanged.  
    

Example -

import java.awt.*;
import java.applet.*;
public class Test extends Applet
{
    public void init()
    {
    Label l1 = new Label("Select your gander");
    CheckboxGroup cg = new CheckboxGroup();  
    Checkbox c1 = new Checkbox("Male", true, cg); //using 1st constructor
    Checkbox c2 = new Checkbox("Female", cg, false); // using 2nd constructor
    Checkbox c3 = new Checkbox("Other", false, cg);  // using 1st constructor

    add(l1);
    add(c1);
    add(c2);
    add(c3);

    }
}
    

Output -


Choice Control-

It is used to create a drop down list of String type items, out of which user can select item at a time. It has the following constructor -
  • public Choice() throws HeadlessException
    It creates a choice list with no item in it. We can add items to it by using add() method of Choice class.
    
                

Choice Methods -

It has several methods but most commonly used are as follows -
  • add() - It is used to add or insert items in choice list. This method add item at the end of items presented in choice. It has the following syntax -
    public void add(String item_name)    
    
  • insert() - It used to add or insert items in choice list at the specified position. It ha sthe following syntax -
    public void insert(String item, int position)    
    Where item is name of item you want to insert and position is the index at which you want to insert the item. 
    Note that index starts from 0.
    
  • remove() - It is used to remove an item from choice list. It has following 2 versions -
    public void remove(String item_name)
    It removes an item specified by item_name from choice list.
    
    public void remove(int item_index)
    It remove an item specified by item_index from choice list. Note that index starts from 0.
        
    
  • removeAll() - It is used to remove all the items from choice list. It has the following syntax -
    public void removeAll()
    
  • getItemCount() - It returns the number of items presented in the choice list. It has the following syntax -
    public int getItemCount()
    
  • getItem() - It is used to get the item presented at a specified position. It has the following syntax -
    public String getItem(int position)
    Where position is index of item you want to get from choice list. Note that index starts from 0.
    
  • getSelectedItem() - It is used to get the currently selected item. It has the following syntax -
    public String getSelectedItem()
    
  • getSelectedIndex() - It is used to get the index position of currently selected item. It has the following syntax -
    public int getSelectedIndex()
    

Example -

import java.awt.*;
import java.applet.*;
public class Test extends Applet
{
    public void init()
    {
    Label l1 = new Label("Select your Country:-");
    Choice ch  = new Choice();
    ch.add("India");
    ch.add("USA");
    ch.add("China");
    ch.add("Japan");
    ch.add("England");
    add(l1);
    add(ch);

    }
}
    

Output -


List Control -

List control provides us a flexible scrolling drop down list. It enables us to create a multi-choice scrolling drop down 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 the following constructors -
  • public List() throws HeadlessException        
    It creates a scrolling drop down list. By default there are four rows of the list will be visible and multiple
    selections will be false i.e. only one item can be selected at a time.
    
  • public  List(int rows_visible) throws HeadlessException        
    It creates a scrolling drop down list, where rows_visible denotes the number of rows visible in list. 
    And by default multiple selection mode is off.
    
  • public  List(int rows_visible, boolean multiselect) throws HeadlessException        
    It creates a scrolling drop down list where rows_visible denotes the number of rows visible in list 
    and multiselect denotes the multiple selection mode is on or not (true means multiple selection mode 
    is on and false means multiple selection mode is off). 
    
  • public  List(int rows_visible, boolean multiselect) throws HeadlessException        
    It creates a scrolling drop down list where rows_visible denotes the number of rows visible in list 
    and multiselect denotes the multiple selection mode is on or not (true means multiple selection mode 
    is on and false means multiple selection mode is off). 
    

List Methods -

It has several methods but most commonly used are as follows -
  • add() - It is used to add or insert items in list. It has following two versions -
    public void add(String item_name)
    It insert item at the end of scrolling list.
    
    public void add(String item_name, int position)
    It insert the item at the specified index in the list, where item_name is the name of item and position
    is the index at which you want to insert the item. Note index starts from 0.    
    
  • remove() - It is used to remove an item from scrolling list. It has following 2 versions -
    public void remove(String item_name)
    It removes an item specified by item_name from list. If there are multiple item of the same name , 
    it will remove the one which came first in order.
    
    public void remove(int item_index)
    It remove an item specified by item_index from list. Note that index starts from 0.   
    
  • removeAll() - It is used to remove all the items from list. It has the following syntax -
    public void removeAll()
    
  • getItemCount() - It returns the number of items presented in the list. It has the following syntax -
    public int getItemCount()
    
  • getItem() - It is used to get the item presented at a specified position. It has the following syntax -
    public String getItem(int position)
    Where position is index of item you want to get from choice list. Note that index starts from 0.
    
  • getItems() - It returns all the items presented in list as String array. It has the following syntax -
    public String[] getItems()
    
  • replaceItem() - It replace an old item of list with the new specified item. It has the following syntax -
    public void replaceItem(String new_item, int position)
    Where new_item is the new item you want to replace and position specify the index at which you want to replace the item value.
    
  • getSelectedItem() - It is used to get the currently selected item. It has the following syntax -
    public String getSelectedItem()
    
  • getSelectedItems() - If multiple choice option is on, then user can select multiple values, in that case this methods is used to get all currently selected items. It has the following syntax -
    public String[] getSelectedItems()
    
  • getSelectedIndex() - It is used to get the index position of currently selected item. It has the following syntax -
    public int getSelectedIndex()
    
  • getSelectedIndexes() - If multiple choice option is on, then user can select multiple values, in that case this methods is used to get the index position of all currently selected items. It has the following syntax -
    public int[] getSelectedIndexes())
    

Example -

import java.awt.*;
import java.applet.*;
public class Test extends Applet
{
    public void init()
    {
    Label l1 = new Label("Select your Hobbies:-");
    List ls  = new List(3, true);// creates list with 3 rows visible and multiple selection mode on
    ls.add("Playing");
    ls.add("Reading");
    ls.add("Dancing");
    ls.add("Singing");
    ls.add("Travling");

    add(l1);
    add(ls);

    }
}
    

Output -


Scrollbar Control -

It is used to create a scrollbar that provides users an efficient way to select continues range of values. It has the following constructors -
  • public Scrollbar() throws HeadlessException
    It creates a vertical scrollbar.
    
  • public Scrollbar(int Orientation) throws HeadlessException
    It create a scrollbar with specified Orientation, Where Orientation can have one of the following two values - 
    Scrollbar.HORIZONTAL - it is a static integer field that creates a horizontal scrollbar.
    Scrollbar.VERTICAL - It is a static integer field that creates a vertical scrollbar.
    
  • public Scrollbar(int Orientation, int thumb_starting_point, int thumb_size, int min, int max) throws HeadlessException
    It creates a scroll bar with the orientation of scrollbar is passed in Orientation, scrollbar thumb starting 
    point is passed in thumb_starting_point, scrollbar thumb size is passed in  thumb_size and minimum and maximum 
    values of scrollbar are passed in min and max parameters.
    
    To understand these values correctly consider the following figure -

Scrollbar Methods

It has several methods but the most commonly used one are as follows -
  • setValues() - 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 thumb_starting_point, int thumb_size, int min, int max)
    
  • setMinimum() - It is used to set the min value of scrollbar. It has the following syntax -
    public void setMinimum(int new_min)
    Sets the min value of scrollbar to new_min value.
    
  • getMinimum() - It is used to get the current min value of scrollbar. It has the following syntax -
    public int getMinimum()
    
  • setMaximum() - It is used to set the max value of scrollbar. It has the following syntax -
    public void setMaximum(int new_max)
    Sets the min value of scrollbar to new_min value.
    
  • getMaximum() - It is used to get the current max value of scrollbar. It has the following syntax -
    public int getMaximum()
    

Example -

import java.awt.*;
import java.applet.*;
public class Test extends Applet
{
    public void init()
    {
		     setLayout(null);
		     Scrollbar sb1 = new Scrollbar();
		     sb1.setValues(20,10,0,200);
		     Scrollbar sb2 = new Scrollbar(Scrollbar.HORIZONTAL, 20, 10, 0, 20);
 /* parameters meaning - orientation, thumb starting point, thumb size,min value, max value  */
		     sb1.setBounds(10,10,20,200);
		     sb2.setBounds(50,10,200,20);
		     add(sb1);
		     add(sb2);

    }

}
   

Output -


TextArea -

TextArea enables users to input large amount of text (for example a paragraph). It has the following constructors -
  • TextArea() throws HeadlessException         
    It creates a default TextArea with no text within it. By default this TextArea contains scrollbars on both sides 
    i.e. horizontally and vertically.
    
  • TextArea(String text) throws HeadlessException         
    It creates a TextArea with the specified text within it.  By default this TextArea contains scrollbars on both 
    sides i.e. horizontally and vertically.
    
  • TextArea(int rows, int columns) throws HeadlessException         
    It creates an empty TextArea with the specified number of rows and columns. By default this 
    TextArea contains scrollbars on both sides i.e. horizontally and vertically.
    
  • TextArea(String text, int rows, int columns) throws HeadlessException         
    It creates TextArea with the specified text within it and specified number of rows and columns. By default this
    TextArea contains scrollbars on both sides i.e. horizontally and vertically.
    
  • TextArea(String text, int rows, int columns, int scrollbars) throws HeadlessException         
    It creates a TextArea  where text - represents the text displayed in TextArea, rows - represents number of rows 
    of TextArea,columns - represents number of columns of TextArea, scrollbars - represents what scrollbars are
    created to view the TextArea. 
    It can have one of the following values - 
       static int SCROLLBARS_BOTH - Scrollbars both side
       static int SCROLLBARS_HORIZONTAL_ONLY - Only horizontal scrollbar
       static int SCROLLBARS_VERTICAL_ONLY - Only vertical scrollbar
       static int SCROLLBARS_NONE - No scrollbar
    

TextArea Methods -

TextArea is a subclass of TextComponent class, So it support the setText(), getText(), getBackground(), setBackground(), getSelectedText(), isEdiatable(), setEditable() etc methods described in TextField control.
TextArea is also having several methods some most commonly used one are as follows -
  • insert() -It is used to insert the text in TextArea at the specified position. It has the following syntax -
    public void insert(String text, int position)
    Where text - is the text you want to insert in Text Area
    position - is the position at which you want to insert the specified text.
    
  • append() -It append the text with the current text at the last of TextArea. It has the following syntax -
    public void append(String text)
    
  • replaceRange() -It replace the text between the specified range with the new specified text. It has the following syntax -
    public void replaceRange(String new_Text, int start_pos, int end_pos)
    Where new_Text - is the text you want to replace
    start_pos - is the starting position of range and
    end_pos - is the ending position of range.
    Note that the text at end_pos will not be replaced i.e. range will be from start_pos to end_pos - 1.
    
  • setRows() -It is used to set the number of rows of TextArea. It has the following syntax -
    public void setRows(int rows)
    Where rows represents the number of rows. 
    
  • getRows() -It is used to get the current number of rows of TextArea. It has the following syntax -
    public int getRows()
    
  • setColumns() -It is used to set the number of columns of TextArea. It has the following syntax -
    public void setColumns(int columns)
    Where rows represents the number of columns.
    
  • getColumns() -It is used to get the current number of columns of TextArea. It has the following syntax -
    public int getColumns()
    

Example -

import java.awt.*;
import java.applet.*;
public class Text extends Applet
{
    public void init()
    {
        TextArea ta1 = new TextArea(); // Default text area
        TextArea ta2 = new TextArea(5, 7); // TextArea with 5 rows and 7 columns
        TextArea ta3 = new TextArea("This is just a demo", 5, 7, TextArea.SCROLLBARS_VERTICAL_ONLY);
        // TextArea with specified text, 5 rows, 7 columns, and only vertical scrollbar
        add(ta1);
        add(ta2);
        add(ta3);

    }
}
    

Output -