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

GUI programming with Swings

The AWT class hierarchy


The AWT defines windows according to a class hierarchy that adds functionality and specificity
with each level. The two most common windows are those derived from Panel, which is used by
applets, and those derived from Frame, which creates a standard application window. Much of
the functionality of these windows is derived from their parent classes. Thus, a description of
the class hierarchies relating to these two classes is fundamental to their understanding. Let’s
look at each of these classes now.

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

Frame encapsulates what is commonly thought of as a “window.” It is a subclass of Window


and has a title bar, menu bar, borders, and resizing corners.

The Origins of Swing

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.

Swing Is Built on the AWT

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.

Two Key Swing Features:

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.

a. Swing Components Are Lightweight

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.

b. Swing Supports a Pluggable Look and Feel

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

Difference between AWT and Swing

There are many differences between java awt and swing that are given below.

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 and


feel. 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.
Hierarchy of Java Swing classes

A Simple Swing Application

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
}
}

Overview of Swing Components:

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.

JButton class declaration:


public class JButton extends AbstractButton implements Accessible

Commonly used Constructors:


Constructor Description

JButton() It creates a button with no text and icon.

JButton(String s) It creates a button with the specified text.

JButton(Icon i) It creates a button with the specified icon object.


Commonly used Methods:
Methods Description

void setText(String s) It is used to set specified text on button

String getText() It is used to return the text of the button.

void setEnabled(boolean b) It is used to enable or disable the button.

void setIcon(Icon b) It is used to set the specified Icon on the button.

Icon getIcon() It is used to get the Icon of the button.

void setMnemonic(int a) It is used to set the mnemonic on the button.

void addActionListener(ActionListener a) It is used to add the action listener to this object.

Java JButton Example:

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 class declaration


public class JLabel extends JComponent implements SwingConstants, Accessible

Commonly used Constructors:


Constructor Description

JLabel() Creates a JLabel instance with no image and with an


empty string for the title.

JLabel(String s) Creates a JLabel instance with the specified text.

JLabel(Icon i) Creates a JLabel instance with the specified image.

JLabel(String s, Icon i, int Creates a JLabel instance with the specified text, image,
horizontalAlignment) and horizontal alignment.

Commonly used Methods:


Methods Description

String getText() It returns the text string that a label displays.

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.

Java JLabel Example

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 class declaration


public class JTextField extends JTextComponent implements SwingConstants
Commonly used Constructors:
Constructor Description

JTextField() Creates a new TextField

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.

Commonly used Methods:


Methods Description

void It is used to add the specified action listener to receive


addActionListener(ActionListener l) action events from this textfield.

Action getAction() It returns the currently set Action for this ActionEvent
source, or null if no Action is set.

void setFont(Font f) It is used to set the current font.

void It is used to remove the specified action listener so that


removeActionListener(ActionListen it no longer receives action events from this textfield.
er l)
Java JTextField Example
import javax.swing.*;
class TextFieldExample
{
public static void main(String args[])
{
JFrame f= new JFrame("TextField Example");
JTextField t1,t2;
t1=new JTextField("Welcome to Javatpoint.");
t1.setBounds(50,100, 200,30);
t2=new JTextField("AWT Tutorial");
t2.setBounds(50,150, 200,30);
f.add(t1); f.add(t2);
f.setSize(400,400);
f.setLayout(null);
f.setVisible(true);
}
}
4. Java JTextArea
The object of a JTextArea class is a multi line region that displays text. It allows the
editing of multiple line text. It inherits JTextComponent class.

JTextArea class declaration


public class JTextArea extends JTextComponent

Commonly used Constructors:


Constructor Description

JTextArea() Creates a text area that displays no text initially.

JTextArea(String s) Creates a text area that displays specified text initially.

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.

Commonly used Methods:


Methods Description

void setRows(int rows) It is used to set specified number of rows.

void setColumns(int cols) It is used to set specified number of columns.

void setFont(Font f) It is used to set the specified font.

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.

