Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 36

UNIT-V

GUI
GUI stands for Graphical User Interface, a term used not only in Java but in all programming
languages that support the development of GUIs. A program's graphical user interface presents
an easy-to-use visual display to the user. It is made up of graphical components (e.g., buttons,
labels, windows) through which the user can interact with the page or application.

What is an Applet?
An applet is a Java program that is embedded inside a web page.
Applets are used to make the web page more dynamic.
An applet is run and managed in a browser using the Java Plug-in software.

Difference between an Application and an Applet


There are two types of Java programs.

Application:
An application is a standalone java program that can run alone on a JVM.
It has a main method that is the execution point of the program.
It is compiled using a javac command and run using a java command.
It can run on a local machine and access the resources in that machine.

Applet:
An applet is a java program that is embedded inside a web page like an image inserted in a
HTML page.
It also needs a JVM to run, which is added to the client's
browser. It exists if the focus is on that web page.
Unlike an application it does not have a main method but has an init() method.
Applet is executed in a restricted environment and cannot access any of the client's resources.
A java applet extends the java.applet.Applet class.

Both applet and application can use all the classes that are defined by Sun's Java API.

Life Cycle of an Applet


As mentioned above an applet does not have a main method like a regular java application.
But an applet has a lifecycle events it follows when it gets loaded.

An applet can initialize itself.


An applet can start running itself.
An applet can stop running itself.
An applet can do the cleanup required after stopping itself.

Pretty efficient isn't it? Let's learn more in detail.


When an applet gets loaded on a web page, we see a message loading...initializing appear, this is
when an instance of a subclass of the java.Applet class is created. This class gets initialized and
starts running.
What happens when an Applet is running?
When the user moves to another page, the browser destroys this applet. When the focus is back
the applet is again created and initialized. So, a state is never stored for an applet.
When the user refreshes or reloads the page, the current applet is destroyed, and a new instance
is created and initialized.
When the user quits the browser, applet now has a chance to stop itself and do a cleanup.

Life Cycle Methods


An applet runs inside an embedded page which is controlled by a software such as a
browser or an applet viewer. This software controls the applet by calling the
applet's life cycle methods as and when required.

init() method :

This method is called when the applet is created for the first time and loaded.
The init() method generally performs task like creating the initial user
interface, setting the background color, the font of the string to be displayed
etc.

start() method :

This method is called when a user views the applet. Generally, applets are
used for animations. When the user focus is on the applet, this method starts
the display or sounds are played.There can be more than one thread that can
be working on a single applet.

stop() method :

This method is called when a user leaves the web page or the web page is no
longer in focus. This does not remove the applet, but the ongoing task done by
the applet is stopped.

destroy() method :

The destroy() method is called when the browser is exited or closed. This is
when the cleanup of resources happens. All the threads executing are stopped.
Types of Applet
Applet types are based on the location they are executed. Hence, we have two types of
applets.

Local Applets :

These are stored in the same system and when a web page should load a
specific applet, it will pick from the local system by using the path and file
name.
Remote Applets :

These Applets are stored in some remote location and when a client browser
wants to load the applet, it will pick from that location on the web with the
help of internet and load it inside the web browser. The web page should have
the URL and parameters necessary to find the applet from the remote location.

Create an Applet
Now as we have a brief understanding of what Applets are, let us understand how to build an
Applet.

The steps involved in developing a simple applet are


