Wednesday, December 14, 2011

CLock CAN TAlk REALLy




import java.util.*;
public class CLockTAlk
{
   public static void main(String[]args)
   {
       // get current time and date
       Calendar now = Calendar.getInstance();
       int hour = now.get(Calendar.HOUR_OF_DAY);
       int minute = now.get(Calendar.MINUTE);
       int month = now.get(Calendar.MONTH)+ 1;
       int day = now.get(Calendar.DAY_OF_MONTH);
       int year = now.get(Calendar.YEAR);

       // display gretting
       if (hour < 12)
           System.out.println("Good morning Sir!
Have you ate breakfast
yet?");
       else if (hour < 18)
           System.out.println("Good afternoon Sir!
Have you ate lunch
yet?");
       else
           System.out.println("Good evening Sir!
Have you ate dinner
yet?");

       // begin time message by showing the minutes
       System.out.print("It is");
       if (minute != 0)
       {
           System.out.print(" " + minute + " ");
           System.out.print( (minute != 1) ? "minutes" : "minute");
           System.out.print(" past");
       }

       // display the hour
           System.out.print(" ");
           System.out.print( (hour > 12) ? (hour - 12) : hour );
           System.out.print(" 0'clock on ");

           // display the name of the month
           switch (month)
           {
               case 1:
                   System.out.print("January");
                   break;
               case 2:
                   System.out.print("February");
                   break;
               case 3:
                   System.out.print("March");
                   break;
               case 4:
                   System.out.print("April");
                   break;
               case 5:
                   System.out.print("May");
                   break;
               case 6:
                   System.out.print("June");
                   break;
               case 7:
                   System.out.print("July");
                   break;
               case 8:
                   System.out.print("August");
                   break;
               case 9:
                   System.out.print("September");
                   break;
               case 10:
                   System.out.print("October");
                   break;
               case 11:
                   System.out.print("November");
                   break;
               case 12:
                   System.out.print("December");
          }

           // display the date and year
           System.out.println(" " + day + ", " + year + ".");
   }

}

Automatically create and delete a file



import java.util.*;
import java.io.*;
public class ab extends TimerTask
    {
     static File file;
     public static void main(String[] args ) throws IOException
         {
         file = new File ("test.dat");
         if (! file.exists() )
             {
             file.createNewFile();
         }
         System.out.println("File Created");
         ab test = new ab();
         Timer t = new Timer ();
         t.schedule(test, 30*1000L);
         try
             {
             while (file.exists())
                 {
                 System.out.print('.');
                 Thread.sleep(1000);
             }
         }
         catch (InterruptedException ie)
             {
             System.out.println("Error");
         }
         System.exit(0);
     } //end of main
     public void run()
         {
         file.delete();
     }
} //end of public class ab

This is a simple text clock. See




javax.swing.Timer for an explanation of how use this simple timer class.




import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.event.*;
import java.util.Calendar;      // only need this one class

/// TextClock
public class TextClock {
  
main
    public static void main(String[] args) {
        JFrame clock = new TextClockWindow();
        clock.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        clock.setVisible(true);
    }//end main
}//endclass TextClock


////// TextClockWindow
class TextClockWindow extends JFrame {
  
instance variables
    private JTextField timeField;  // set by timer listener

  
constructor
    public TextClockWindow() {
        // Build the GUI - only one panel
        timeField = new JTextField(6);
        timeField.setFont(new Font("sansserif", Font.PLAIN, 48));

        Container content = this.getContentPane();
        content.setLayout(new FlowLayout());
        content.add(timeField);
      
        this.setTitle("Text Clock");
        this.pack();

        // Create a 1-second timer and action listener for it.
        // Specify package because there are two Timer classes
        javax.swing.Timer t = new javax.swing.Timer(1000,
              new ActionListener() {
                  public void actionPerformed(ActionEvent e) {
                      Calendar now = Calendar.getInstance();
                      int h = now.get(Calendar.HOUR_OF_DAY);
                      int m = now.get(Calendar.MINUTE);
                      int s = now.get(Calendar.SECOND);
                      timeField.setText("" + h + ":" + m + ":" + s);
                  }
              });
        t.start();  // Start the timer
    }//end constructor
}//endclass TextClock

Simple Mathematical Calculations 2




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

// Java extension packages
import javax.swing.*;

public class Points extends JApplet implements ActionListener {
   JTextField x1Input, x2Input, y1Input, y2Input;
   JLabel labelX1, labelY1, labelX2, labelY2;

   // set up GUI components
   public void init()
   {
      labelX1 = new JLabel( "Enter X1: " );
      labelY1 = new JLabel( "Enter Y1: " );
      labelX2 = new JLabel( "Enter X2: " );
      labelY2 = new JLabel( "Enter Y2: " );
      x1Input = new JTextField( 4 );
      x2Input = new JTextField( 4 );
      y1Input = new JTextField( 4 );
      y2Input = new JTextField( 4 );
      y2Input.addActionListener( this );

      Container container = getContentPane();
      container.setLayout( new FlowLayout() );
      container.add( labelX1 );
      container.add( x1Input );
      container.add( labelY1 );
      container.add( y1Input );
      container.add( labelX2 );
      container.add( x2Input );
      container.add( labelY2 );
      container.add( y2Input );
   }

   // display distance between user input points
   public void actionPerformed( ActionEvent e )
   {
      double x1, y1, x2, y2;

 // read in two points
      x1 = Double.parseDouble( x1Input.getText() );
      y1 = Double.parseDouble( y1Input.getText() );
      x2 = Double.parseDouble( x2Input.getText() );
      y2 = Double.parseDouble( y2Input.getText() );

      double theDistance = distance( x1, y1, x2, y2 );
      showStatus( "Distance is " + theDistance );
   }

   // calculate distance between two points
   public double distance( double x1, double y1,
      double x2, double y2 )
   {
      return Math.sqrt( Math.pow( ( x1 - x2 ), 2 ) +
         Math.pow( ( y1 - y2 ), 2 ) );
   }

} // end class Points

Simple Mathematical Calculations




// Exercise 3.12 Solution: Multiples.java
// Given two doubles as input, the program determines if the first// is a multiple of the second.

// Java core packages
import java.awt.Graphics;   // import class Graphics

// Java extension packages
import javax.swing.*;       // import package javax.swing

public class Multiples extends JApplet {
   String result;   // output display String

   // initialize applet by obtaining values from user
   public void init()
   {
      String firstNumber;    // first String entered by user
      String secondNumber;   // second String entered by user
      double number1;        // first number to compare
      double number2;        // second number to compare

      // read first number from user as a String
      firstNumber =
         JOptionPane.showInputDialog( "Enter first floating-point number:" );

      // read second number from user as a String
      secondNumber =
         JOptionPane.showInputDialog( "Enter second floating-point number:" );

      // convert numbers from type String to type double
      number1 = Double.parseDouble( firstNumber );
      number2 = Double.parseDouble( secondNumber );

      if ( number1 % number2 == 0 )
       result  = number1 + " is a multiple of " + number2;

      if ( number1 % number2 != 0 )
       result  = number1 + " is not a multiple of " + number2;

   }  // end method init

   // draw results on applet's background
   public void paint( Graphics g )
   {
      // draw result as a String at (25, 25)
      g.drawString( result, 25, 25 );

   }  // end method paint

}  // end class OddEven

Audio channel player




import java.io.File;
import java.io.InputStream;
import java.io.IOException;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;

import javax.sound.sampled.AudioFormat;
import javax.sound.sampled.AudioInputStream;
import javax.sound.sampled.AudioSystem;
import javax.sound.sampled.LineUnavailableException;
import javax.sound.sampled.LineListener;
import javax.sound.sampled.LineEvent;
import javax.sound.sampled.Mixer;
import javax.sound.sampled.SourceDataLine;
import javax.sound.sampled.DataLine;
import javax.sound.sampled.FloatControl;
import javax.sound.sampled.BooleanControl;


public class AudioChannelPlayer
{
private static final boolean DEBUG = true;
private static final int BUFFER_SIZE = 16384;



public static void main(String[] args)
{
 // TODO: set AudioFormat after the first soundfile
 AudioFormat audioFormat = new AudioFormat(
  AudioFormat.Encoding.PCM_SIGNED,
  44100.0F, 16, 2, 4, 44100.0F, true);
 SourceDataLine  line = null;

 try
 {
  DataLine.Info info = new DataLine.Info(SourceDataLine.class, audioFormat);
  line = (SourceDataLine) AudioSystem.getLine(info);
  line.open(audioFormat, line.getBufferSize());
 }
 catch (LineUnavailableException e)
 {
  e.printStackTrace();
 }
 line.start();
 AudioChannel channel = new AudioChannel(line);
 channel.start();
 for (int nArgPos = 0; nArgPos < args.length; nArgPos++)
 {
  if (args[nArgPos].startsWith("-s"))
  {
   String strDuration = args[nArgPos].substring(2);
   int nDuration = Integer.parseInt(strDuration);
   handleSilence(nDuration, channel);
  }
  else
  {
   handleFile(args[nArgPos], channel);
  }

 }
 // TODO: instead of waiting a fixed amount of time, wait until the queue of AudioChannel is empty.
 try
 {
  Thread.sleep(10000);
 }
 catch (InterruptedException e)
 {
 }
}


private static void handleFile(String strFilename, AudioChannel channel)
{
 File audioFile = new File(strFilename);
 AudioInputStream audioInputStream = null;
 try
 {
  audioInputStream = AudioSystem.getAudioInputStream(audioFile);
 }
 catch (Exception e)
 {
  /*
   * In case of an exception, we dump the exception
   * including the stack trace to the console output.
   * Then, we exit the program.
   */
  e.printStackTrace();
  System.exit(1);
 }
 if (audioInputStream != null)
 {
  boolean bSuccessfull = channel.addAudioInputStream(audioInputStream);
  if (! bSuccessfull)
  {
   out("Warning: could not enqueue AudioInputStream; presumably formats don't match!");
  }
 }
}


private static void handleSilence(int nDuration, AudioChannel channel)
{
}



private static void out(String strMessage)
{
 System.out.println(strMessage);
}
}


/*** AudioChannelPlayer.java ***/

Built by Text2Html

BlowfishCipher




package com.ack.security.jce;

import javax.crypto.Cipher;
import javax.crypto.KeyGenerator;
import javax.crypto.SecretKey;
import javax.swing.JOptionPane;

/**
 * This program demonstrates how to encrypt/decrypt input
 * using the Blowfish Cipher with the Java Cryptograhpy.
 *
 */
public class BlowfishCipher {

  public static void main(String[] args) throws Exception {

    // create a key generator based upon the Blowfish cipher
    KeyGenerator keygenerator = KeyGenerator.getInstance("Blowfish");

    // create a key
    SecretKey secretkey = keygenerator.generateKey();

    // create a cipher based upon Blowfish
    Cipher cipher = Cipher.getInstance("Blowfish");

    // initialise cipher to with secret key
    cipher.init(Cipher.ENCRYPT_MODE, secretkey);

    // get the text to encrypt
    String inputText = JOptionPane.showInputDialog("Input your message: ");

    // encrypt message
    byte[] encrypted = cipher.doFinal(inputText.getBytes());

    // re-initialise the cipher to be in decrypt mode
    cipher.init(Cipher.DECRYPT_MODE, secretkey);

    // decrypt message
    byte[] decrypted = cipher.doFinal(encrypted);

    // and display the results
    JOptionPane.showMessageDialog(JOptionPane.getRootFrame(),
                                  "encrypted text: " + new String(encrypted) + "\n" +
                                  "decrypted text: " + new String(decrypted));

    // end example
    System.exit(0);
  }
}

Listing all running threads




// Find the root thread group
ThreadGroup root = Thread.currentThread().getThreadGroup().getParent();
    while (root.getParent() != null) {
     root = root.getParent();
}

// Visit each thread group
visit(root, 0);

// This method recursively visits all thread groups under `group'.
    public static void visit(ThreadGroup group, int level) {
     // Get threads in `group'
     int numThreads = group.activeCount();
     Thread[] threads = new Thread[numThreads*2];
     numThreads = group.enumerate(threads, false);
  
     // Enumerate each thread in `group'
         for (int i=0; i         // Get thread
         Thread thread = threads[i];
     }
  
     // Get thread subgroups of `group'
     int numGroups = group.activeGroupCount();
     ThreadGroup[] groups = new ThreadGroup[numGroups*2];
     numGroups = group.enumerate(groups, false);
  
     // Recursively visit each subgroup
         for (int i=0; i         visit(groups[i], level+1);
     }
}

//Here's an example of some thread groups that contain some threads:
java.lang.ThreadGroup[name=system,maxpri=10]
Thread[Reference Handler,10,system]
Thread[Finalizer,8,system]
Thread[Signal Dispatcher,10,system]
Thread[CompileThread0,10,system]
java.lang.ThreadGroup[name=main,maxpri=10]
Thread[main,5,main]
Thread[Thread-1,5,main]

Demonstrating the runnable interface




  import java.awt.*;
 import java.awt.event.*;
 import javax.swing.*;

 public class RandomCharacters extends JApplet implements Runnable, ActionListener 
 {
private String alphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
private JLabel outputs[];
private JCheckBox checkboxes[];
private final static int SIZE = 3;

private Thread threads[];
private boolean suspended[];

public void init()
{
outputs = new JLabel[ SIZE ];
checkboxes = new JCheckBox[ SIZE ];
threads = new Thread[ SIZE ];
suspended = new boolean[ SIZE ];

Container c = getContentPane();
c.setLayout( new GridLayout( SIZE, 2, 5, 5 ) );

for ( int i = 0; i < SIZE; i++ ) 
{
outputs[ i ] = new JLabel();
outputs[ i ].setBackground( Color.green );
outputs[ i ].setOpaque( true );
c.add( outputs[ i ] );

checkboxes[ i ] = new JCheckBox( "Suspended" );
checkboxes[ i ].addActionListener( this );
c.add( checkboxes[ i ] );
}
}

public void start()
{
// create threads and start every time start is called
for ( int i = 0; i < threads.length; i++ ) 
{
threads[ i ] = new Thread( this, "Thread " + (i + 1) );
threads[ i ].start();
}
}

public void run()
{
Thread currentThread = Thread.currentThread();
int index = getIndex( currentThread );
char displayChar;

while ( threads[ index ] == currentThread ) 
{
// sleep from 0 to 1 second
try 
{
Thread.sleep( (int) ( Math.random() * 1000 ) );

synchronized( this ) 
{
while ( suspended[ index ] && threads[ index ] == currentThread )
wait();
}
}
catch ( InterruptedException e ) 
{
System.err.println( "sleep interrupted" );
}

displayChar = alphabet.charAt( (int) ( Math.random() * 26 ) );
outputs[ index ].setText( currentThread.getName() +
": " + displayChar );
}

System.err.println( currentThread.getName() + " terminating" );
}

private int getIndex( Thread current )
{
for ( int i = 0; i < threads.length; i++ )
if ( current == threads[ i ] )
return i;

return -1;
}

public synchronized void stop()
{
// stop threads every time stop is called
// as the user browses another Web page
for ( int i = 0; i < threads.length; i++ )
threads[ i ] = null;

notifyAll();
}

public synchronized void actionPerformed( ActionEvent e )
{
for ( int i = 0; i < checkboxes.length; i++ ) 
{
if ( e.getSource() == checkboxes[ i ] ) 
{
suspended[ i ] = !suspended[ i ];

outputs[ i ].setBackground( !suspended[ i ] ? Color.green : Color.red );

if ( !suspended[ i ] )
notify();

return;
}
}
}
 }


Horoscope


Description: This program allows the user to input a number and compute for the factorial of the number.

import javax.swing.*;
import java.awt.event.*;
import java.awt.*;

public class Factorial extends JFrame
     {
     private JTextField txtNum;
     private JLabel lblNum, lblRes;
     private JButton btnCompute;
  
     public static int ComputeFactorial(int number)
         {
         int n = number-1;
         do
             {
             number = number*n;
             n--;
         }while(n>=1);
         return number;
     }
  
     public Factorial()
         {
         super("GUI Factorial");
         Container c = getContentPane();
         c.setLayout(new FlowLayout());
         lblNum = new JLabel("Enter an integer: ");
         txtNum = new JTextField(10);
         lblRes = new JLabel();
         btnCompute = new JButton("Compute");
      
         btnCompute.addActionListener
         (
         new ActionListener()
             {
             public void actionPerformed(ActionEvent e)
                 {
                 String str = txtNum.getText();
                 int tmp = Integer.parseInt(str);
                 tmp = ComputeFactorial(tmp);
                 lblRes.setText("The factorial of "+str+" is "+tmp);
             }
         }
         );
        
         c.add(lblNum);
         c.add(txtNum);
         c.add(btnCompute);
         c.add(lblRes);
         setSize(200,150);
         show();
     }
  
     public static void main(String args[])
         {
         Factorial app = new Factorial();
         app.setResizable(false);
         app.setLocation(400,200);
         app.addWindowListener
         (
         new WindowAdapter()
             {
             public void windowClosing(WindowEvent e)
                 {
                 System.exit(0);
             }
         }
         );
     }
  
}

Calender of the current month



import java.util.*;

public class CalendarExample
     {
    
     public static void main(String []args)
         {
         //Construct new calendar
        
         GregorianCalendar d = new GregorianCalendar();
        
         int today = d.get(Calendar.DAY_OF_MONTH);
         int month = d.get(Calendar.MONTH);
        
         d.set(Calendar.DAY_OF_MONTH, 1);
        
         int weekday = d.get(Calendar.DAY_OF_WEEK);
        
         System.out.println("Sun Mon Tue Wed Thu Fri Sat");
        
         for (int i = Calendar.SUNDAY; i < weekday; i++)
         System.out.print(" ");
        
         do
             {
             int day = d.get(Calendar.DAY_OF_MONTH);
            
             if (day < 10) System.out.print(" ");
             System.out.print(day);
            
             if(day == today)
             System.out.print("* ");
             else
             System.out.print(" ");
            
             if (weekday == Calendar.SATURDAY)
             System.out.println();
            
             d.add(Calendar.DAY_OF_MONTH, 1);
             weekday = d.get(Calendar.DAY_OF_WEEK);
            
         }
        
         while (d.get(Calendar.MONTH) == month);
        
         if (weekday != Calendar.SUNDAY)
         System.out.println();
        
     }
}

Port Scanner




import java.net.*;
import java.io.IOException;
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;

    public class PScanner {
  
         public static void main(String[] args) {
         InetAddress ia=null;
         String host=null;
             try {
          
             host=JOptionPane.showInputDialog("Enter the Host name to scan:\n example: xxx.com");
                 if(host!=null){
                 ia = InetAddress.getByName(host);
             scan(ia); }
         }
             catch (UnknownHostException e) {
             System.err.println(e );
         }
         System.out.println("Bye from NFS");
         //System.exit(0);
     }
  
        public static void scan(final InetAddress remote) {
        //variables for menu bar
      
        int port=0;
        String hostname = remote.getHostName();
      
             for ( port = 0; port < 65536; port++) {
                 try {
                 Socket s = new Socket(remote,port);
                 System.out.println("Server is listening on port " + port+ " of " + hostname);
                 s.close();
             }
                 catch (IOException ex) {
                 // The remote host is not listening on this port
                 System.out.println("Server is not listening on port " + port+ " of " + hostname);
             }
         }//for ends
     }
}

Ping a server




import java.io.*;
import java.net.*;

     public class PseudoPing {
         public static void main(String args[]) {
             try {
             Socket t = new Socket(args[0], 7);
             DataInputStream dis = new DataInputStream(t.getInputStream());
             PrintStream ps = new PrintStream(t.getOutputStream());
             ps.println("Hello");
             String str = is.readLine();
             if (str.equals("Hello"))
             System.out.println("Alive!") ;
             else
             System.out.println("Dead or echo port not responding");
             t.close();
         }
             catch (IOException e) {
         e.printStackTrace();}
     }
}

Change look and feel




package com.ack.gui.swing.simple;

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

public class ChangeLookAndFeel extends JFrame implements ActionListener {
  static String metalClassName = "javax.swing.plaf.metal.MetalLookAndFeel";
  static String motifClassName = "com.sun.java.swing.plaf.motif.MotifLookAndFeel";
  static String windowsClassName = "com.sun.java.swing.plaf.windows.WindowsLookAndFeel";

  public static void main( String[] argv ) {
    ChangeLookAndFeel myExample = new ChangeLookAndFeel( "Change Look And Feel" );
  }

  public ChangeLookAndFeel( String title ) {
    super( title );
    setSize( 150, 150 );
    addWindowListener( new WindowAdapter() {
      public void windowClosing( WindowEvent we ) {
        dispose();
        System.exit( 0 );
      }
    } );
    JPanel my_panel = new JPanel();
    my_panel.setLayout( new GridLayout( 1, 3 ) );
    JButton jb = new JButton( "Metal" );
    my_panel.add( jb );
    jb.addActionListener( this );
    jb = new JButton( "Motif" );
    my_panel.add( jb );
    jb.addActionListener( this );
    jb = new JButton( "Windows" );
    my_panel.add( jb );
    jb.addActionListener( this );
    getContentPane().add( my_panel );
    my_panel.setBorder( BorderFactory.createEtchedBorder() );
    pack();
    setVisible( true );
  }

  public void changeLookTo( String cName ) {
    try {
      UIManager.setLookAndFeel( cName );
    }
    catch( Exception e ) {
      System.out.println( "Could not change l&f" );
    }
    SwingUtilities.updateComponentTreeUI( this );
    this.pack();
  }

  public void actionPerformed( ActionEvent ae ) {
    String title = ae.getActionCommand();
    if( title.equals( "Metal" ) )
      changeLookTo( metalClassName );
    else if( title.equals( "Motif" ) )
      changeLookTo( motifClassName );
    else if( title.equals( "Windows" ) ) changeLookTo( windowsClassName );

  }
}

FingerPrint in Java



package com.ack.security.jce;

import java.io.FileInputStream;
import java.security.MessageDigest;
import javax.swing.*;

import sun.misc.BASE64Encoder;

/**
 * Builds the finger print of file, crypto hash value
 */
public class FingerPrint {
  public static void main(String[] args) throws Exception {
    // get the file path e.g. c:\Docs\zigzag.txt
    String inputText = JOptionPane.showInputDialog("Input your file path  ");

    // trying to build new message digest which represents and encapsulates
    // the Message Java Digest

    MessageDigest messageDigest = MessageDigest.getInstance("MD5");
    // calculating from the given file running its inside
    // while calculating the digest formula

    FileInputStream input = new FileInputStream(inputText);
    byte[] buffer = new byte[8192];
    int length;
    while( (length = input.read(buffer)) != -1 ) {
      messageDigest.update(buffer, 0, length);
    }
    byte[] raw = messageDigest.digest();

    //printout in 64 base
    BASE64Encoder encoder = new BASE64Encoder();
    String base64 = encoder.encode(raw);

    // and display the results
    JOptionPane.showMessageDialog(JOptionPane.getRootFrame(),
                                  "your file finger print is "
                                  + new String(base64.toString()));


  } // main method end

}  // class end

BlowfishCipher




package com.ack.security.jce;

import javax.crypto.Cipher;
import javax.crypto.KeyGenerator;
import javax.crypto.SecretKey;
import javax.swing.JOptionPane;

/**
 * This program demonstrates how to encrypt/decrypt input
 * using the Blowfish Cipher with the Java Cryptograhpy.
 *
 */
public class BlowfishCipher {

  public static void main(String[] args) throws Exception {

    // create a key generator based upon the Blowfish cipher
    KeyGenerator keygenerator = KeyGenerator.getInstance("Blowfish");

    // create a key
    SecretKey secretkey = keygenerator.generateKey();

    // create a cipher based upon Blowfish
    Cipher cipher = Cipher.getInstance("Blowfish");

    // initialise cipher to with secret key
    cipher.init(Cipher.ENCRYPT_MODE, secretkey);

    // get the text to encrypt
    String inputText = JOptionPane.showInputDialog("Input your message: ");

    // encrypt message
    byte[] encrypted = cipher.doFinal(inputText.getBytes());

    // re-initialise the cipher to be in decrypt mode
    cipher.init(Cipher.DECRYPT_MODE, secretkey);

    // decrypt message
    byte[] decrypted = cipher.doFinal(encrypted);

    // and display the results
    JOptionPane.showMessageDialog(JOptionPane.getRootFrame(),
                                  "encrypted text: " + new String(encrypted) + "\n" +
                                  "decrypted text: " + new String(decrypted));

    // end example
    System.exit(0);
  }
}

Adding Items and Removing Itesm from JList




import java.awt.*;
import java.awt.event.*;
import javax.swing.*;

    public class PhilosophersJList extends JFrame {
  
     private DefaultListModel philosophers;
     private JList list;
  
     public PhilosophersJList()
         {
         super( "Favorite Philosophers" );
      
         // create a DefaultListModel to store philosophers
         philosophers = new DefaultListModel();
         philosophers.addElement( "Socrates" );
         philosophers.addElement( "Plato" );
         philosophers.addElement( "Aristotle" );
         philosophers.addElement( "St. Thomas Aquinas" );
         philosophers.addElement( "Soren Kierkegaard" );
         philosophers.addElement( "Immanuel Kant" );
         philosophers.addElement( "Friedrich Nietzsche" );
         philosophers.addElement( "Hannah Arendt" );
      
         // create a JList for philosophers DefaultListModel
         list = new JList( philosophers );
      
         // allow user to select only one philosopher at a time
         list.setSelectionMode(
         ListSelectionModel.SINGLE_SELECTION );
      
         // create JButton for adding philosophers
         JButton addButton = new JButton( "Add Philosopher" );
         addButton.addActionListener(
             new ActionListener() {
          
             public void actionPerformed( ActionEvent event )
                 {
                 // prompt user for new philosopher's name
                 String name = JOptionPane.showInputDialog(
                 PhilosophersJList.this, "Enter Name" );
              
                 // add new philosopher to model
                 philosophers.addElement( name );
             }
         }
         );
      
         // create JButton for removing selected philosopher
         JButton removeButton =
         new JButton( "Remove Selected Philosopher" );
      
         removeButton.addActionListener(
             new ActionListener() {
          
             public void actionPerformed( ActionEvent event )
                 {
                 // remove selected philosopher from model
                 philosophers.removeElement(
                 list.getSelectedValue() );
             }
         }
         );
      
         // lay out GUI components
         JPanel inputPanel = new JPanel();
         inputPanel.add( addButton );
         inputPanel.add( removeButton );
      
         Container container = getContentPane();
         container.add( list, BorderLayout.CENTER );
         container.add( inputPanel, BorderLayout.NORTH );
      
         setDefaultCloseOperation( EXIT_ON_CLOSE );
         setSize( 400, 300 );
         setVisible( true );
      
     } // end PhilosophersJList constructor
  
     // execute application
     public static void main( String args[] )
         {
         new PhilosophersJList();
     }
}

A scoping example




  import java.awt.Container;
 import javax.swing.*;

 public class Scoping extends JApplet
 {
JTextArea outputArea;
int x = 1; // instance variable

public void init()
{
outputArea = new JTextArea();
Container c = getContentPane();
c.add( outputArea );
}

public void start()
{
int x = 5; // variable local to method start

outputArea.append( "local x in start is " + x );

methodA(); // methodA has automatic local x
methodB(); // methodB uses instance variable x
methodA(); // methodA reinitializes automatic local x
methodB(); // instance variable x retains its value

outputArea.append( "\n\nlocal x in start is " + x );
}

public void methodA()
{
int x = 25; // initialized each time a is called

outputArea.append( "\n\nlocal x in methodA is " + x + " after entering methodA" );
++x;
outputArea.append( "\nlocal x in methodA is " + x + " before exiting methodA" );
}

public void methodB()
{
outputArea.append( "\n\ninstance variable x is " + x + " on entering methodB" );
x *= 10;
outputArea.append( "\ninstance variable x is " + x + " on exiting methodB" );
}
 }

Callable statement example




public class CallableStmt
    {
     public static void main(String args[])
         {
         try
             {
             Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
             Connection con = DriverManager.getConnection("jdbc:odbc:uma","kworker","kworker");
          
             //calling a stored procedure with no input/output param
             /*
             CREATE PROCEDURE HELLOWORLD
             AS
             SELECT 'HELLOWORLD' AS HELLO
             */
             CallableStatement cs1 = con.prepareCall("{call HelloWorld}");
             ResultSet rs1 = cs1.executeQuery();
             while(rs1.next())
                 {
                 String one = rs1.getString("HELLO");
                 System.out.println(one);
             }
          
          
             //Calling a stored procedure which takes in 2 parameters for addition
             /*
             --EXECUTE ADDITION 10,25,NULL
             ALTER PROCEDURE ADDITION
             @A INT
             , @B INT
             , @C INT OUT
             AS
             SELECT @C = @A + @B
             */
             CallableStatement cs2 = con.prepareCall("{call ADDITION(?,?,?)}");
             cs2.registerOutParameter(3,java.sql.Types.INTEGER);
             cs2.setInt(1,10);
             cs2.setInt(2,25);
             cs2.execute();
             int res = cs2.getInt(3);
             System.out.println(res);
          
             //Another way
             /*
             --create table test(slno int,ques varchar(100),ans text)
             --EXECUTE fetchRec 1
             create procedure fetchRec
             @A int
             as
             select * from test where slno=@A
             */
             CallableStatement cs3 = con.prepareCall("{call fetchRec(?)}");
             cs3.registerOutParameter(1,java.sql.Types.INTEGER);
             cs3.setInt(1,5);
             ResultSet rs3 = cs3.executeQuery();
             while(rs3.next())
                 {
                 String ques = rs3.getString(2);
                 String ans = rs3.getString(3);
                 System.out.println(ques);
                 System.out.println(ans);
             }
          
          
         }
         catch(Exception e)
             {
             e.printStackTrace();
         }
     }
}