Java JTextArea Example


import javax.swing.*;
public class TextAreaExample
{
TextAreaExample(){
JFrame f= new JFrame();
JTextArea area=new JTextArea("Welcome to javatpoint");
area.setBounds(10,30, 200,200);
f.add(area);
f.setSize(300,300);
f.setLayout(null);
f.setVisible(true);
}
public static void main(String args[])
{
new TextAreaExample();
}
}
Layout Management:
All of the components that we have shown so far have been positioned by the default layout
manager. As we mentioned at the beginning of this chapter, a layout manager automatically
arranges your controls within a window by using some type of algorithm. If you have
programmed for other GUI environments, such as Windows, then you are accustomed to laying
out your controls by hand. While it is possible to lay out Java controls by hand, too, you
generally won’t want to, for two main reasons. First, it is very tedious to manually layout a large
number of components. Second, sometimes the width and height information is not yet available
when you need to arrange some control, because the native toolkit components haven’t been
realized.

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.

Fields of FlowLayout class:


o public static final int LEFT
o public static final int RIGHT
o public static final int CENTER
o public static final int LEADING
o public static final int TRAILING

Constructors of FlowLayout class


1. FlowLayout(): creates a flow layout with centered alignment and a default 5 unit
horizontal and vertical gap.
2. FlowLayout(int align): creates a flow layout with the given alignment and a default 5
unit horizontal and vertical gap.
3. FlowLayout(int align, int hgap, int vgap): creates a flow layout with the given
alignment and the given horizontal and vertical gap.

Example of FlowLayout class: Using FlowLayout() constructor


// import statements  
import java.awt.*;    
import javax.swing.*;    
    
public class FlowLayoutExample  
{   
JFrame frameObj;  

// 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

Constructors of BorderLayout class:


o BorderLayout(): creates a border layout but with no gaps between the components.
o BorderLayout(int hgap, int vgap): creates a border layout with the given horizontal
and vertical gaps between the components.
Example of BorderLayout class: Using BorderLayout() constructor
import java.awt.*;    
import javax.swing.*;    
public class Border   
{    
JFrame f;    
Border()  
{    
    f = new JFrame();    
     // creating buttons  
    JButton b1 = new JButton("NORTH");; // the button will be labeled as NORTH   
    JButton b2 = new JButton("SOUTH");; // the button will be labeled as SOUTH  
    JButton b3 = new JButton("EAST");; // the button will be labeled as EAST  
    JButton b4 = new JButton("WEST");; // the button will be labeled as WEST  
    JButton b5 = new JButton("CENTER");; // the button will be labeled as CENTER  
        
    f.add(b1, BorderLayout.NORTH); // b1 will be placed in the North Direction    
    f.add(b2, BorderLayout.SOUTH);  // b2 will be placed in the South Direction    
    f.add(b3, BorderLayout.EAST);  // b2 will be placed in the East Direction    
    f.add(b4, BorderLayout.WEST);  // b2 will be placed in the West Direction    
    f.add(b5, BorderLayout.CENTER);  // b2 will be placed in the Center    
        
    f.setSize(300, 300);    
    f.setVisible(true);    
}    
public static void main(String[] args) {    
    new Border();    
}    
}    

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.

Constructors of GridLayout class


1. GridLayout(): creates a grid layout with one column per component in a row.
2. GridLayout(int rows, int columns): creates a grid layout with the given rows and
columns but no gaps between the components.
3. GridLayout(int rows, int columns, int hgap, int vgap): creates a grid layout with the
given rows and columns along with given horizontal and vertical gaps.

Example of GridLayout class: Using GridLayout() Constructor


// import statements  
import java.awt.*;    
import javax.swing.*;    
public class GridLayoutExample  
{    
JFrame frameObj;    

// 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:

The events can be broadly classified into two categories:


