Awt Notes1

Download as pdf or txt
Download as pdf or txt
You are on page 1of 12

Introduction to Java AWT Controls

Java AWT controls are the controls that are used to design graphical user interfaces or web
applications. To make an effective GUI, Java provides java.awt package that supports various
AWT controls like Label, Button, CheckBox, CheckBox Group, List, Text Field, Text Area,
Choice, Canvas, Image, Scrollbar, Dialog, File Dialog, etc that creates or draw various components
on web and manage the GUI based application.

Java AWT (Abstract Window Toolkit) is an API to develop GUI or window-based


applications in java.
Java AWT components are platform-dependent i.e. components are displayed according to the
view of operating system. AWT is heavyweight i.e. its components are using the resources of OS.
The java.awt package provides classes for AWT api such as TextField, Label, TextArea,
RadioButton, CheckBox, Choice, List etc.
Java AWT Hierarchy
The hierarchy of Java AWT classes are given below.

Container
The Container is a component in AWT that can contain another components like buttons,
textfields, labels etc. The classes that extends Container class are known as container such as
Frame, Dialog and Panel.
Window
The window is the container that have no borders and menu bars. You must use frame, dialog or
another window for creating a window.
Panel
The Panel is the container that doesn't contain title bar and menu bars. It can have other
components like button, textfield etc.
Frame
The Frame is the container that contain title bar and can have menu bars. It can have other
components like button, textfield etc.
Useful Methods of Component class
Method Description

public void add(Component c) inserts a component on this component.

public void setSize(int width,int sets the size (width and height) of the
height) component.

public void defines the layout manager for the


setLayout(LayoutManager m) component.

public void setVisible(boolean status) changes the visibility of the component, by


default false.

Java AWT Example


To create simple awt example, you need a frame. There are two ways to create a frame in AWT.
● By extending Frame class (inheritance)
● By creating the object of Frame class (association)
Example: By extending Frame class (inheritance)
import java.awt.*;
class First extends Frame{
First(){
Button b=new Button("click me");
b.setBounds(30,100,80,30);// setting button position
add(b);//adding button into frame
setSize(300,300);//frame size 300 width and 300 height
setLayout(null);//no layout manager
setVisible(true);//now frame will be visible, by default not visible
}
public static void main(String args[]){
First f=new First();
}}

Example: By creating the object of Frame class (association)


import java.awt.*;
class First2{
First2(){
Frame f=new Frame();
Button b=new Button("click me");
b.setBounds(30,50,80,30);
f.add(b);
f.setSize(300,300);
f.setLayout(null);
f.setVisible(true);
}
public static void main(String args[]){
First2 f=new First2();
}}

Java GUI Event Handling


Any program that uses GUI (graphical user interface) such as Java application written for
windows, is event driven. Event describes the change in state of any object. For Example
: Pressing a button, Entering a character in Textbox, Clicking or Dragging a mouse, etc.

Components of Event Handling


Event handling has three main components,
● Events : An event is a change in state of an object.
● Events Source : Event source is an object that generates an event.
● Listeners : A listener is an object that listens to the event. A listener gets notified
when an event occurs
How Events are handled?
● A source generates an Event and send it to one or more listeners registered with
the source. Once event is received by the listener, they process the event and
then return. Events are supported by a number of Java packages,
like java.util, java.awt and java.awt.event.
Java Event classes and Listener interfaces

Event Classes Description Listener Interface

ActionEvent generated when button is pressed, menu-item is ActionListener


selected, list-item is double clicked

MouseEvent generated when mouse is dragged, MouseListener


moved,clicked,pressed or released and also when
it enters or exit a component

KeyEvent generated when input is received from keyboard KeyListener

ItemEvent generated when check-box or list item is clicked ItemListener

TextEvent generated when value of textarea or textfield is TextListener


changed

MouseWheelE generated when mouse wheel is moved MouseWheelListener


vent

WindowEvent generated when window is activated, deactivated, WindowListener


deiconified, iconified, opened or closed

