Sunday, 29 September 2019

Chapter5:-Applet,AWT,Swing


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:
It works at client side so less response time.
Secured

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

Drawback of Applet
Plugin is required at client browser to execute applet.

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.

public void init(): is used to initialized the Applet. It is invoked only once. This is the first method called during the lifecycle of an applet . This method kickstarts the execution of an applet. In this method, we usually initialize variables that are going to be needed throughout the life of an applet.
public void start(): is invoked after the init() method or browser is maximized. It is used to start the Applet. Method start() is called automatically by init() method. This method is a place where the actual work begins and it is called right after an applet is resuming its execution after being in a suspended position when its window was minimized.
public void stop(): is used to stop the Applet. It is invoked when Applet is stop or browser is minimized. This method is called when an applet's execution has been stopped or suspended for a while because the user has minimized the applet window.
public void destroy(): is used to destroy the Applet. It is invoked only once. This is the last method to be called in the lifecycle of an applet as this method is called only when an applet has finally terminated its execution. This method is a place for clean-up operation in order to free the memory from the resources consumed during the lifetime of an applet.

import java.awt.*;
import java.applet.*;

/*
<applet  code="Applet1" width=400 height=200>
</applet>
*/

public class Applet1 extends Applet
{
 public void init()
{
System.out.println("Initializing an applet");
}
public void start()
{
System.out.println("Starting an applet");
}
 public void stop()
{
System.out.println("Stopping an applet");
}
 public void destroy()
{
System.out.println("Destroying an applet");
}
 }


java.awt.Component class
The Component class provides 1 life cycle method of applet.
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.

How to run an Applet?
There are two ways to run an applet
By html file.
By appletViewer tool (for testing purpose).

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> 

The APPLET tag of HTML is used to start an applet either from a web browser or an applet viewer. The HTML tag allows a Java applet to be embedded in an HTML document.

Attributes in the applet tag.

Code-The name of the Java applet. Class file, which contains the compiled applet code. This name must be relative to the base URL of the Applet and cannot be an absolute URL. The extension in the file name is optional.
width -This refers to the width of the applet panel specified in pixels in the browser window.
Height- This refers to the height of the applet panel specified in pixels in the browser window. The width and height attributes specify the applet's, display area. This applet area does not include any windows or dialogue boxes that the applet shows.
Codebase -This refers to the base URL of the applet. That is, the URL of the directory that contains the applet class file. If this attribute is not specified then the HTML document's URL directory is taken as the CODEBASE.
align -This refers to the alignment of the apple!. The possible attribute values are LEFT, RlGHT, TOP, BOTTOM, MIDDLE, BASELINE, TEXTTOP, ABSMIDDLE and ABSBOTTOM.
vspace -This refers to the space, specified in number of pixels, used as a margin above and below the applet.
hspace -This refers to the space, specified in number of pixels, used as a margin to the left and right of the applet.
param -The param tag, specifies an applet parameter as a name-value pair. The name is the parameters name, value is. its value. The values of these parameters can be obtained using the getParameter () method.

The Font class provides a method of specifying and using fonts. The Font class constructor constructs font objects using the font's name, style (PLAIN, BOLD, ITALIC, or BOLD + ITALIC), and point size. Java's fonts are named in a platform independent manner and then mapped to local fonts that are supported by the operating system on which it executes. The getName() method returns the logical Java font name of a particular font and the getFamily() method returns the operating system-specific name of the font. The standard Java font names are Courier, Helvetica, TimesRoman etc.

The font can be set for a graphics context and for a component.
Font getFont() It is a method of Graphics class used to get the font property
setFont(Font f) is used to set a font in the graphics context
import java.applet.Applet;
import java.awt.*;
import java.awt.event.*;
/* <APPLET CODE ="FontClass.class" WIDTH=300 HEIGHT=200> </APPLET> */
public class FontClass extends java.applet.Applet
{
Font f; String m;
public void init()
{
f=new Font("Arial",Font.ITALIC,20);
m="Welcome to Java";
setFont(f);
}
public void paint(Graphics g)
{
Color c=new Color(0,255,0);
g.setColor(c);
g.drawString(m,4,20);
}
}

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>

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