1. Import the java.applet.Applet & java.awt.Graphics classes.
2. An applet is created by extending java.applet.Applet class.
3. We override the paint method which takes an Graphics class object as parameter.
4. In the paint method ,we write a simple code that draws this applet by calling the
drawString() method on the graphics object.
5. The arguments for the drawString method are the text to be displayed and length and width
in which the text inside the applet is to be displayed.
First Applet Program
1. import java.applet.Applet;
2. import java.awt.Graphics;
3.
4. public class FirstApplet extends Applet { public void
5. paint(Graphics g){
6. g.drawString("First Applet", 20 ,100);
This Java program is compiled and the FirstApplet.class file is used to run the applet.

Note: An applet class is always declared public as the applet runs in an external
environment and declaring it public gives the external application be able to run it.

Run an Applet
Now we have developed an applet, lets run it. To run an applet, we need a simple
HTML file that has an APPLET tag as below.

1. <HTML>
2. <BODY>
3. <APPLET CODE=FirstApplet.class WIDTH=200 HEIGHT=200 >
4. </APPLET>
5. </BODY>
6. </HTML>
Note: To run an applet written with Java 2 APIs in a browser, the browser must be
enabled for the Java 2 Platform or we must use an Applet Viewer.
Passing Parameters to Applets
In the previous example FirstApplet, we have hardcoded the message "First Applet"
inside the g.drawString() method. But this message can be dynamic and passed as
a parameter from the embedded web page.
To pass a parameter from a HTML page to an applet, the <PARAM> tag is used inside
the applet tag and our applet program can read the parameter and display the message in
the applet.
To achieve this we need to tweak our applet program and HTML program a little.

1. import java.applet.Applet;
2. import java.awt.Graphics;
3. public class SecondApplet extends Applet {
4. String defaultName = "First Applet";
5. public void paint (Graphics g) {
6. String param = this.getParameter("Message");
7. if (param == null)
8. param = defaultName;
9. g.drawString(param1, 20, 100);
10. }
11. }

1. <HTML>
2. <BODY>
3. <APPLET CODE=SecondApplet.class WIDTH=200 HEIGHT=200 >
4. <PARAM name="Message" value="CodeTantra Applet!">
5. </PARAM>
6. </APPLET>
7. </BODY>
8. </HTML>

So, what happened above can be explained as


The HTML file has a <PARAM> Tag added with name and value attributes inside
the <APPLET> Tag.
The applet has a defaultName declared which can be used in case of null parameter.
The paint method gets the param by using the getParameter("Message") and sets it to a
String. A check is done if the parameter received is not null, if null the default message is
assigned.
The g.drawString() method takes the message as one of its argument to display the message.

An applet can have more than one PARAM. It can ignore the PARAMs it does not need and use
only those required.
Events and Event Handling
Event :

An Event can be defined as an action that has occurred when a user does something
like a click of a button, entering some data in an input field, checkbox, selecting an
item from a list of items.

Event Source :
An Event Source is the Object of the class where an event occurred. This has all the
information related to the event that occurred which can be passed on to the listener classes.

Event Listener :
To handle events, the program must listen if these events are happening. When an event
occurs, it must invoke the specific action. These listening programs are called Event
Listeners.
When an event occurs, a program should register itself as listening to such event by
implementing the necessary listener interface. It should implement the method of that interface
that provides the event handling.
A program can implement more than one interface i.e. it can listen to many events.

Delegation Event Model


The Delegation Event Model is also known as the 1.1 event model. In this model, a
source generates an event and sends it to one or more listeners that have registered to handle this
event. The listener waits for an event to be generated. Once generated, the listener processes the
event and then returns. This event model makes event handling very efficient and makes the code
more modular by separating the GUI(Graphical User Interface) with the Application code that
handles events.
A few features of delegation event model are
 Here the Listener classes register to the events.
 The events that have the listeners registered will only be handled.
 Every event type has its own Event class.
 Every type of Listener has a separate class.

Any click on a source like a button generates an event. This event object is of
class ActionEvent.
This button must call its method addActionListener() to register any Listener class that wants to
handle this click of button event.

A class that handles the above click of button event must register as an object to the
source addActionListener() method. It must implement ActionListener interface

Types of Events in EventObject class


Any interaction with the Graphical user interface creates events of type EventObject class
which is the super class of all event classes. A few of the event classes described in the
java.awt.event are
ActionEvent
MouseEvent
TextEvent
ItemEvent
KeyEvent
WindowEvent
AdjustmentEvent

The corresponding Listener classes for the events are as below


Event Listener

ActionEvent ActionListener

MouseEvent MouseListener

TextEvent TextListener

ItemEvent ItemListener

KeyEvent KeyListener

WindowEvent WindowListener

KeyEvent and KeyListener


As we go forward we shall be using the delegation event model mentioned above. Let
us work now on how mouse and keyboard events are handled. We shall be learning
about the event classes that are generated and the important methods on it. We shall also
be looking at the corresponding listener interfaces and the methods that need to be
implemented for those interfaces.
KeyEvent :

An object of KeyEvent class is generated when any keystrokes occur at source when
a key is pressed on the keyboard in the text field or textarea.
The important methods of this class are
public char getKeyChar() : Returns the character entered.
public int getKeyCode() : Returns the code of the character entered.
public boolean isActionKey() : Returns a Boolean value true if the key pressed is not a
character but is one of the arrow keys or any of the function keys etc.
public void addItemListener(ItemListener il) : This method is to be called by the source of the
event such as text field to add the listener to the field. This listener must implement the
KeyListener interface.
KeyListener :

Any class that implements the KeyListener interface to handle key events have to
implement the below methods.
public void keyPressed(KeyEvent ke) : This method is invoked when a key is pressed.
public void keyReleased(KeyEvent ke) : This method is invoked when a key is released.
public void keyTyped(KeyEvent ke) : This method is invoked when a character is returned
when the key is pressed.

Below is a simple program that shows how the KeyEvent and KeyListener work.
1. package com.ct.applet;
2.
3. import java.applet.Applet; import java.awt.Color; import java.awt.Graphics; import java.awt.Tex
4. import java.awt.event.KeyEvent; import java.awt.event.KeyListener;
5.
6.
7.
8.
9.
10. public class KeyApplet extends Applet implements KeyListener {
11. TextField tf1; public void init() {
12. tf1 = new TextField(10); add(tf1); tf1.addKeyListener(this);
13.
14.
15.
16.
17. }
18.
19. public void keyPressed(KeyEvent e) { System.out.println("Key Pressed");
20. }
21.
22. public void keyReleased(KeyEvent e) { System.out.println("Key Released");
23.
24. }
25.
26. public void keyTyped(KeyEvent e) { char c = e.getKeyChar();
27. System.out.println("Key Is " + c);
28. if (c != KeyEvent.CHAR_UNDEFINED) { repaint();
29. }
30. }
31.
32. public void paint(Graphics g) {
33.
34.
35.
36.
37. g.setColor(Color.gray);
38. g.drawString("In paint method", 100, 50);
39. }
40. }

KeyApplet class output

MouseEvent and MouseListener


MouseEvent :
An event of type MouseEvent class occurs in the source when
A mouse cursor enters the source.
A mouse cursor exits the source.
A button on the mouse is pressed.
A button on the mouse is released.

The methods of the MouseEvent class are


public int getX() : This method returns the x coordinate of the mouse event.
public int getY() : This method returns the y coordinate of the mouse event.
public void addMouseListener(ItemListener il) : This method is called by the source when it
has to register the listener class that handles the event.

MouseListener :

Any class that implements the MouseListener interface to handle mouse events that
are generated on the source, has to override and implement below given methods.
public void mouseEntered(MouseEvent me) : To be invoked when the mouse cursor comes
inside the source.
public void mouseExited(MouseEvent me) : To be invoked when the mouse cursor exits the
source.
public void mousePressed(MouseEvent me) : To be invoked when the mouse button is pressed
on source.
public void mouseReleased(MouseEvent me) : To be invoked when the mouse button is
released on source.
public void mouseClicked(MouseEvent me) : To be invoked when the mouse button is clicked
on source.

The MouseMotionListener is another listener that can track the movement of Mouse in
the applet.
Below program shows how the MouseEvent and MouseListener work.
import java.applet.Applet;
import java.awt.*;
import java.awt.event.*;
public class AppletMouseListener extends Applet implements MouseListener
{
String str="";
// init() in place of frame constructor
public void init()
{
addMouseListener(this);
}
// override all the 5 abstract methods of MouesListener
public void mousePressed(MouseEvent e)
{
str = "You pressed mouse";
repaint();
}
public void mouseReleased(MouseEvent e)
{
str = "You released mouse";
repaint();
}
public void mouseClicked(MouseEvent e)
{
str = "You clicked mouse";
repaint();
}
public void mouseEntered(MouseEvent e)
{
str = "Mouse entered frame";
repaint();
}
public void mouseExited(MouseEvent e)
{
str = "Mouse existed frame";
repaint();
}
// write paint() method to draw on applet window
public void paint(Graphics g)
{
g.drawString(str, 75, 150);
}
}

MouseApplet class output


Output of the above program can be seen when mouse is hovered or clicked over the grey area in
applet viewer

Adapter Classes
In our earlier MouseListener example, we had implemented all the methods of the
MouseListener interface whether we needed them or not. This is because of the java
standard that the class implementing the interface must provide implementation of all the
methods of the interface.

Any listener class that chooses to be a listener, must implement all the methods of that
interface be it empty method bodies. It must implement irrespective of whether it needs it
or not. To overcome this feature and to write a cleaner clutter free code,
the AWT framework helps us by providing adapter classes for all the Listener interfaces.
These adapter classes implement all the methods of the interface by writing all the empty
methods. The listener just extends this class and overrides only the necessary method to
perform the task.

In the above example of MouseListener, we have a MouseAdapter class that


implements the MouseListener interface. An applet if wants to notice a mouse click and
none other, it just needs to write the implementation of that method ignoring all the other
methods of the interface.

Inner Classes
As our adapter classes eliminates the need for writing all the method of the inner class, let
us see what inner classes are used for. If you have observed in the
previous MouseApplet class extends the Applet class. If we have an applet which does
event handling, not only does it need to extend the Applet class, it must extend
the Adapter class also.

But multiple inheritance of classes is not supported in Java. Here we take help of the inner
classes. The Applet class can be extended by our class, and an inner class is written to
extend the Adapter class.

Let us now build a similar class based on MouseApplet example, that listens to mouse
click event only, and uses the MouseAdapter class to do the event handling using inner
class.
The changes from the previous example are
We add an inner class which extends the adapter class.
This inner class has a mouseClicked implementation.
The init method now calls an object of inner class as the MouseListener.
The paint method just prints the Mouse clicked.
Below program implements Adapter class using the concept of Inner class
1. package com.ct.applet;
2.
3. import java.applet.Applet; import java.awt.Color; import java.awt.Graphics;
4. import java.awt.event.MouseAdapter; import java.awt.event.MouseEvent;
5.
6. public class MouseApplet2 extends Applet { boolean mouseClicked = false;
7.
8. public void init() {
9. this.setBackground(Color.gray); this.addMouseListener(new MouseAppletAdapter());
10. }
11.
12. class MouseAppletAdapter extends MouseAdapter { public void mouseClicked(MouseEvent e) {
13. mouseClicked = true; repaint();
14. }
15.
16.
17.
18.
19.
20.
21.
22.
23. }
24.
25. public void paint(Graphics g) {
26. g.setColor(Color.yellow); if (mouseClicked) {
27. g.drawString("MouseClicked", 10, 150); mouseClicked = false;
28. }
29.
30. }
31.
32.
33. }

MouseApplet class output


Output of the above program can be seen only when mouse is clicked over the grey area in applet
viewer.

Basic structure of AWT


Java provides us a class library called the AWT (also known as the Abstract Window
Toolkit) which is very flexible and powerful. We are aware that a user interface
interacts with the user to get data. The user interface can be a UNIX shell where we type
command or a GUI (graphical interface) that is very pleasing to the eye.
The AWT is platform dependent. The AWT provides a set of tools for developing
the GUI.
A GUI is built using graphical elements called Components. This can be thought as the
super class of all the components present in AWT.
Components are placed within Containers. As Containers are also Components, one can
be placed inside another. The only rule being components must fit completely within a
container, so that one can contain another and so on. This process of nesting of
components creates a tree, wherein the container is the root and components such as text
fields, labels, buttons become the leaves.

AWT Packages
AWT consists of 12 packages of 370 classes. The commonly used
are java.awt and java.awt.event.
The java.awt package contains the core AWT graphic classes
Components like Button, Checkbox.
Containers like Frame and Panel.
Layout managers like BorderLayout and GridLayout.
Graphics classes like Graphics and Font.
The java.awt.event package is used for event handling which we have learnt earlier
Events like ActionEvent and MouseEvent.
Event Listener Interfaces like ActionListener and MouseListener.
Event Listener Adapter classes like MouseAdapter and KeyAdapter.

Components of AWT
The AWT has 4 container classes and 9 component classes. Applet is also a container class
which is the subclass of Panel.
The Container classes are
Window
Frame
Dialog
Panel

The Component classes are


Label
TextField
TextArea
Button
Canvas
Choice
List
CheckBox
Scroll Bar

Steps to create a Container


Steps to create a container and add a component(s) are
We first declare the component with a name and create an object using the new operator using
the components constructor.
Decide on what container to be created to add the above components (such as Frame or Panel).
Then add the component(s) on the container using the Container.add(Component) method.

Label
Before we write a program let us understand these User Interface Components in detail.
A Label is used to display a text, it can be placed before a component or on the top of the
component to label something. The Label can be created using the new keyword and calling one
of the constructors of the label component.

Constructors
public Label (String strLabel, int alignment)
public Label (String strLabel)
public Label ()

A label supports method that can be used to get and set text and alignment of the label. A few
methods that are commonly used are listed below.
Methods
public String getText()
public void setText(String
strLabel) public int getAlignment()
public void setAlignment(int alignment)

The label alignment uses one of the three constants defined in the class.
Constants
public static final LEFT
public static final RIGHT
public static final CENTER
Example
An example to show how labels are used.

1. Panel p = new Panel();


2. Label name = new Label("UserName");
3. p.add(name);
4. Label pwd = new Label("Password");
5. p.add(pwd);

Button
A Button triggers an event when pressed. Generally, we use button when we want to do
something when the button is pressed. When a button is pressed and released, AWT sends an
instance of ActionEvent to the button's action listeners that have registered to this button.
A Button is created by using one of the below constructors
Constructors
public Button()
public Button(String label)

A few common methods used on this class are


Methods
public void addActionListener(ActionListener listener)
public ActionListener[] getActionListeners()
public void removeActionListener(ActionListener listener)
Program
1. package com.ct.applet;
2.
3. import java.awt.Button; import java.awt.Color; import java.awt.Graphics;
4. import java.awt.event.ActionEvent; import java.awt.event.ActionListener;
5.
6. public class ButtonApplet extends java.applet.Applet implements ActionListener { String buttonC
7.
8.
9.
10.
11.
12. public void init() {
13.
14. this.setBackground(Color.gray); Button b1 = new Button("I"); b1.addActionListen
15. this.add(b2);
16. this.add(b3);
17.
18.
19.
20.
21.
22.
23.
24.
25. }
26.
27. public void paint(Graphics g) {
28. g.setColor(Color.yellow);
29. g.drawString(buttonClicked + " button clicked" , 10, 150);
30. }
31.
32. public void actionPerformed(ActionEvent e) { buttonClicked =e.getActionCommand(); repa
33. }
34.
35.
36.
37. }

ButtonApplet class output

TextField
A TextField class is a component that is used for single line text that needs to be entered or
edited. TextFields are commonly used in forms. A Label is used along with the TextField to
display the name of text field.
Textfield is created using one of the below constructors. The noOfColoumns argument
in public TextField(int noOfColumns) method specifies the size of the TextField.
The text argument in public TextField(String text) method is the default text to be displayed
inside the TextField.
Constructors
public TextField()
public TextField(int noOfColumns)
public TextField(String text)
public TextField(String text,int noOfColumns)

A few common public methods of this class are


Methods
public void setText(String text)
public int getColumns()
public int getMinimumSize()
public void addTextListener(TextListener listener)
public ActionListener[] getActionListeners()
public void removeActionListener(ActionListener listener)
Program
1. package com.ct.applet;
2.
3. import java.awt.Color; import java.awt.Graphics; import java.awt.Label; import java.awt.TextField
4. import java.awt.event.TextEvent; import java.awt.event.TextListener;
5.
6.
7.
8.
9.
10. public class TextFieldApplet extends java.applet.Applet implements TextListener {
11. String textEntered = "";
12.
13. public void init() {
14.
15. this.setBackground(Color.gray); Label lab = new Label("Enter name"); this.add(lab)
16. TextField text1 = new TextField(25); this.add(text1); text1.addTextListener(this);
17.
18.
19.
20.
21. }
22.
23. public void paint(Graphics g) {
24. g.setColor(Color.yellow); g.drawString(textEntered, 10, 150);
25. }
26.
27. public void textValueChanged(TextEvent e) {
28.
29. textEntered = e.paramString();
30. repaint();
31. }
32.
33. }

TextFieldApplet class output


CheckboxGroup
A CheckboxGroup is used to get together a set of checkboxes and group them. Grouping them
makes a condition when only one in the group can be in ON state at any point of time. Clicking
any other checkbox in the group changes the other check boxes to OFF state. It is used for the
functionality of radio buttons. The event handling can be done on each checkbox and not on the
group.
The Checkbox can be created using one of the following constructors. The CheckboxGroup has
only a single constructor from which it can be created.
Constructors
Checkbox
Checkbox()
Checkbox(String name)
Checkbox(String name, boolean state)
Checkbox(String name, boolean state, CheckboxGroup cg)
Checkbox(String name, CheckboxGroup cg, boolean state)
CheckboxGroup
CheckboxGroup()

A few public methods on the Checkbox and CheckboxGroup are


Methods
Checkbox
public void setLabel(String label)
public void setState(boolean state)
public String getLabel()
public boolean getState()
public void setCheckboxGroup(CheckboxGroup g)
CheckboxGroup
public Checkbox getSelectedCheckbox()
public Checkbox setSelectedCheckbox(Checkbox box)

Program
1. package com.ct.applet;
2.
3. import java.applet.Applet; import java.awt.Checkbox; import java.awt.CheckboxGroup; import j
4. import java.awt.Graphics;
5. import java.awt.event.ItemEvent; import java.awt.event.ItemListener;
6.
7.
8.
9.
10.
11. public class CheckboxApplet extends Applet implements ItemListener {
12. String checkboxLabel = "cb3";
13.
14. public void init() {
15. // creating a single check box
16. this.setBackground(Color.gray);
17. Checkbox cb = new Checkbox("Seperate Checkbox");
18. this.add(cb);
19. // Adding Item listeners
20. cb.addItemListener(this);
21. // creating a checkbox group and adding listeners to check boxes
22. CheckboxGroup cbg = new CheckboxGroup();
23. Checkbox cb1 = new Checkbox("Checkbox1 of Group", cbg, false);
24. cb1.addItemListener(this);
25. Checkbox cb2 = new Checkbox("Checkbox2 of Group", cbg, false);
26. cb2.addItemListener(this);
27. Checkbox cb3 = new Checkbox("Checkbox3 of Group", cbg, true);
28. cb3.addItemListener(this);
29. // adding the checkboxes to applet
30. this.add(cb1);
31. this.add(cb2);
32. this.add(cb3);
33. }
34.
35. public void itemStateChanged(ItemEvent e) {
36. // getting the name of the checkbox clicked checkboxLabel = e.getItem().toString(); repaint();
37. }
38.
39.
40.
41. public void paint(Graphics g) {
42. g.setColor(Color.yellow); g.drawString(checkboxLabel + " clicked", 10, 150);
43. // resetting the string to empty checkboxLabel = "";
44. }
45.
46.
47.
48. }

CheckboxApplet class output


Choice
A Choice component class is used for displaying lists wherein the user can select one or more
items in the list. It is used for the LIST element in HTML.
A Choice menu is created using the below constructor
Constructors
Choice()

A few public methods on the Choice class are


Methods
public void add(String item)
public void addItemListener(ItemListener il)
public ItemListener[] getItemListeners()
public String getItem(int index)
public String getSelectedItem()
public void insert(String item, int index)

Program
1. package com.ct.applet;
2.
3. import java.applet.Applet; import java.awt.Choice; import java.awt.Color; import java.awt.Graph
4. import java.awt.event.ItemEvent; import java.awt.event.ItemListener;
5.
6.
7.
8.
9.
10.
11. public class ChoiceApplet extends Applet implements ItemListener {
12. String itemSelected = "";
13.
14. public void init() {
15. // creating a List item using choice component this.setBackground(Color.gray);
16. Label lab = new Label("Car Color Choice"); this.add(lab);
17. Choice colorChoice = new Choice(); colorChoice.add("RED"); colorChoice.add("BLUE");
18. }
19.
20. public void itemStateChanged(ItemEvent e) {
21.
22.
23.
24.
25.
26.
27.
28.
29.
30. // getting the name of the item selected
31. itemSelected = e.getItem().toString();
32. repaint();
33. }
34. void paint(Graphics g) {
public
g.setColor(Color.yellow);
g.drawString(itemSelected + " selected", 10, 150);
// resetting the string to empty
itemSelected = "";
40.}
41. }

ChoiceApplet class output

Layout Managers
A Layout in English means "the plan or design or arrangement of something laid out". In
Java AWT, Layout Managers specify how components inside a container are to be laid
out.
When placing any component inside a container, the layout manager of the container
takes the responsibility of positioning the component objects. Layout managers are
behind the screen taking care of all the computation required in positioning the
component object when an object is first added to the container, or the container is
resized. The components itself are resized relative to the container when the user resizes
the window.
If left to the developer, this repositioning code will take a few hundred lines of code.
A layout manager takes care of all this and positions the components based on the size
of container as and when required.
In the java.awt, a LayoutManager is an Interface. The LayoutManager
Interface methods that all the different types of layout managers implement are
public void addLayoutComponent (String name, Component component)
public void removeLayoutComponent (Component component)
public Dimension preferredLayoutSize (Container target)
minimumLayoutSize (Container target)
public void layoutContainer (Container target)

The different types of Layout Managers that are a part of java.awt. are
FlowLayout
BorderLayout
GridLayout
CardLayout
GridBagLayout
Flow Layout
The FlowLayout is the default layout used by java.awt.Applet and java.awt.Panel.
It places all the components one by one in a sequential order from left to right.
Once it cannot fit any more components, it moves to the next row and starts from left to right.
Based on the container size, the components preferred size is chosen, else a part of the
component is visible.
The order is the same as the order they were added.
The developer can specifically change the order.
The alignment is always LEFT and can be changed using the constants below, but still it follows
the adding of objects from left to right based on the alignment.

Constants
public final static int LEFT
public final static int RIGHT
public final static int CENTER

A FlowLayout can be added to a container using one of the constructors


Constructors
FlowLayout()
FlowLayout(int alignment)
FlowLayout(int alignment,int hgap,int vgap)

A few common public methods that are used are


Methods
public int getAlignment ()
public void setAlignment (int al)
public int getHgap()
public void setHgap(in hg)
public void setVgap(int
vg) public int getVgap()

Let us work on a simple example to visually see how a flow layout looks. This does not
do anything except we set the hgap and vgap to 15 and add components. This is to have
an idea of how it looks.
FlowLayoutExample Program
1. package com.ct.applet;
2.
3. import java.applet.Applet; import java.awt.Button; import java.awt.FlowLayout; import java.awt
4. public class FlowLayoutExample extends Applet { public void init() {
5. FlowLayout fl = new FlowLayout(); this.setLayout(fl);
6. fl.setHgap(15); fl.setVgap(15);
7. // Create a Label and add it
8. Label label = new Label("Course:");
9. // Adding it add(label);
10. // Create a TextField and add it TextField tf = new TextField("Java"); add(tf);
11. // Create a Button and add it Button b1 = new Button("YES"); add(b1);
12. // Create a Button and add it Button b2 = new Button("NO"); add(b2);
13. }
14.
15.
16.
17.
18.
19.
20.
21.
22.
23.
24.
25.
26.
27.
28.
29.
30.
31. }

FlowLayoutExample class output


Resizing the window, we can observe the button, textfield and label components are
automatically positioning themselves according to the gap defined in the flow layout
program.

Border Layout
A container for frames, dialogs or applets is a Content Pane. The default layout of the
content pane is the Border Layout. A Border Layout has five areas in it. They are top,
bottom, left, right and center. The components are placed in one of the five areas. Any
extra space that is left after placing the components is put in the center area.
The five areas of the are defined as Border Layout constants. There are constants like
EAST, WEST, NORTH & SOUTH too that can be used to add the components to the
container.
Constants
public static String PAGE_START
public static String PAGE_END
public static String LINE_START
public static String LINE_END
public static String CENTER
Constructors

There are two constructors defined to create a Border Layout.They are


BorderLayout() : Used to create a new BorderLayout with no gaps between the components.
BorderLayout(int hgap, int vgap) : Used to create a new BorderLayout with no gaps
between the components.

Methods

A few methods that are frequently used are


public void addLayoutComponent(Component comp,Constraints cons)
public int getHgap()
public void setHgap(in hg)
public void setVgap(int
vg) public int getVgap()

BorderLayoutExample Program
1. package com.ct.applet;
2.
3. import java.applet.Applet;
4. import java.awt.BorderLayout;
5. import java.awt.Color;
6. import
java.awt.Label; 7.
8. public class BorderLayoutExample extends Applet {
9.
10. public void init() {
11. setLayout(new BorderLayout());
12. Label l1 = new Label("NORTH", Label.CENTER);
13. l1.setBackground(Color.YELLOW);
14. Label l2 = new Label("SOUTH", Label.CENTER);
15. l2.setBackground(Color.YELLOW);
16. Label l3 = new Label("EAST", Label.CENTER);
17. l3.setBackground(Color.GREEN);
18. Label l4 = new Label("WEST", Label.CENTER);
19. l4.setBackground(Color.GREEN);
20. Label l5 = new Label("CENTER", Label.CENTER);
21. l5.setBackground(Color.RED);
22. add(l1, BorderLayout.NORTH);
23. add(l2, BorderLayout.SOUTH);
24. add(l3, BorderLayout.EAST);
25. add(l4, BorderLayout.WEST);
26. add(l5, BorderLayout.CENTER);
27. }
28.
29. }

BorderLayoutExample class output

Grid Layout
A Grid Layout is used if the components must be placed as a grid of cells. Each cell is
of the same size. The component that is added to the cell occupies the whole cell. Based
on the place available the cell size is as large as it can be.
A grid layout is created using one of the below constructors. The
arguments rows and columns specify the number of rows and columns that need to be
created for the grid. If the value of rows or columns is specified as zero, it means any
number of rows or columns can be created. The Grid Layout must be explicitly
specified as the layout manager.
Constructors
public GridLayout(int rows, int columns)
public GridLayout(int rows, int cols, int hGap,int vGap)

Methods

A few frequently used methods are


public int getRows()
public int getColumns()
public int getHgap()
public int getVgap()
public void setRows(int rows)
public void setColumns(int cols)
public void setHgap(int hGap)
public void setVgap(int vGap)
GridLayoutExample Program
1. package com.ct.applet;
2.
3. import java.applet.Applet; import java.awt.Button; import java.awt.GridLayout; import java.awt.
4.
5. public class GridLayoutExample extends Applet { public void init() {
6. // We are just setting the number of rows and columns setLayout(new GridLayout(5, 3));
7. // Let us iterate and see add labels,Button and TextField for (int row = 0; row < 5; row++) {
8. add(new Label("Label " + row)); add(new TextField("TextField " + row)); add(new Button("Butt
9. }
10. }
11.
12.
13.
14.
15.
16.
17.
18.
19.
20. }

GridLayoutExample class output


Card Layout
All the layout managers that we have learnt till now display all the components added to
the container all at once. A Card Layout differs in this, which means we can display
only a set of components at a time. A set of components share the same space with
another set of components. At any point of time, only one set of components are visible.
Card Layout derives its name from a deck of cards where at any point of time you pick
a single/set of cards(s) from the stack and the other cards are below the visible card(s).
Constructors
public CardLayout()
public cardLayout(int hGap,int vGap)

Methods

The Card Layout apart from the methods that are used by the layout managers like
setvGap(), getvGap() etc, have a few methods that are specific to this layout that are
used to add and show a specific set of components at a time. Let us look at such
methods.
public void first(Container parent)
public void next(Container parent)
public void previous(Container parent)
public void last(Container parent)
public void show(Container parent, String name)

CardLayoutExample Program
1. package com.ct.applet;
2.
3. import java.applet.Applet; import java.awt.Button; import java.awt.CardLayout;
4. import java.awt.event.ActionEvent; import java.awt.event.ActionListener;
5.
6. public class CardLayoutExample extends Applet implements ActionListener {
7. // Declaring a cardlayout as a global variable. CardLayout card = new CardLayout(20, 20);
8.
9.
10.
11.
12.
13. public void init() {
14. // Setting this container to display components using the card layout setLayout(card);
15. // Initializing a button and adding it to card1 Button b1 = new Button("Button1"); add(b1, "C
16. b1.addActionListener(this); // adding an action listener on the button.
17.
18.
19.
20.
21. // Initializing an other button and adding it to card2 Button b2 = new Button("Butt
22. add(b2, "Card2");
23. b2.addActionListener(this); // adding an action listener on the button.
24.
25.
26. }
27.
28. public void actionPerformed(ActionEvent e) { card.next(this);// This toggles to the next card
29. }
30.
31.
32. }

CardLayoutExample class output


The below output shows how only one button is visible at a point of time using Card Layout.
Clicking on Button1 changes to Button2 and vice versa.
What is Swing?
Java Swing is a lightweight Graphical User Interface (GUI) toolkit that includes a rich set of
widgets. It includes package lets you make GUI components for your Java applications, and It
is platform independent.
The Swing library is built on top of the Java Abstract Widget Toolkit (AWT), an older, platform
dependent GUI toolkit. You can use the Java GUI components like button, textbox, etc. from the
library and do not have to create the components from scratch.

No. Java AWT Java Swing

1) AWT components are platform-dependent. Java swing components


are platform-independent.

2) AWT components are heavyweight. Swing components


are lightweight.

3) AWT doesn't support pluggable look and Swing supports pluggable look
feel. and feel.