ComponentEv generated when component is hidden, moved, ComponentEventListener


ent resized or set visible

ContainerEve generated when component is added or removed ContainerListener


nt from container

AdjustmentEv generated when scroll bar is manipulated AdjustmentListener


ent

FocusEvent generated when component gains or loses FocusListener


keyboard focus

Steps to perform Event Handling

Steps to handle events:


● Implement appropriate interface in the class.
● Register the component with the listener.
Registration Methods
For registering the component with the Listener, many classes provide the registration methods.
For example:
● Button
● public void addActionListener(ActionListener a){}
● MenuItem
● public void addActionListener(ActionListener a){}
● TextField
● public void addActionListener(ActionListener a){}
● public void addTextListener(TextListener a){}
● TextArea
● public void addTextListener(TextListener a){}
● Checkbox
● public void addItemListener(ItemListener a){}
● Choice
● public void addItemListener(ItemListener a){}
● List
● public void addActionListener(ActionListener a){}
● public void addItemListener(ItemListener a){}
import java.awt.*;
import java.awt.event.*;
import java.applet.*;
import java.applet.*;
import java.awt.event.*;
import java.awt.*;

public class Test extends Applet implements KeyListener


{ String msg="";
public void init()
{ addKeyListener(this);}
public void keyPressed(KeyEvent k)
{ showStatus("KeyPressed"); }
public void keyReleased(KeyEvent k)
{ showStatus("KeyRealesed"); }
public void keyTyped(KeyEvent k)
{ msg = msg+k.getKeyChar();
repaint(); }
public void paint(Graphics g)
{ g.drawString(msg, 20, 40);
}}

Example:: Java event handling by implementing ActionListener


import java.awt.*;
import java.awt.event.*;
class AEvent extends Frame implements ActionListener{
TextField tf;
AEvent(){
//create components
tf=new TextField();
tf.setBounds(60,50,170,20);
Button b=new Button("click me");
b.setBounds(100,120,80,30);
//register listener
b.addActionListener(this);//passing current instance
//add components and set size, layout and visibility
add(b);add(tf);
setSize(300,300);
setLayout(null);
setVisible(true); }
public void actionPerformed(ActionEvent e){
tf.setText("Welcome"); }
public static void main(String args[]){
new AEvent(); } }
public void setBounds(int xaxis, int yaxis, int width, int height); have been used in the above
example that sets the position of the component it may be button, textfield etc.
AWT Controls
Java AWT Button
The button class is used to create a labeled button that has platform independent implementation.
The application result in some action when the button is pushed.
• Constructors
– Button()
-Button(String buttonLabel)
• The button size (preferred size) is based on the height and width of the label in the current font,
plus some extra space determined by the OS
• Useful Methods
– getLabel/setLabel
• Retrieves or sets the current label
Handling Button Events
• Attach an ActionListener to the Button and handle the event in actionPerformed
Java AWT Checkbox
The Checkbox class is used to create a checkbox. It is used to turn an option on (true) or off
(false). Clicking on a Checkbox changes its state from "on" to "off" or from "off" to "on".
• Constructors – These three constructors apply to checkboxes that operate independently of
each other (i.e., not radio buttons)
● Checkbox()
• Creates an initially unchecked checkbox with no label
● Checkbox(String checkboxLabel)
• Creates a checkbox (initially unchecked) with the specified label; see setState for changing it
● Checkbox(String checkboxLabel, boolean state)
• Creates a checkbox with the specified label – The initial state is determined by the boolean
value provided
– A value of true means it is checked
Checkbox methods
• getState/setState
– Retrieves or sets the state of the checkbox: checked (true) or unchecked (false)
• getLabel/setLabel
– Retrieves or sets the label of the checkbox
Handling Checkbox Events
• Attach an ItemListener
–Add it with addItemListener and process the ItemEvent in itemStateChanged
public void itemStateChanged(ItemEvent event) { ... }
• The ItemEvent class has a getItem method which returns the item just selected or deselected •
The return value of getItem is an Object so you should cast it to a String before using it
import java.awt.*;
import java.awt.event.*;
public class CheckboxExample
{
CheckboxExample(){
Frame f= new Frame("CheckBox Example");
final Label label = new Label();
label.setAlignment(Label.CENTER);
label.setSize(400,100);
Checkbox checkbox1 = new Checkbox("C++");
checkbox1.setBounds(100,100, 50,50);
Checkbox checkbox2 = new Checkbox("Java");
checkbox2.setBounds(100,150, 50,50);
f.add(checkbox1); f.add(checkbox2); f.add(label);
checkbox1.addItemListener(new ItemListener() {
public void itemStateChanged(ItemEvent e) {
label.setText("C++ Checkbox: "
+ (e.getStateChange()==1?"checked":"unchecked"));
} });
checkbox2.addItemListener(new ItemListener() {
public void itemStateChanged(ItemEvent e) {
label.setText("Java Checkbox: "
+ (e.getStateChange()==1?"checked":"unchecked"));
} });
f.setSize(400,400);
f.setLayout(null);
f.setVisible(true); }
public static void main(String args[])
{ new CheckboxExample();
} }
Java AWT CheckboxGroup
The object of CheckboxGroup class is used to group together a set of Checkbox. At a time only
one check box button is allowed to be in "on" state and remaining check box button in "off"
state. It inherits the object class.
● CheckboxGroup Constructors
CheckboxGroup()
• Creates a non-graphical object used as a “tag” to group checkboxes logically together
• Checkboxes with the same tag will look and act like radio buttons
• Only one checkbox associated with a particular tag can be selected at any given time
● Checkbox Constructors
– Checkbox(String label, CheckboxGroup group, boolean state)
• Creates a radio button associated with the specified group, with the given label and initial state
• If you specify an initial state of true for more than one Checkbox in a group, the last one will be
shown selected
Other Methods for Radio Buttons

