CardLayout Demo

This example shows the CardLayout manager. Pressing any one of three button available will show a different "card". Ex.If red Button is clicked,the panel with re background is Shown. Panels in card layout are switched using show() method.

import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;


public class CardLayoutDemo extends Frame implements ActionListener
{


Panel cardPanel;
Panel p1,p2,p3;
Panel buttonP;

Button b1,b2,b3;
CardLayout cLAyout;

Display a Label Contaning Both an Icon and A String

The following example illustrates how to create and display a label containing both an
icon and a string. The applet begins by getting its content pane. Next, an ImageIcon
object is created for the file france.gif. This is used as the second argument to the
JLabel constructor. The first and last arguments for the JLabel constructor are the label
text and the alignment. Finally, the label is added to the content pane.

import java.awt.*;
import javax.swing.*;
/* */
public class SwingProgram extends JApplet{
public void init()
{
//get content pane
Container cp= getContentPane();
// Create an Icon

Simple Calculator Using Applet

import java.applet.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.TextEvent;
import java.awt.event.TextListener;;
public class calculator extends Applet implements ActionListener, TextListener

{
String s,s1,s2,s3,s4;
Button b1,b2,b3,b4,b5,b6,b7,b8,b9,b0;
Button add,sub,eq,cl,mul,div;
TextField t1;
int a,b,c;

public void init()
{
t1=new TextField(10);
b1=new Button("1");
b2=new Button("2");
b3=new Button("3");
b4=new Button("4");
b5=new Button("5");
b6=new Button("6");
b7=new Button("7");
b8=new Button("8");
b9=new Button("9");
b0=new Button("0");
add=new Button("+");
sub=new Button("-");
mul=new Button("*");
div=new Button("/");
eq=new Button("=");
cl=new Button("Clear");



GridLayout gb=new GridLayout(4,5);
setLayout(gb);

CheckBox Demonstration

package GuIBasedProgram;
import java.applet.*;
import java.awt.*;
import java.awt.event.*;

public class Boxes extends Applet implements ActionListener {
    Button b1;
    Checkbox name1;
    Checkbox name2;
    public void init()
    {
        name1=new Checkbox("Red",null,false);
        name2=new Checkbox("Blue",null,false);
        b1=new Button("Submit");
        add(name1);
        add(name2);
        add(b1);
        b1.addActionListener(this);
    }

Button Demonstration

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

public class ButtonClass extends Applet implements ActionListener {
    Button red,white,blue;
    Label hit;
    public void init()
    {
        red=new Button("Red");
        white=new Button("White");
        blue=new Button("Blue");
        hit=new Label("Hit a Button to Change the Screen Color");
       
        add(red);
        add(blue);
        add(white);
        add(hit);
       

Use of MouseMotionListner


import java.applet.*;
import java.awt.*;
import java.awt.event.MouseEvent;
import java.awt.event.MouseMotionListener;
public class MouseMotionEx extends Applet implements MouseMotionListener
{

  
    int xcord;
    int ycord;
    public void init()
    {
        addMouseMotionListener(this);
    }

Playing audio clips

import java.applet.*;
import java.lang.*;
import java.net.URL;
public class AudioDemo extends Applet {

AudioClip aud_clip;
public void init()
{
aud_clip=getAudioClip(getDocumentBase(),"chicken.au");
}

Constructor Overloading

//Demonstration Of Constructor OverLoading

public class Rect {
int l,b;
Rect() //Constructor 1
{
l=10;
b=5;
}
Rect(int l,int b) //Constructor 2
{
this.b=b;
this.l=l;
}

Usage of Font and Color class

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


public class ColorFont extends Applet
{
public void init()
{
Color color1=new Color(230,220,0);
setBackground(color1);
}
public void paint(Graphics g)
{
String str="";
String FontList[];
GraphicsEnvironment ge=GraphicsEnvironment.getLocalGraphicsEnvironment();
FontList = ge.getAvailableFontFamilyNames();
g.drawString("Font Available ARE :", 5, 30);
for(int i=0;i {
str+=FontList[i]+",";
g.drawString(str, 5, 50);
}


Simple Event Handing

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

class EventHandling extends Frame implements ActionListener{
TextField tf;
EventHandling(){

tf=new TextField();
tf.setBounds(60,50,170,20);

Bubble Sort

import java.util.Scanner;

class BubbleSort {
  public static void main(String []args) {
    int n, c, d, swap;
    Scanner in = new Scanner(System.in);

    System.out.println("Input number of integers to sort");
    n = in.nextInt();

    int array[] = new int[n];

    System.out.println("Enter " + n + " integers");

Find Your IP Address

import java.net.InetAddress;

class IPAddress
{
   public static void main(String args[]) throws Exception
   {
      System.out.println(InetAddress.getLocalHost());
   }
}


For Each Loop (Enhanced For Loop)

class ForeachLoop {
  public static void main(String[] args) {
    int primes[] = { 2, 3, 5, 7, 11, 13, 17, 19, 23, 29};

    for (int t: primes) {
      System.out.println(t);
    }
  }
}


Largest among Three Numbers

import java.util.Scanner;

class Largest
{
   public static void main(String args[])
   {
      int x, y, z;
      System.out.println("Enter three integers ");
      Scanner in = new Scanner(System.in);

      x = in.nextInt();
      y = in.nextInt();
      z = in.nextInt();

   

Multiple Class

class Computer {
  Computer() {
    System.out.println("Constructor of Computer class.");
  }

  void computer_method() {
    System.out.println("Power gone! Shut down your PC soon...");
  }

  public static void main(String[] args) {
    Computer my = new Computer();
    Laptop your = new Laptop();

    my.computer_method();
    your.laptop_method();
  }
}

Static Block

class StaticBlock {
  public static void main(String[] args) {
    System.out.println("Main method is executed.");
  }

  static {
    System.out.println("Static block is executed before main method.");
  }
}

Even Or Odd

import java.util.Scanner;

class OddOrEven
{
   public static void main(String args[])
   {
      int x;
      System.out.println("Enter an integer to check if it is odd or even ");
      Scanner in = new Scanner(System.in);
      x = in.nextInt();

      if ( x % 2 == 0 )
         System.out.println("You entered an even number.");
      else

Get Input From User using Scanner

import java.util.Scanner;

class GetInputFromUser
{
   public static void main(String args[])
   {
      int a;
      float b;
      String s;

      Scanner in = new Scanner(System.in);

Try-Catch-Finally

class trycatchfinally
{
  public static void main(String[] args) {

  try {
   int a,b,c;
a=5;
b=0;
c=a/b;
  }
  catch (Exception e) {
    System.out.println("Divide By Zero");
  }
 

Try-Catch Block

public class trycatch {
public static void main(String args[]){
     try{
        int a[] = new int[2];
        System.out.println("Access element three :" + a[3]);
     }catch(ArrayIndexOutOfBoundsException e){
        System.out.println("Exception thrown  :" + e);
     }
     System.out.println("Out of the block");
  }

}

Addition of Two Numbers Using Applet

import java.awt.*;
   import java.applet.*;
    import java.awt.event.*;
    import java.awt.Label;

    public class add extends Applet implements ActionListener{
      TextField text1,text2,output;
      Label label1,label2,label3,title;
      Button button,clear;
      public void init(){
        setLayout(null);

Draw lines,Rectangles And Ovals

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

public class draw extends Applet
{
public void paint(Graphics g)
{
for(int i=0;i<=250;i++)
{
Color c1=new Color(35-i,55-i,110-i);
g.setColor(c1);

Java - Overriding

class Animal{

   public void move(){
      System.out.println("Animals can move");
   }
}

Suspend And Resume Thread

class susresThread implements Runnable
{
String n;
Thread thrd;
boolean suspended;
susresThread()
{
thrd=new Thread(this,"Suspend Resume Thread");
suspended=false;
thrd.start();
}

Hello Java

class Hello
{
public static void main(String args[])
{
System.out.println("Hello Java..");
}
}

Command Line

class comline
{
public static void main(String args[])
{
int count,i=0;
String s;
count=args.length;
System.out.println("Number of Argument ="+count);

Thread Priority

class ThreadOne extends Thread
{
public void run()
{
try
{
for(int i=0;i<5;i++)
{
System.out.println("Thread 1 : i ="+i);
Thread.sleep(500);
}
}
catch(Exception e)
{

}
}
}

Thread Methods : yield(),stop(),sleep()

class D extends Thread
{
public void run()
{
for(int i=0;i<5;i++)
{
if(i==0) yield(); //Transfer Control to B when i=0

System.out.println("From Class D i ="+i);
}
}
}

Thread Test


class A extends Thread
{
public void run()
{
for(int i=0;i<5;i++)
{
System.out.println("From Thread A :"+i);
}
}
}

Creating Thread

public class PingPong extends Thread {
    private String word; // What word to print
    private int delay; // how long to pause
    public PingPong(String whatToSay, int delayTime) {
        word = whatToSay;
        delay = delayTime;
    }

Smiley

import java.awt.*;
import java.applet.*;
 public class smiley extends Applet
 {
public void init()
{
setBackground(Color.gray);

}

Banner

import java.awt.*;
import java.applet.*;
public class Banner extends Applet implements Runnable{
String str="This is a Banner.........";
Thread t;
boolean b;
public void init()
{
setBackground(Color.gray);
setBackground(Color.yellow);
}
public void start()
{

Reading and Writing using random access file.

import java.io.*;
public class RandomFile {
    public static void main(String args[])throws IOException
    {
        System.out.println("Reading Content in Read Write Mode");
        RandomAccessFile Ra=new RandomAccessFile("Ex1.txt","rw");
        Ra.seek(Ra.length());
        System.out.println("Writing Content In File : Ex.txt");
        String srt="Use For Java Program..";
     

Copying charecter from one File to another File

import java.io.*;
public class FileChar {
    public static void main(String args[]) throws IOException
    {
        File f=new File(args[0]);
        int n;
        char a[]=new char[50];
        String str;
       
        if(args.length!=2)
        {
            System.out.print("File Not Entered..");
            System.exit(0);
        }
        if(f.exists())
        {
            FileReader fr=new FileReader(f);
            System.out.println("Reading :"+args[0]);
            fr.read(a);
            for(char c : a)
            {
                System.out.print(c);
            }
            System.out.println();
        }
        else
        {
            System.out.println("File does Not Exist :"+args[0]);
            System.exit(0);
        }
       
        String s=new String(a);
        System.out.println("Writing :"+args[1]);
        FileWriter fw=new FileWriter(args[1]);
        fw.write(s);
        fw.close();
        System.out.print("Content Copied..");
    }
}


Writing byte to File

import java.io.*;
public class WriteFile {
    public static void main(String args[]) throws IOException
    {
        File f=new File(args[0]);
        byte b=01;
        if(!f.exists())
            System.out.println("\n"+args[0] +" is New File");
        else
       

Reading bytes from File

import java.io.*;
public class RdFile {
    public static void main(String args[]) throws IOException
    {
        if(args.length != 1)
        {
            System.out.println("\nFile Not Found.....!!!");
            System.exit(0);
        }
        File f=new File(args[0]);
        byte b[]={};
        //Reading File...
        if(f.exists())
        {
            FileInputStream f1=new FileInputStream(f);
            int num=f1.available();
            b=new byte[num];
            int n=f1.read(b);
            String str=new String(b);
            System.out.println("\nContent :"+str);
            f1.close();
            f=null;
        }
        else
        {
            System.out.print("\nFile Does not Exist");
            System.exit(0);
        }
      
}
}


Copying byte from one file to another file.

import java.io.*;
public class FileDemo
{
    public static void main(String args[]) throws IOException
    {
        if(args.length != 2)
        {
            System.out.println("\nFile Not Found.....!!!");
            System.exit(0);
        }
   

Circle

package Applet;
import java.awt.*;
import java.applet.Applet;
import java.awt.Graphics;

public class SecondApplet extends Applet {

Hello World

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



public class HelloWorldApplet extends Applet
{
   public void paint(Graphics g)
   {
      g.drawString("Hello World",25,50);
   }
}