Write the difference between local applet and remote applet.

Local Applet:- An applet developed locally and stored in a local system is known as a local applet. When a Web page is trying to find a local applet, it does not need to use the Internet and therefore the local system does not require the Internet connection. It simply searches the directories in the local system and locates and loads the specified applet.

 Specifying a Local Applet:
<applet codebase="path" code="NewApplet.class" width=120 height=120 ></apple>

Remote Applets:- A remote applet is developed by someone else and stored on a remote computer connected to the Internet. If our system is connected to the internet, we can download the remote applet onto our system via at the Internet and run it. To locate and load a remote applet, we must know the applet’s address on the Web. This address is known as Uniform Resource Locator (URL) and must be specified in the applet’s HTML document as the value of the CODEBASE attribute.

Specifying a Remote Applet:
<applet codebase=http://www.myconnectdemo.com/applets/code="NewApplet.class" width=120 height=120 >  


Java AWT (Abstract Window Toolkit) is an API to develop GUI or window-based applications in java.
Java AWT components are platform-dependent i.e. components are displayed according to the view of operating system. AWT is heavyweight i.e. its components are using the resources of OS.
The java.awt package provides classes for AWT api such as TextField, Label, TextArea, RadioButton, CheckBox, Choice, List etc.

Container
The Container is a component in AWT that can contain another components like buttons, textfields, labels etc. The classes that extends Container class are known as container such as Frame, Dialog and Panel.

Window
The window is the container that have no borders and menu bars. You must use frame, dialog or another window for creating a window.

Panel
The Panel is the container that doesn't contain title bar and menu bars. It can have other components like button, textfield etc.

Frame
The Frame is the container that contain title bar and can have menu bars. It can have other components like button, textfield etc.   

Useful Methods of Component class

public void add(Component c)-inserts a component on this component.
public void setSize(int width,int height)-sets the size (width and height) of the component.
public void setLayout(LayoutManager m)-defines the layout manager for the component.
public void setVisible(boolean status)-changes the visibility of the component, by default false.

Java AWT Example
To create simple awt example, you need a frame. There are two ways to create a frame in AWT.
oBy extending Frame class (inheritance)
oBy creating the object of Frame class (association)

AWT Example by Inheritance
import java.awt.*; 
class First extends Frame
First()
Button b=new Button("click me"); 
b.setBounds(30,100,80,30);// setting button position 
add(b);//adding button into frame 
setSize(300,300);//frame size 300 width and 300 height 
setLayout(null);//no layout manager 
setVisible(true);//now frame will be visible, by default not visible 
public static void main(String args[])
First f=new First(); 
}
Frame
Frame is a subclass of Window and have resizing canvas. It is a container that contain several different components like button, title bar, textfield, label etc. In Java, most of the AWT applications are created using Frame window. Frame class has two different constructors,

Frame() throws HeadlessException

Frame(String title) throws HeadlessException

Creating a Frame
There are two ways to create a Frame. They are,
1.By Instantiating Frame class
2.By extending Frame class

Creating Frame Window by Instantiating Frame class
import java.awt.*;
public class Testawt
{
Testawt()
{
Frame fm=new Frame();    //Creating a frame
Label lb = new Label("welcome to java graphics");   //Creating a label
fm.add(lb);           //adding label to the frame
fm.setSize(300, 300);   //setting frame size.
fm.setVisible(true);     //set frame visibilty true
}
public static void main(String args[])
{
Testawt ta = new Testawt();
}
}

Creating Frame window by extending Frame class
package testawt;

import java.awt.*;
import java.awt.event.*;

public class Testawt extends Frame
{
public Testawt()
{
Button btn=new Button("Hello World");
add(btn);   //adding a new Button.
setSize(400, 500);        //setting size.
setTitle("StudyTonight");  //setting title.
setLayout(new FlowLayout());  //set default layout for frame.
setVisible(true);           //set frame visibilty true.
}
public static void main (String[] args)
{
Testawt ta = new Testawt();   //creating a frame.
}
}

Points to Remember:
1.While creating a frame (either by instantiating or extending Frame class), Following two attributes are must for visibility of the frame:
osetSize(int width, int height);
osetVisible(true);
2.When you create other components like Buttons, TextFields, etc. Then you need to add it to the frame by using the method - add(Component's Object);
3.You can add the following method also for resizing the frame - setResizable(true);
                          
Java AWT Panel
The Panel is a simplest container class. It provides space in which an application can attach any other component. It inherits the Container class.
It doesn't have title bar.
AWT Panel class declaration
1.  public class Panel extends Container implements Accessible 
Java AWT Panel Example

import java.awt.*; 
public class PanelExample
PanelExample() 
Frame f= new Frame("Panel Example");
Panel panel=new Panel();
panel.setBounds(40,80,200,200);
panel.setBackground(Color.gray);
Button b1=new Button("Button 1");
b1.setBounds(50,100,80,30);
b1.setBackground(Color.yellow);
Button b2=new Button("Button 2");
b2.setBounds(100,100,80,30);
b2.setBackground(Color.green);
panel.add(b1);
panel.add(b2);
f.add(panel);
f.setSize(400,400);
f.setLayout(null);
f.setVisible(true);
}
public static void main(String args[]) 
new PanelExample(); 

}  


Java AWT Label
The object of Label 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.

AWT Label Class Declaration

1.      public class Label extends Component implements Accessible  
Class constructors
S.N.
Constructor & Description
1
Label()
Constructs an empty label.
2
Label(String text)
Constructs a new label with the specified string of text, left justified.
3
Label(String text, int alignment)
Constructs a new label that presents the specified string of text with the specified alignment.


Class methods


S.N.
Method & Description
1
void addNotify()
Creates the peer for this label.
2
AccessibleContext getAccessibleContext()
Gets the AccessibleContext associated with this Label.
3
int getAlignment()
Gets the current alignment of this label.
4
String getText()
Gets the text of this label.
5
protected String paramString()
Returns a string representing the state of this Label.
6
void setAlignment(int alignment)
Sets the alignment for this label to the specified alignment.
7
void setText(String text)
Sets the text for this label to the specified text.

Java Label Example
import java.awt.*;
class LabelExample
{
public static void main(String args[])
{
 Frame f= new Frame("Label Example");
 Label l1,l2;
l1=new Label("First Label.");
l1.setBounds(50,100, 100,30);
l2=new Label("Second Label.");
l2.setBounds(50,150, 100,30);
f.add(l1); f.add(l2);
f.setSize(400,400);
f.setLayout(null);
f.setVisible(true);
}
}

Java AWT Choice

The object of Choice class is used to show popup menu of choices. Choice selected by user is shown on the top of a menu. It inherits Component class.

AWT Choice Class Declaration

1.      public class Choice extends Component implements ItemSelectable, Accessible  

Java AWT Choice Example

import java.awt.*;  
public class ChoiceExample  
{  
        ChoiceExample(){  
        Frame f= new Frame();  
        Choice c=new Choice();  
        c.setBounds(100,10075,75);  
        c.add("Item 1");  
        c.add("Item 2");  
        c.add("Item 3");  
        c.add("Item 4");  
        c.add("Item 5");  
        f.add(c);  
        f.setSize(400,400);  
        f.setLayout(null);  
        f.setVisible(true);  
     }  
public static void main(String args[])  
{  
   new ChoiceExample();  
}  
}  
Java AWT List
The object of List class represents a list of text items. By the help of list, user can choose either one item or multiple items. It inherits Component class.
public class List extends Component implements ItemSelectable, Accessible  
import java.awt.*;  
public class ListExample  
{  
     ListExample()
{  
        Frame f= new Frame();  
        List l1=new List(5);  
        l1.setBounds(100,100, 75,75);  
        l1.add("Item 1");  
        l1.add("Item 2");  
        l1.add("Item 3"); 
        l1.add("Item 4");
        l1.add("Item 5");
        f.add(l1)
        f.setSize(400,400);
        f.setLayout(null); 
        f.setVisible(true);  
        }  
      public static void main(String args[])
     { 
      new ListExample(); 
      }  
       }  