• CheckboxGroup
– getSelectedCheckbox
• Returns the radio button (Checkbox) that is currently selected or null if none is selected
• Checkbox
– In addition to the general methods described in Checkboxes, Checkbox has the following two
methods specific to CheckboxGroup’s:
– getCheckboxGroup/setCheckboxGroup
• Determines or registers the group associated with the radio button
Note: Event-handling is the same as with Checkboxes:
import java.applet.Applet;
import java.awt.*;
public class CheckboxGroups extends Applet
{
public void init()
{ setLayout(new GridLayout(4, 2));
setBackground(Color.LIGHT_GRAY);
setFont(new Font("Serif", Font.BOLD, 16));
add(new Label("Flavor", Label.CENTER));
add(new Label("Toppings", Label.CENTER));
CheckboxGroup flavorGroup = new CheckboxGroup();
add(new Checkbox("Vanilla", flavorGroup, true));
add(new Checkbox("Colored Sprinkles"));
add(new Checkbox("Chocolate", flavorGroup, false));
add(new Checkbox("Cashews"));
add(new Checkbox("Strawberry", flavorGroup, false));
add(new Checkbox("Kiwi")); } }
Java AWT List
The object of List class represents a list of text items. By the help of list, user can choose either
one item or multiple items. It inherits Component class.
• Constructors
● List(int rows, boolean multiSelectable)
• Creates a listbox with the specified number of visible rows (not items)
• Depending on the number of item in the list (addItem or add), a scrollbar is automatically
created
• The second argument determines if the List is multi selectable
• The preferred width is set to a platform-dependent value, and is
typically not directly related to the width of the widest entry
● List()
• Creates a single-selectable list box with a platform-dependent number of rows and a platform-
dependent width
● List(int rows)
• Creates a single-selectable list box with the specified number of rows and a platform-dependent
width
Other List Methods
• add
– Add an item at the end or specified position in the list box
– All items at that index or later get moved down
• isMultipleMode
– Determines if the list is multiple selectable (true) or single
selectable (false)
• remove/removeAll
– Remove an item or all items from the list
• getSelectedIndex
– For a single-selectable list, this returns the index of the selected item
– Returns –1 if nothing is selected or if the list permits multiple selections
• getSelectedIndexes
– Returns an array of the indexes of all selected items
• Works for single- or multi-selectable lists
• If no items are selected, a zero-length (but non-null) array is returned
• getSelectedItem
– For a single-selectable list, this returns the label of the selected item
– Returns null if nothing is selected or if the list permits multiple selections
• getSelectedItems
– Returns an array of all selected items
– Works for single- or multi-selectable lists
• If no items are selected, a zero-length (but non-null) array is returned
• select
– Programmatically selects the item in the list
– If the list does not permit multiple selections, then the previously selected item, if any, is also
deselected
Handling List Events
• addItemListener/removeItemListener
– ItemEvents are generated whenever an item is selected or deselected (single-click)
– Handle ItemEvents in itemStateChanged
• addActionListener/removeActionListener
– ActionEvents are generated whenever an item is doubleclicked or RETURN (ENTER) is
pressed while selected
– Handle ActionEvents in actionPerformed

Labels
Label is an object of type Label. It contains a string, which it displays. Labels are passive
controls that do not support any interaction with the user.
Constructors
● Label() //creates blank label
● Label(String str) //creates a label that contains the string specified by str
● Label(String str,int how) // creates a label that contains the string specified by str
And uses the alignment
how must be one of three constants:Label.LEFT,Label.RIGHT,Label.CENTER

Methods
setText() //set or change a text
getText()//obtain the current label

Scroll Bars
Scroll bar are used to select continues 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. Scrollbar control represents a scroll bar component in order to enable
user to select from range of values.
Constructors:
Scrollbar() //Constructs a new vertical scroll bar.
Scrollbar(int orientation) //Constructs a new scroll bar with the specified orientation
Scrollbar(int orientation, int value, int visible, int minimum, int maximum) //Constructs a new
scroll bar with the specified orientation, initial value, visible amount, and minimum and
maximum values.
Methods :
public addAdjustmentListener(AdjustmentListener al) // Adds an AdjustmentListener.
public int getValue() // Gets the Scrollbar's current position value.
public int setValue(int value)// Sets the Scrollbar's current position value
TextField
The textField component allows the user to edit single line of text.When the user types a key
in the text field the event is sent to the TextField. The key event may be key pressed, Key released
or key typed. The key event is passed to the registered KeyListener. It is also possible to for an
ActionEvent if the ActionEvent is enabled on the textfield then ActionEvent may be fired by
pressing the return key.
Constructors:
TextField() //Constructs a new text field.
TextField(int columns) //Constructs a new empty text field with the specified number of
columns.
TextField(String text)// Constructs a new text field initialized with the specified text.
Methods
String getText() // obtain the string currently contained in the textfield
void setText(String str) //to set the text
import java.awt.*;
class TextFieldExample{
public static void main(String args[]){
Frame f= new Frame("TextField Example");
TextField t1,t2;
t1=new TextField("Welcome to Javatpoint.");
t1.setBounds(50,100, 200,30);
t2=new TextField("AWT Tutorial");
t2.setBounds(50,150, 200,30);
f.add(t1); f.add(t2);
f.setSize(400,400);
f.setLayout(null);
f.setVisible(true); } }
TextArea
The TextArea control in AWT provide us multiline editor area. The user can type here
as much as he wants. When the text in the text area become larger than the viewable area the
scroll bar is automatically appears which help us to scroll the text up & down and right & left
Constructors:
● TextArea()
Constructs a new text area with the empty string as text.
● TextArea(int rows, int columns)
Constructs a new text area with the specified number of rows and columns and the empty string
as text.
● TextArea(String text)
Constructs a new text area with the specified text.
● TextArea(String text, int rows, int columns)
Constructs a new text area with the specified text, and with the specified number of rows and
columns.
● TextArea(String text, int rows, int columns, int scrollbars)
Constructs a new text area with the specified text, and with the rows, columns, and scroll bar
visibility as specified.

You might also like