Java Notes - 5th Unit
Java Notes - 5th Unit
Component
At the top of the AWT hierarchy is the Component class. Component is an abstract class that
encapsulates all of the attributes of a visual component. All user interface elements that are
displayed on the screen and that interact with the user are subclasses of Component. It defines
over a hundred public methods that are responsible for managing events, such as mouse and
keyboard input, positioning and sizing the window, and repainting. A Component object is
responsible for remembering the current foreground and background colors and the currently
selected text font.
Container
The Container class is a subclass of Component. It has additional methods that allow other
Component objects to be nested within it. Other Container objects can be stored inside of a
Container. This makes for a multileveled containment system. A container is responsible for
laying out (that is, positioning) any components that it contains. It does this through the use of
various layout managers.
Panel
The Panel class is a concrete subclass of Container. It doesn’t add any new methods; it simply
implements Container. A Panel may be thought of as a recursively nestable, concrete screen
component. Panel is the super-class for Applet. When screen output is directed to an applet, it
is drawn on the surface of a Panel object. In essence, a Panel is a window that does not contain
a title bar, menu bar, or border. This is why you don’t see these items when an applet is run
inside a browser. When you run an applet using an applet viewer, the applet viewer provides
the title and border.
Window
The Window class creates a top-level window. A top-level window is not contained within any
other object; it sits directly on the desktop. Generally, you won’t create Window objects
directly. Instead, you will use a subclass of Window called Frame, described next.
Frame
Swing did not exist in the early days of Java. Rather, it was a response to deficiencies present in
Java’s original GUI subsystem: the Abstract Window Toolkit. The AWT defines a basic set of
controls, windows, and dialog boxes that support a usable, but limited graphical interface. One
reason for the limited nature of the AWT is that it translates its various visual components into
their corresponding, platform-specific equivalents, or peers. This means that the look and feel
of a component is defined by the platform, not by Java. Because the AWT components use
native code resources, they are referred to as heavyweight. The use of native peers led to
several problems. First, because of variations between operating systems, a component might
look, or even act, differently on different platforms. This potential variability threatened the
overarching philosophy of Java: write once, run anywhere. Second, the look and feel of each
component was fixed (because it is defined by the platform) and could not be (easily) changed.
Third, the use of heavyweight components caused some frustrating restrictions. For example, a
heavyweight component is always rectangular and opaque.
Before moving on, it is necessary to make one important point: although Swing eliminates a
number of the limitations inherent in the AWT, Swing does not replace it. Instead, Swing is built
on the foundation of the AWT. This is why the AWT is still a crucial part of Java. Swing also uses
the same event handling mechanism as the AWT. Therefore, a basic understanding of the AWT
and of event handling is required to use Swing.
As just explained, Swing was created to address the limitations present in the AWT. It does this
through two key features: lightweight components and a pluggable look and feel. Together they
provide an elegant, yet easy-to-use solution to the problems of the AWT. More than anything
else, it is these two features that define the essence of Swing. Each is examined here.
With very few exceptions, Swing components are lightweight. This means that they are written
entirely in Java and do not map directly to platform-specific peers. Because lightweight
components are rendered using graphics primitives, they can be transparent, which enables
nonrectangular shapes. Thus, lightweight components are more efficient and more flexible.
Furthermore, because lightweight components do not translate into native peers, the look and
feel of each component is determined by Swing, not by the underlying operating system. This
means that each component will work in a consistent manner across all platforms.
Swing supports a pluggable look and feel (PLAF). Because each Swing component is rendered by
Java code rather than by native peers, the look and feel of a component is under the control of
Swing. This fact means that it is possible to separate the look and feel of a component from the
logic of the component, and this is what Swing does. Separating out the look and feel provides a
significant advantage: it becomes possible to change the way that a component is rendered
without affecting any of its other aspects. In other words, it is possible to “plug in” a new look
and feel for any given component without creating any side effects in the code that uses that
component. Moreover, it becomes possible to define entire sets of look-and-feels that
represent different GUI styles. To use a specific style, its look and feel is simply “plugged in.”
Once this is done, all components are automatically rendered using that style. Pluggable look-
and-feels offer several important advantages. It is possible to define a look and feel that is
consistent across all platforms. Conversely, it is possible to create a look and feel that acts like a
specific platform. For example, if you know that an application will be running only in a
Windows environment, it is possible to specify the Windows look and feel. It is also possible to
design a custom look and feel. Finally, the look and feel can be changed dynamically at run time
There are many differences between java awt and swing that are given below.
Swing programs differ from both the console-based programs and the AWT-based programs.
For example, they use a different set of components and a different container hierarchy than
does the AWT. Swing programs also have special requirements that relate to threading. The
best way to understand the structure of a Swing program is to work through an example. There
are two types of Java programs in which Swing is typically used. The first is a desktop
application. The second is the applet. This section shows how to create a Swing application.
import javax.swing.*;
public class FirstSwingExample {
public static void main(String[] args) {
JFrame f=new JFrame();//creating instance of JFrame
JButton b=new JButton("click");//creating instance of JButton
b.setBounds(130,100,100, 40);//x axis, y axis, width, height
f.add(b);//adding button in JFrame
f.setSize(400,500);//400 width and 500 height
f.setLayout(null);//using no layout managers
f.setVisible(true);//making the frame visible
}
}
1. Java JButton
The JButton class is used to create a labeled button that has platform independent
implementation. The application result in some action when the button is pushed. It
inherits AbstractButton class.
import javax.swing.*;
public class ButtonExample {
public static void main(String[] args) {
JFrame f=new JFrame("Button Example");
JButton b=new JButton("Click Here");
b.setBounds(50,100,95,30);
f.add(b);
f.setSize(400,400);
f.setLayout(null);
f.setVisible(true);
}
}
2. Java JLabel
The object of JLabel class is a component for placing text in a container. It is used to
display a single line of read only text. The text can be changed by an application but a
user cannot edit it directly. It inherits JComponent class.
JLabel(String s, Icon i, int Creates a JLabel instance with the specified text, image,
horizontalAlignment) and horizontal alignment.
void setText(String text) It defines the single line of text this component will
display.
void setHorizontalAlignment(int It sets the alignment of the label's contents along the
alignment) X axis.
Icon getIcon() It returns the graphic image that the label displays.
int getHorizontalAlignment() It returns the alignment of the label's contents along
the X axis.
import javax.swing.*;
class LabelExample
{
public static void main(String args[])
{
JFrame f= new JFrame("Label Example");
JLabel l1,l2;
l1=new JLabel("First Label.");
l1.setBounds(50,50, 100,30);
l2=new JLabel("Second Label.");
l2.setBounds(50,100, 100,30);
f.add(l1); f.add(l2);
f.setSize(300,300);
f.setLayout(null);
f.setVisible(true);
}
}
3. Java JTextField
The object of a JTextField class is a text component that allows the editing of a single
line text. It inherits JTextComponent class.
JTextField(String text) Creates a new TextField initialized with the specified text.
JTextField(String text, int Creates a new TextField initialized with the specified text and
columns) columns.
JTextField(int columns) Creates a new empty TextField with the specified number of
columns.
Action getAction() It returns the currently set Action for this ActionEvent
source, or null if no Action is set.
JTextArea(int row, int Creates a text area with the specified number of rows and
column) columns that displays no text initially.
JTextArea(String s, int row, Creates a text area with the specified number of rows and
int column) columns that displays specified text.
void insert(String s, int It is used to insert the specified text on the specified
position) position.
void append(String s) It is used to append the given text to the end of the
document.
1. Java FlowLayout
The Java FlowLayout class is used to arrange the components in a line, one after another
(in a flow). It is the default layout of the applet or panel.
// constructor
FlowLayoutExample()
{
// creating a frame object
frameObj = new JFrame();
// creating the buttons
JButton b1 = new JButton("1");
JButton b2 = new JButton("2");
JButton b3 = new JButton("3");
JButton b4 = new JButton("4");
JButton b5 = new JButton("5");
JButton b6 = new JButton("6");
JButton b7 = new JButton("7");
JButton b8 = new JButton("8");
JButton b9 = new JButton("9");
JButton b10 = new JButton("10");
// adding the buttons to frame
frameObj.add(b1); frameObj.add(b2); frameObj.add(b3); frameObj.add(b4);
frameObj.add(b5); frameObj.add(b6); frameObj.add(b7); frameObj.add(b8);
frameObj.add(b9); frameObj.add(b10);
// parameter less constructor is used
// therefore, alignment is center
// horizontal as well as the vertical gap is 5 units.
frameObj.setLayout(new FlowLayout());
frameObj.setSize(300, 300);
frameObj.setVisible(true);
}
// main method
public static void main(String argvs[])
{
new FlowLayoutExample();
}
}
Output:
2. Java BorderLayout
The BorderLayout is used to arrange the components in five regions: north, south, east,
west, and center. Each region (area) may contain one component only. It is the default
layout of a frame or window.
The BorderLayout provides five constants for each region:
o public static final int NORTH
o public static final int SOUTH
o public static final int EAST
o public static final int WEST
o public static final int CENTER
Output:
3. Java GridLayout
The Java GridLayout class is used to arrange the components in a rectangular grid. One
component is displayed in each rectangle.
// constructor
GridLayoutExample()
{
frameObj = new JFrame();
// creating 9 buttons
JButton btn1 = new JButton("1");
JButton btn2 = new JButton("2");
JButton btn3 = new JButton("3");
JButton btn4 = new JButton("4");
JButton btn5 = new JButton("5");
JButton btn6 = new JButton("6");
JButton btn7 = new JButton("7");
JButton btn8 = new JButton("8");
JButton btn9 = new JButton("9");
// adding buttons to the frame
// since, we are using the parameterless constructor, therfore;
// the number of columns is equal to the number of buttons we
// are adding to the frame. The row count remains one.
frameObj.add(btn1); frameObj.add(btn2); frameObj.add(btn3);
frameObj.add(btn4); frameObj.add(btn5); frameObj.add(btn6);
frameObj.add(btn7); frameObj.add(btn8); frameObj.add(btn9);
// setting the grid layout using the parameterless constructor
frameObj.setLayout(new GridLayout());
frameObj.setSize(300, 300);
frameObj.setVisible(true);
}
// main method
public static void main(String argvs[])
{
new GridLayoutExample();
}
}
Output:
Event Handling in Java
An event can be defined as changing the state of an object or behavior by performing actions.
Actions can be a button click, cursor movement, keypress through keyboard or page scrolling,
etc. The java.awt.event package can be used to provide various event classes.
Classification of Events:
● Foreground Events
● Background Events
What is an Event?
Change in the state of an object is known as event i.e. event describes the change in state of
source. Events are generated as result of user interaction with the graphical user interface
components. For example, clicking on a button, moving the mouse, entering a character
through keyboard,selecting an item from list, scrolling the page are the activities that causes an
event to happen.
Types of Event:
In order to design a listener class we have to develop some listener interfaces. These
Listener interfaces forecast some public abstract callback methods which must be
implemented by the listener class.
If you do not implement the any if the predefined interfaces then your class can not act
as a listener class for a source object.
Callback Methods
These are the methods that are provided by API provider and are defined by the application
programmer and invoked by the application developer. Here the callback method represents an
event method. In response to an event java JRE will fire callback method. All such callback
methods are provided in listener interfaces.
If a component wants some listener will listen to its events then the source must register itself
to the listener.
The Java MouseListener is notified whenever you change the state of mouse. It is
notified against MouseEvent. The MouseListener interface is found in java.awt.event
package. It has five methods.
public abstract void mouseClicked(MouseEvent e);
public abstract void mouseEntered(MouseEvent e);
public abstract void mouseExited(MouseEvent e);
public abstract void mousePressed(MouseEvent e);
public abstract void mouseReleased(MouseEvent e);
import java.awt.*;
import java.awt.event.*;
public class MouseListenerExample extends Frame implements MouseListener{
Label l;
MouseListenerExample(){
addMouseListener(this);
l=new Label();
l.setBounds(20,50,100,20);
add(l);
setSize(300,300);
setLayout(null);
setVisible(true);
}
public void mouseClicked(MouseEvent e) {
l.setText("Mouse Clicked");
}
public void mouseEntered(MouseEvent e) {
l.setText("Mouse Entered");
}
public void mouseExited(MouseEvent e) {
l.setText("Mouse Exited");
}
public void mousePressed(MouseEvent e) {
l.setText("Mouse Pressed");
}
public void mouseReleased(MouseEvent e) {
l.setText("Mouse Released");
}
public static void main(String[] args) {
new MouseListenerExample();
}
}
Output:
Java MouseMotionListener Interface
public abstract void mouseDragged(MouseEvent e);
public abstract void mouseMoved(MouseEvent e);
import java.awt.*;
import java.awt.event.*;
public class MouseMotionListenerExample extends Frame implements MouseMotionLi
stener{
MouseMotionListenerExample(){
addMouseMotionListener(this);
setSize(300,300);
setLayout(null);
setVisible(true);
}
public void mouseDragged(MouseEvent e) {
Graphics g=getGraphics();
g.setColor(Color.BLUE);
g.fillOval(e.getX(),e.getY(),20,20);
}
public void mouseMoved(MouseEvent e) {}
public static void main(String[] args) {
new MouseMotionListenerExample();
}
}
Output:
The Java KeyListener is notified whenever you change the state of key. It is notified
against KeyEvent. The KeyListener interface is found in java.awt.event package, and it
has three methods.
1. public abstract void keyPressed (KeyEvent It is invoked when a key has been
e); pressed.
2. public abstract void keyReleased (KeyEvent It is invoked when a key has been
e); released.
3. public abstract void keyTyped (KeyEvent e); It is invoked when a key has been
typed.
Java KeyListener Example
KeyListenerExample.java
// importing awt libraries
import java.awt.*;
import java.awt.event.*;
// class which inherits Frame class and implements KeyListener interface
public class KeyListenerExample extends Frame implements KeyListener {
// creating object of Label class and TextArea class
Label l;
TextArea area;
// class constructor
KeyListenerExample() {
// creating the label
l = new Label();
// setting the location of the label in frame
l.setBounds (20, 50, 100, 20);
// creating the text area
area = new TextArea();
// setting the location of text area
area.setBounds (20, 80, 300, 300);
// adding the KeyListener to the text area
area.addKeyListener(this);
// adding the label and text area to the frame
add(l);
add(area);
// setting the size, layout and visibility of frame
setSize (400, 400);
setLayout (null);
setVisible (true);
}
// overriding the keyPressed() method of KeyListener interface where we set the text of t
he label when key is pressed
public void keyPressed (KeyEvent e) {
l.setText ("Key Pressed");
}
// overriding the keyReleased() method of KeyListener interface where we set the text of
the label when key is released
public void keyReleased (KeyEvent e) {
l.setText ("Key Released");
}
// overriding the keyTyped() method of KeyListener interface where we set the text of the
label when a key is typed
public void keyTyped (KeyEvent e) {
l.setText ("Key Typed");
}
// main method
public static void main(String[] args) {
new KeyListenerExample();
}
}
Output:
Java Applet
Applet is a special type of program that is embedded in the webpage to generate the
dynamic content. It runs inside the browser and works at client side.
Advantage of Applet
Drawback of Applet
o Plug-in is required at client browser to execute applet.
Hierarchy of Applet
As displayed in the above diagram, Applet class extends Panel. Panel class extends Container
which is the subclass of Component.
Lifecycle of Java Applet
1. Applet is initialized.
2. Applet is started.
3. Applet is painted.
4. Applet is stopped.
5. Applet is destroyed.
The java.applet.Applet class 4 life cycle methods and java.awt.Component class provides
1 life cycle methods for an applet.
java.applet.Applet class
For creating any applet java.applet.Applet class must be inherited. It provides life cycle
methods of applet.
1. public void init(): is used to initialized the Applet. It is invoked only once.
2. public void start(): is invoked after the init() method or browser is maximized. It is used
to start the Applet.
3. public void stop(): is used to stop the Applet. It is invoked when Applet is stop or
browser is minimized.
4. public void destroy(): is used to destroy the Applet. It is invoked only once.
5. public void paint(Graphics g): is used to paint the Applet. It provides Graphics class
object that can be used for drawing oval, rectangle, arc etc.
Who is responsible to manage the life cycle of an applet?
To execute the applet by html file, create an applet and compile it. After that create an
html file and place the applet code in html file. Now click the html file.
//First.java
import java.applet.Applet;
import java.awt.Graphics;
public class First extends Applet{
public void paint(Graphics g){
g.drawString("welcome",150,150);
}
Note: class must be public because its object is created by Java Plugin software that resides
on the browser.
myapplet.html
<html>
<body>
<applet code="First.class" width="300" height="300">
</applet>
</body>
</html>
Syntax:
public String getParameter(String parameterName)
myapplet.html
<html>
<body>
<applet code="UseParam.class" width="300" height="300">
<param name="msg" value="Welcome to applet">
</applet>
</body>
</html>
Additional Topics:
Painting in Applet
We can perform painting operation in applet by the mouseDragged() method of
MouseMotionListener.
import java.awt.*;
import java.awt.event.*;
import java.applet.*;
public class MouseDrag extends Applet implements MouseMotionListener{
public void init(){
addMouseMotionListener(this);
setBackground(Color.red);
}
public void mouseDragged(MouseEvent me){
Graphics g=getGraphics();
g.setColor(Color.white);
g.fillOval(me.getX(),me.getY(),5,5);
}
public void mouseMoved(MouseEvent me){}
}
In the above example, getX() and getY() method of MouseEvent is used to get the current x-axis
and y-axis. The getGraphics() method of Component class returns the object of Graphics.
myapplet.html
<html>
<body>
<applet code="MouseDrag.class" width="300" height="300">
</applet>
</body>
</html>
Digital clock in Applet
Digital clock can be created by using the Calendar and SimpleDateFormat class. Let's see
the simple example:
import java.applet.*;
import java.awt.*;
import java.util.*;
import java.text.*;
public class DigitalClock extends Applet implements Runnable {
Thread t = null;
int hours=0, minutes=0, seconds=0;
String timeString = "";
public void init() {
setBackground( Color.green);
}
public void start() {
t = new Thread( this );
t.start();
}
public void run() {
try {
while (true) {
Calendar cal = Calendar.getInstance();
hours = cal.get( Calendar.HOUR_OF_DAY );
if ( hours > 12 ) hours -= 12;
minutes = cal.get( Calendar.MINUTE );
seconds = cal.get( Calendar.SECOND );
SimpleDateFormat formatter = new SimpleDateFormat("hh:mm:ss");
Date date = cal.getTime();
timeString = formatter.format( date );
repaint();
t.sleep( 1000 ); // interval given in milliseconds
}
}
catch (Exception e) { }
}
public void paint( Graphics g ) {
g.setColor( Color.blue );
g.drawString( timeString, 50, 50 );
}
}
In the above example, getX() and getY() method of MouseEvent is used to get the current x-axis
and y-axis. The getGraphics() method of Component class returns the object of Graphics.
myapplet.html
<html>
<body>
<applet code="DigitalClock.class" width="300" height="300">
</applet>
</body>
</html>
1. public abstract void drawString(String str, int x, int y): is used to draw the specified
string.
2. public void drawRect(int x, int y, int width, int height): draws a rectangle with the
specified width and height.
3. public abstract void fillRect(int x, int y, int width, int height): is used to fill rectangle
with the default color and specified width and height.
4. public abstract void drawOval(int x, int y, int width, int height): is used to draw oval
with the specified width and height.
5. public abstract void fillOval(int x, int y, int width, int height): is used to fill oval with
the default color and specified width and height.
6. public abstract void drawLine(int x1, int y1, int x2, int y2): is used to draw line
between the points(x1, y1) and (x2, y2).
7. public abstract boolean drawImage(Image img, int x, int y, ImageObserver
observer): is used draw the specified image.
8. public abstract void drawArc(int x, int y, int width, int height, int startAngle, int
arcAngle): is used draw a circular or elliptical arc.
9. public abstract void fillArc(int x, int y, int width, int height, int startAngle, int
arcAngle): is used to fill a circular or elliptical arc.
10. public abstract void setColor(Color c): is used to set the graphics current color to the
specified color.
11. public abstract void setFont(Font font): is used to set the graphics current font to the
specified font.
import java.applet.Applet;
import java.awt.*;
public class GraphicsDemo extends Applet{
public void paint(Graphics g){
g.setColor(Color.red);
g.drawString("Welcome",50, 50);
g.drawLine(20,30,20,300);
g.drawRect(70,100,30,30);
g.fillRect(170,100,30,30);
g.drawOval(70,200,30,30);
g.setColor(Color.pink);
g.fillOval(170,200,30,30);
g.drawArc(90,150,30,30,30,270);
g.fillArc(270,150,30,30,0,180);
}
}
myapplet.html
<html>
<body>
<applet code="GraphicsDemo.class" width="300" height="300">
</applet>
</body>
</html>
MVC Architecture in Java
In this section, we will discuss the MVC Architecture in Java, alongwith its advantages
and disadvantages and examples to understand the implementation of MVC in Java.
The model designs based on the MVC architecture follow MVC design pattern. The
application logic is separated from the user interface while designing the software using
model designs.
o Model: It represents the business layer of application. It is an object to carry the data
that can also contain the logic to update controller if data is changed.
o View: It represents the presentation layer of application. It is used to visualize the data
that the model contains.
o Controller: It works on both the model and view. It is used to manage the flow of
application, i.e. data flow in the model object and to update the view whenever data is
changed.
In Java Programming, the Model contains the simple Java classes, the View used to
display the data and the Controller contains the servlets. Due to this separation the user
requests are processed as follows:
1. A client (browser) sends a request to the controller on the server side, for a page.
2. The controller then calls the model. It gathers the requested data.
3. Then the controller transfers the data retrieved to the view layer.
4. Now the result is sent back to the browser (client) by the view.
o MVC has the feature of scalability that in turn helps the growth of application.
o The components are easy to maintain because there is less dependency.
o A model can be reused by multiple views that provides reusability of code.
o The developers can work with the three layers (Model, View, and Controller)
simultaneously.
o Using MVC, the application becomes more understandable.
o Using MVC, each layer is maintained separately therefore we do not require to deal with
massive code.
o The extending and testing of application is easier.
AD