Java AWT Scrollbar
The object of Scrollbar class is used to add horizontal and vertical scrollbar. Scrollbar is a GUI component allows us to see invisible number of rows and columns.

public class Scrollbar extends Component implements Adjustable, Accessible 

import java.awt.*; 
class ScrollbarExample
ScrollbarExample()
Frame f= new Frame("Scrollbar Example"); 
Scrollbar s=new Scrollbar();
s.setBounds(100,100, 50,100);
f.add(s);
f.setSize(400,400);
f.setLayout(null);
f.setVisible(true); 
public static void main(String args[])
 new ScrollbarExample(); 
}  


Java AWT TextField
The object of a TextField class is a text component that allows the editing of a single line text. It inherits TextComponent class.
public class TextField extends TextComponent 

import java.awt.*; 
class TextFieldExample
public static void main(String args[])
    Frame f= new Frame("TextField Example"); 
    TextField t1,t2; 
    t1=new TextField("Welcome to Javatpoint."); 
    t1.setBounds(50,100, 200,30); 
    t2=new TextField("AWT Tutorial"); 
    t2.setBounds(50,150, 200,30); 
    f.add(t1); f.add(t2); 
    f.setSize(400,400); 
    f.setLayout(null); 
    f.setVisible(true); 
}  


Java AWT TextArea
The object of a TextArea class is a multi line region that displays text. It allows the editing of multiple line text. It inherits TextComponent class.

public class TextArea extends TextComponent 

import java.awt.*; 
public class TextAreaExample 
     TextAreaExample(){ 
        Frame f= new Frame(); 
            TextArea area=new TextArea("Welcome to javatpoint"); 
        area.setBounds(10,30, 300,300); 
        f.add(area); 
        f.setSize(400,400); 
        f.setLayout(null); 
        f.setVisible(true); 
     } 
public static void main(String args[]) 
   new TextAreaExample(); 

}   

Java AWT MenuItem and Menu
The object of MenuItem class adds a simple labeled menu item on menu. The items used in a menu must belong to the MenuItem or any of its subclass.

The object of Menu class is a pull down menu component which is displayed on the menu bar. It inherits the MenuItem class.

AWT MenuItem class declaration
public class MenuItem extends MenuComponent implements Accessible  
AWT Menu class declaration
public class Menu extends MenuItem implements MenuContainer, Accessible  

import java.awt.*;  
class MenuExample  
{  
     MenuExample(){  
         Frame f= new Frame("Menu and MenuItem Example");  
         MenuBar mb=new MenuBar();  
         Menu menu=new Menu("Menu");  
         Menu submenu=new Menu("Sub Menu");  
         MenuItem i1=new MenuItem("Item 1");  
         MenuItem i2=new MenuItem("Item 2");  
         MenuItem i3=new MenuItem("Item 3");  
         MenuItem i4=new MenuItem("Item 4");  
         MenuItem i5=new MenuItem("Item 5");  
         menu.add(i1);  
         menu.add(i2);  
         menu.add(i3);  
         submenu.add(i4);  
         submenu.add(i5);  
         menu.add(submenu);  
         mb.add(menu);  
         f.setMenuBar(mb);  
         f.setSize(400,400);  
         f.setLayout(null);  
         f.setVisible(true);  
}  
public static void main(String args[])  
{  
new MenuExample();  
}  

}  


Java AWT PopupMenu
PopupMenu can be dynamically popped up at specific position within a component. It inherits the Menu class.