 Foreground Events - Those events which require the direct interaction of user.They are
generated as consequences of a person interacting with the graphical components in
Graphical User Interface. For example, clicking on a button, moving the mouse, entering
a character through keyboard, selecting an item from list, scrolling the page etc.
 Background Events - Those events that require the interaction of end user are known as
background events. Operating system interrupts, hardware or software failure, timer
expires, an operation completion are the example of background events.
Event Handling is the mechanism that controls the event and decides what should happen if an
event occurs. This mechanism has the code which is known as event handler that is executed
when an event occurs. Java uses the Delegation Event Model to handle the events. This model
defines the standard mechanism to generate and handle the events.
Let's have a brief introduction to this model.
The Delegation Event Model has the following key participants namely:
 Source - The source is an object on which event occurs. Source is responsible for
providing information of the occurred event to it's handler. Java provide as with classes
for source object.
 Listener - It is also known as event handler. Listener is responsible for generating
response to an event. From java implementation point of view the listener is also an
object. Listener waits until it receives an event. Once the event is received, the listener
process the event an then returns.
The benefit of this approach is that the user interface logic is completely separated from the
logic that generates the event. The user interface element is able to delegate the processing of
an event to the separate piece of code. In this model, Listener needs to be registered with the
source object so that the listener can receive the event notification. This is an efficient way of
handling the event because the event notifications are sent only to those listeners that want to
receive them.

Steps involved in event handling:

 The User clicks the button and the event is generated.


 Now the object of concerned event class is created automatically and information about
the source and the event get populated with in same object.
 Event object is forwarded to the method of registered listener class.
 The method is now getting executed and returns.

Points to remember about listener

 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.

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.

Steps for Event Handling:

1) Implement the ActionListener interface in the class:


public class ActionListenerExample Implements ActionListener  

2) Register the component with the Listener:


component.addActionListener(instanceOfListenerclass);  

3) Override the actionPerformed() method:


public void actionPerformed(ActionEvent e){  
           //Write the code here  
}  

Java MouseListener Interface

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.

Methods of MouseListener interface

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);  

Java MouseListener Example

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

The Java MouseMotionListener is notified whenever you move or drag mouse. It is


notified against MouseEvent. The MouseMotionListener interface is found in
java.awt.event package. It has two methods.

Methods of MouseMotionListener interface

public abstract void mouseDragged(MouseEvent e);  
public abstract void mouseMoved(MouseEvent e);  

Java MouseMotionListener Example

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:

Java KeyListener Interface

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.

Methods of KeyListener interface

Sr. Method name Description


no.

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

In the following example, we are implementing the methods of the KeyListener


interface.

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

There are many advantages of applet. They are as follows:

o It works at client side so less response time.


o Secured
o It can be executed by browsers running under many platforms, including Linux,
Windows, Mac Os etc.

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.

Lifecycle methods for Applet:

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?

 Java Plug-in software.

Simple example of Applet by html file:

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>  

Parameter passing in Applet:


We can get any information from the HTML file as a parameter. For this purpose, Applet
class provides a method named getParameter().

Syntax:
public String getParameter(String parameterName)  

Example of using parameter in Applet:


import java.applet.Applet;  
import java.awt.Graphics;  
  
public class UseParam extends Applet{  
  
public void paint(Graphics g){  
String str=getParameter("msg");  
g.drawString(str,50, 50);  
}  
  
}  

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.

Example of Painting in Applet

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:

Example of Digital clock in Applet:

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>  

Displaying Graphics in Applet

java.awt.Graphics class provides many methods for graphics programming.

Commonly used methods of Graphics class:

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.

Example of Graphics in applet:

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

The Model-View-Controller (MVC) is a well-known design pattern in the web


development field. It is way to organize our code. It specifies that a program or
application shall consist of data model, presentation information and control
information. The MVC pattern needs all these components to be separated as different
objects.

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.

What is MVC architecture 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.

The MVC pattern architecture consists of three layers:

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.

Advantages of MVC Architecture


The advantages of MVC architecture are as follows:

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

You might also like