4) AWT provides less components than Swing. Swing provides more powerful
components such as tables, lists,
scrollpanes, colorchooser,
tabbedpane etc.

5) AWT doesn't follows MVC(Model View Swing follows MVC.


Controller) where model represents data,
view represents presentation and controller
acts as an interface between model and view.
Java Swing class Hierarchy Diagram

S.No. Class & Description

JLabel
1
A JLabel object is a component for placing text in a container.

JButton
2
This class creates a labeled button.

JColorChooser
3 A JColorChooser provides a pane of controls designed to allow a user to
manipulate and select a color.

JCheck Box
4 A JCheckBox is a graphical component that can be in either an on (true)
or off (false) state.

JRadioButton
5 The JRadioButton class is a graphical component that can be in either
an on (true) or off (false) state. in a group.

JList
6
A JList component presents the user with a scrolling list of text items.
JComboBox
7
A JComboBox component presents the user with a show up menu of choices.

JTextField
8 A JTextField object is a text component that allows for the editing of a single line
of text.

JPasswordField
9
A JPasswordField object is a text component specialized for password entry.

JTextArea
10 A JTextArea object is a text component that allows editing of a multiple lines of
text.

ImageIcon
11 A ImageIcon control is an implementation of the Icon interface that paints Icons
from Images

JScrollbar
12 A Scrollbar control represents a scroll bar component in order to enable the user
to select from range of values.

JOptionPane
13 JOptionPane provides set of standard dialog boxes that prompt users for a value
or informs them of something.

JFileChooser
14 A JFileChooser control represents a dialog window from which the user can
select a file.

JProgressBar
15 As the task progresses towards completion, the progress bar displays the task's
percentage of completion.

JSlider
16 A JSlider lets the user graphically select a value by sliding a knob within a
bounded interval.

JSpinner
17 A JSpinner is a single line input field that lets the user select a number or an
object value from an ordered sequence.

MVC in JSP
MVC stands for Model View and Controller. It is a design pattern that separates the business
logic, presentation logic and data.
Controller acts as an interface between View and Model. Controller intercepts all the incoming
requests.
Model represents the state of the application i.e. data. It can also have business logic.
View represents the presentaion i.e. UI(User Interface).
Advantage of MVC (Model 2) Architecture
1. Navigation Control is centralized
2. Easy to maintain the large application

You might also like