AWT PopupMenu class declaration
public class PopupMenu extends Menu implements MenuContainer, Accessible 
Java AWT PopupMenu Example
import java.awt.*; 
import java.awt.event.*; 
class PopupMenuExample 
     PopupMenuExample(){ 
         final Frame f= new Frame("PopupMenu Example"); 
         final PopupMenu popupmenu = new PopupMenu("Edit");  
         MenuItem cut = new MenuItem("Cut"); 
         cut.setActionCommand("Cut"); 
         MenuItem copy = new MenuItem("Copy"); 
         copy.setActionCommand("Copy"); 
         MenuItem paste = new MenuItem("Paste"); 
         paste.setActionCommand("Paste");     
         popupmenu.add(cut); 
         popupmenu.add(copy); 
         popupmenu.add(paste);       
         f.addMouseListener(new MouseAdapter() { 
            public void mouseClicked(MouseEvent e) {             
                popupmenu.show(f , e.getX(), e.getY()); 
            }                
         }); 
         f.add(popupmenu);  
         f.setSize(400,400); 
         f.setLayout(null); 
         f.setVisible(true); 
     } 
public static void main(String args[]) 
        new PopupMenuExample(); 

}   


Java LayoutManagers
The LayoutManagers are used to arrange components in a particular manner. LayoutManager is an interface that is implemented by all the classes of layout managers.
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 frame or window. 

The BorderLayout provides five constants for each region:

public static final int NORTH
public static final int SOUTH
public static final int EAST
public static final int WEST
public static final int CENTER
Constructors of BorderLayout class:
BorderLayout(): creates a border layout but with no gaps between the components.
JBorderLayout(int hgap, int vgap): creates a border layout with the given horizontal and vertical gaps between the components.

import java.awt.*; 
import javax.swing.*; 
 
public class Border
JFrame f; 
Border(){ 
    f=new JFrame(); 
     
    JButton b1=new JButton("NORTH");; 
    JButton b2=new JButton("SOUTH");; 
    JButton b3=new JButton("EAST");; 
    JButton b4=new JButton("WEST");; 
    JButton b5=new JButton("CENTER");; 
     
    f.add(b1,BorderLayout.NORTH); 
    f.add(b2,BorderLayout.SOUTH); 
    f.add(b3,BorderLayout.EAST); 
    f.add(b4,BorderLayout.WEST); 
    f.add(b5,BorderLayout.CENTER); 
     
    f.setSize(300,300); 
    f.setVisible(true); 
public static void main(String[] args) { 
    new Border(); 


  
Java GridLayout
The GridLayout is used to arrange the components in rectangular grid. One component is displayed in each rectangle.

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

import java.awt.*; 
Java GridLayout
The GridLayout is used to arrange the components in rectangular grid. One component is displayed in each rectangle.

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

import java.awt.*; 
import javax.swing.*; 
 
public class MyGridLayout
JFrame f; 
MyGridLayout()
    f=new JFrame(); 
     
    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"); 
         
    f.add(b1);f.add(b2);f.add(b3);f.add(b4);f.add(b5); 
    f.add(b6);f.add(b7);f.add(b8);f.add(b9); 
 
    f.setLayout(new GridLayout(3,3)); 
    //setting grid layout of 3 rows and 3 columns 
 
    f.setSize(300,300); 
    f.setVisible(true); 
public static void main(String[] args) { 
    new MyGridLayout(); 
}  



Java FlowLayout
The FlowLayout is used to arrange the components in a line, one after another (in a flow). It is the default layout of applet or panel.

Fields of FlowLayout class
public static final int LEFT
public static final int RIGHT
public static final int CENTER
public static final int LEADING
public static final int TRAILING

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

import java.awt.*; 
import javax.swing.*; 
 
public class MyFlowLayout

JFrame f; 
MyFlowLayout()

    f=new JFrame(); 
     
    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"); 
             
    f.add(b1);f.add(b2);f.add(b3);f.add(b4);f.add(b5); 
     
    f.setLayout(new FlowLayout(FlowLayout.RIGHT)); 
    //setting flow layout of right alignment 
 
    f.setSize(300,300); 
    f.setVisible(true); 

public static void main(String[] args) { 
    new MyFlowLayout();