Unit 2 Java AWT
Unit 2 Java AWT
Strings, which are widely used in Java programming, are a sequence of characters. In Java
programming language, strings are treated as objects. The Java platform provides the String
class to create and manipulate strings.
String – Object or Primitive?
Strings could be considered a primitive type in Java, but in fact they are not. As a String is
actually made up of an array of char primitives.
String objects are immutable- That means once a string object is created it cannot be
altered. For mutable string, you can use StringBuffer and StringBuilder classes. [
An object whose state cannot be changed after it is created is known as an Immutable
object. String, Integer, Byte, Short, Float, Double and all other wrapper class's objects are
immutable.]
Creating String object: There are two ways to create String object:
1. By string literal For Example: String s="welcome";
2. By new keyword For Example: String s=new String("Welcome");
Java String Example
Applet
An applet is a program written in the Java programming language that can be an HTML.
page, much in the same way an image is included in a page.
Types of Applets:
Local Applet
It is written on its own and then embedded into the web pages. It is developed locally and
is stored in the local system/machine. In the local applet, a web page doesn’t get the
information from the internet, instead, it is specified by the local pathname or filename. In
java applet, there are two attributes specifically used in defining an applet. The first
attribute is the codebase which specifies the path name and the second attribute is the
code that defines the file name that contains the applet code.
Remote Applet
It is developed and designed by developer another developer and not the java team. It
resides on a remote computer that is connected to the internet. For running the applet
which is stored in remote computer, the system must be connected to the internet for able
to download and run the applet program. The remote applet can be loaded only if the
address of applet is known on the web which is also known as URL (Uniform Resource
Locator).
A Java applet is an applet delivered in the form of Java byte code. Java applets can run A
Java applet can run in a web browser using a Java Virtual Machine (JVM), or in Sun's Applet
Viewer, a standalone tool to test applets.
Features of Applet
Applets are inherently graphical in nature and tend to contain controls such as buttons,text
fields and list boxes.
It can perform various task such as:
1) Play audio clips, images, and animations
2) Connect to a database on the Web server from which the applet was downloaded.
3) Communicate with the Web server by using sockets
4) Communicate with a Java application running on the Web server.
5) May use Common Object Request Broker Architecture (CORBA) to communicate with
Java or non-Java applications on the Web server.
Life Cycle of Applet
Basically, there are five methods in the Applet class on which any applet is built.
1) init(): Subclasses may override these methods to accomplish certain tasks at certain
times. It is called exactly once when the applet starts up. The web browser can invoke them
when it needs to without knowing in advance whether the method is implemented in the
superclass or the subclass.
2) start(): This method is automatically called after the browser calls the init method. It is
also called whenever the user returns to the page containing the applet after having gone
off to other pages.
3) stop(): This method is automatically called when the user moves off the page on which
the applet sits. It can, therefore, be called repeatedly in the same applet.
4) destroy(): This method is only called when the browser shuts down normally Because
applets are meant to live on an HTML page, one should not normally leave resources
behind after a user leaves the page that contains the applet.
Applet Code:
Java AWT
• Java AWT (Abstract Windowing Toolkit) is an API to develop GUI or window-based
application 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 uses the resources of system.
The java.awt package provides classes for AWT API such as TextField, Label, TextArea,
RadioButton, CheckBox, Choice, List etc.
In java everything is exist in the form of class and object so every components has a class
and if we want to use the particular components in our GUI application we only need to
create the object of class and the component will be added in the application .one object
creation will be responsible to create one instance of the component.
Java AWT Hierarchy
Object: The Object class is the top most class and parent of all the classes in java by default.
Every class in java is directly or indirectly derived from the object class.
Component: Component class is at the top of AWT hierarchy. It is an abstract class that
encapsulates all the attributes of visual component.
A component object is responsible for remembering the current foreground and
background colors and the currently selected text font.
Container: The Container is also the component that contains another components like
button , label ,list etc. in itself.
The classes that extends Container class are known as container such as Frame, Dialog and
Panel.
Panel: Panel class is a concrete subclass of Container. It does not contain title bar, menu bar
or border. Panel is a container that can only holds other components like button, text field
etc.
Frame: Frame is subclass of Window Class. It is a container that contain several different
components like button, title bar, textfield, label etc. In Java, most of the AWT applications
are created using Frame window. Frames can be resize accordingly.
Creating a Frame
There are two ways to create a Frame. They are,
When we create a frame (either by instantiating or extending Frame class), there are two
attributes that are must for visibility of the frame:
2. setVisible(true);
When we create other components like Buttons, TextFields, etc. Then we need to add it to
the frame by using the method - add(Component's Object);
We can add the following method also for resizing the frame –
setResizable(true);
1. By Instantiating Frame class
Frames can be created by creating the object of the frame class inside the class that we
have created.
import java.awt.*;
public class awtFrame
{
awtFrame()
{
Frame fm=new Frame("java programming"); //Creating a frame
Label lb = new Label("welcome to java graphics"); //Creating a label
fm.add(lb); //adding label to the frame
fm.setSize(300, 300); //setting frame size.
fm.setVisible(true); //set frame visibilty true
}
public static void main(String args[])
{
awtFrame t = new awtFrame();
}
}
In the above program we have created a class awtFrame in which only the object of the
frame has created. To set the size of the frame visible the size of the frame is set by
setSize() method and to make it visible setVisible(true) method is used.
2. By extending Frame class
import java.awt.*;
import java.awt.event.*;
public class TestAwt1 extends Frame
{
public TestAwt1()
{
Button btn=new Button("Click here");
add(btn); //adding a new Button.
setSize(400, 500); //setting size.
setTitle("this is a frame"); //setting title.
setLayout(new FlowLayout()); //set default layout for frame.
setVisible(true); //set frame visibilty true.
}
public static void main (String[] args)
{
TestAwt1 ta = new TestAwt1(); //creating a frame.
}
}
AWT Button: In Java, AWT contains a Button Class. It is used for creating a labelled button
which can perform an action.
import java.awt.*;
public class ButtonDemo1
{
public static void main(String[] args)
{
Frame f1=new Frame(" Frame is designed for Button Demo");
Button b1=new Button("Press Here");
Button b2= new Button("Login");
b1.setBounds(100,200,80,50);
b2.setBounds(140, 250, 50, 50);
f1.add(b2);
f1.add(b1);
f1.setSize(500,500);
f1.setLayout(null);
f1.setVisible(true);
}
}
AWT Label: Labels are created using the Label class. Labels are often used to identify the
purpose of other components on a given interface ;they cannot be edited directly by the
user.
Constructors:
1) Label(): It creates a label with its string aligned to the left.
2) Label(String): It creates a label initialized with the given string, and aligned left.
3) Label(String, int): It creates a label with specified text and alignment indicated by the int
argument: Label.Right, Label.Left and Label.Center
import java.awt.*;
class LabelDemo1
{
public static void main(String args[])
{
Frame l_Frame= new Frame("Label Demo");
Label lab1,lab2;
lab1=new Label("Welcome to the world of ");
lab1.setBounds(50,50,200,30);
lab2=new Label("Java Programming");
lab2.setBounds(50,100,200,30);
l_Frame.add(lab1);
l_Frame.add(lab2);
l_Frame.setSize(500,500);
l_Frame.setLayout(null);
l_Frame.setVisible(true);
}
}
AWT Choice(ComboBox): In Java, AWT contains a Choice Class. It is used for creating a
drop-down menu of choices. When a user selects a particular item from the drop-down
then it is shown on the top of the menu.
Choice Declaration:
import java.awt.*;
public class ChoiceDemo
{
ChoiceDemo()
{
Frame choice_f= new Frame("Frame is used to contain Combo box");
Choice obj=new Choice();
obj.setBounds(80,80, 100,100);
obj.add("Red");
obj.add("Blue");
obj.add("Black");
obj.add("Pink");
obj.add("White");
obj.add("Green");
choice_f.add(obj);
choice_f.setSize(400,400);
choice_f.setLayout(null);
choice_f.setVisible(true);
}
public static void main(String args[])
{
new ChoiceDemo();
}
}
AWT List: The 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.
ListDeclaration:
public class List extends Component implements ItemSelectable, Accessible
Constructors:
List()
List(int numRows)
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 (other can be scrolled into view as needed).
import java.awt.*;
public class ListDemo
{
ListDemo()
{
Frame list_f= new Frame("Frame to show Days of the Week");
List obj=new List(7);
obj.setBounds(80,80, 100,100);
obj.add("Sunday");
obj.add("Monday");
obj.add("Tuesday");
obj.add("Wednesday");
obj.add("Thursday");
obj.add("Friday");
obj.add("Saturday");
list_f.add(obj);
list_f.setSize(400,400);
list_f.setLayout(null);
list_f.setVisible(true);
}
public static void main(String args[])
{
new ListDemo();
}
}
AWT Menu Bar: A Menu Bar is a set of option that allows to the user to choose from any
one of the several options. One can add AWT menus to Frame class windows using three
AWT classes:
Constructor :
MenuBar()
2. Menu: After adding the menu bar to a frame window , one can add menus ,such as
file menu and help menu ,this can be done using the Menu class.
Menu declaration:
Constructor:
Menu()
Menu(String label)
Menu(String label, Boolean tearOff()
3. MenuItem: It is used to add the menu items such as New, Open and Save etc.
MenuItem declaration:
Constructors:
MenuItem()
MenuItem(String label)
MenuItem(String label, MenuShortcut s)
import java.awt.*;
class MenuDemo1
{
MenuDemo1()
{
Frame menu_f= new Frame("Menu and MenuItem Demo");
MenuBar menu_bar=new MenuBar();
Menu menu11=new Menu("Menu");
Menu sub_menu1=new Menu("Sub Menu ");
MenuItem a1=new MenuItem("Red");
MenuItem a2=new MenuItem("Light Red");
MenuItem a3=new MenuItem("Drak Red");
MenuItem b1=new MenuItem("Green");
MenuItem b2=new MenuItem("Light Green");
MenuItem b3=new MenuItem("Dark Green");
menu11.add(a1);
sub_menu1.add(a2);
sub_menu1.add(a3);
menu11.add(b1);
sub_menu1.add(b2);
sub_menu1.add(b3);
menu11.add(sub_menu1);
menu_bar.add(menu11);
menu_f.setMenuBar(menu_bar);
menu_f.setSize(400,400);
menu_f.setLayout(null);
menu_f.setVisible(true);
}
public static void main(String args[])
{
MenuDemo1 d=new MenuDemo1();
}
}
Layout Manager
Layouts tell Java where to put components in containers (Panel, content pane, etc). Every
panel (and other container) has a default layout, but it's better to set the layout explicitly
for clarity.
In Java, Layout Managers is used for arranging the components in order. LayoutMananger is
an interface which implements the classes of the layout manager.
These are some of the class which are used for the representation of layout manager.
1. java.awt.BorderLayout
2. java.awt.FlowLayout
3. java.awt.GridLayout
4. java.awt.CardLayout
Border Layout
BorderLayout is used, when we want to arrange the components in five regions. The five
regions can be north, south, east, west and the centre. There are 5 types of constructor in
Border Layout. They are as following:
import java.awt.*;
public class Border
{
Frame frame;
Border()
{
frame=new Frame();
frame.add(box1,BorderLayout.NORTH);
frame.add(box2,BorderLayout.SOUTH);
frame.add(box3,BorderLayout.EAST);
frame.add(box4,BorderLayout.WEST);
frame.add(box5,BorderLayout.CENTER);
frame.setSize(400,400);
frame.setVisible(true);
}
public static void main(String[] args)
{
new Border();
}
}
Output:
Grid Layout
Grid Layout is used, when we want to arrange the components in a rectangular grid.There
are 3 types of constructor in Grid Layout. They are as following:
1. GridLayout()
2. GridLayout(int rows, int columns)
3. GridLayout(int rows, int columns, inthgap, int vgap)
import java.awt.*;
public class Grid{
Frame frame1;
Grid(){
frame1=new Frame();
frame1.add(box1);
frame1.add(box2);
frame1.add(box3);
frame1.add(box4);
frame1.add(box5);
frame1.add(box6);
frame1.add(box7);
frame1.add(box8);
frame1.add(box9);
frame1.setLayout(new GridLayout(3,3));
frame1.setSize(500,500);
frame1.setVisible(true);
}
public static void main(String[] args) {
new Grid();
}
}
Output:
Flow Layout
Flow Layout is used, when we want to arrange the components in a sequence one after
another.
There are 3 types of constructor in the Flow Layout. They are as following:
1. FlowLayout()
2. FlowLayout(int align)
3. FlowLayout(int align, inthgap, intvgap)
import java.awt.*;
public class Flow{
Frame frame1;
Flow(){
frame1=new Frame();
frame1.add(box1);
frame1.add(box2);
frame1.add(box3);
frame1.add(box4);
frame1.add(box5);
frame1.add(box6);
frame1.add(box7);
frame1.add(box8);
frame1.add(box9);
frame1.add(box10);
frame1.setLayout(new FlowLayout(FlowLayout.LEFT));
frame1.setSize(400,400);
frame1.setVisible(true);
}
public static void main(String[] args) {
new Flow();
}
}
Output:
Event Handling
Event handling in Java is the procedure that controls an event and performs appropriate
action if it occurs. The code or set of instructions used to implement it is known as
the Event handler.
It consists of two major components:
The event source and
The event listener.
The source is the object where the event occurs, and the event listener is responsible for
taking appropriate actions when an event occurs. These Listeners must be registered with
the source object in order for the listener to receive event notifications.
Events in Java
Events in java represent the change in the state of any object. Events occur when the user
interacts with the interface. Clicking a button, moving the mouse, typing a character,
selecting an item from a list, and scrolling the page are all examples of behaviors that cause
an event to occur.
Types of Events in Java:
Foreground Events: These events necessitate the user's direct participation. They are
produced as a result of a user interacting with graphical components in a Graphical User
Interface.
Background Events: Background events are those that require end-user interaction.
Operating system interrupts and hardware or software failures are examples of background
events.
b.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e) {
int a = Integer.parseInt(tf1.getText());
int b = Integer.parseInt(tf2.getText());
int c = a + b;
l1.setText("Their sum is = " + String.valueOf(c));
}
});
}
public static void main(String []args) {
new AWTEvent();
}
}
Output: