Friday, December 21, 2012

To Draw a Thick Line using JAVA GUI

To draw a Thick line using JAVA GUI :
Check following example:

Java Code:

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

public class StrokeExample extends JPanel implements Runnable {

    protected void paintComponent(Graphics g) {

        super.paintComponent(g);
        int w = getWidth();
        int h = getHeight();
        g.drawLine(0,0,w,h);    //default
        Graphics2D g2 = (Graphics2D) g;
        g2.setStroke(new BasicStroke(3));
        g2.drawLine(0,h,w,0);   //thick

    }

    public void run() {

        JFrame f = new JFrame();
        f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        f.getContentPane().add(new StrokeExample());
        f.setSize(500,400);
        f.setLocationRelativeTo(null);
        f.setVisible(true);

    }

Saturday, December 15, 2012

Quadratic Equation In java

import javax.swing.JOptionPane;
import java.io.*;
class Solution
{
    private int a,b,c,desc;
    private  double r1,r2;
    public void solve()
    {
        desc=b*b-4*a*c;
        if(desc>0)
        {
            r1=(-b+Math.sqrt(desc))/(2*a);
            r2=(-b-Math.sqrt(desc))/(2*a);
            JOptionPane.showMessageDialog(null,"roots are"+r1+" "+r2,"Message",JOptionPane.INFORMATION_MESSAGE);
        }
        else if(desc==0)
        {
            r1=r2=(-b+Math.sqrt(desc))/(2*a);
            JOptionPane.showMessageDialog(null,"roots are"+r1+" "+r2,"Message",JOptionPane.INFORMATION_MESSAGE);
        }
        else
        {
            JOptionPane.showMessageDialog(null,"there are no real solutions","Message",JOptionPane.INFORMATION_MESSAGE);
        }
    }
    public void input()
    {
        String n1,n2,n3;
        n1=JOptionPane.showInputDialog("enter a value");
        n2=JOptionPane.showInputDialog("enter b value");
        n3=JOptionPane.showInputDialog("enter c value");
        a=Integer.parseInt(n1);
        b=Integer.parseInt(n2);
        c=Integer.parseInt(n3);
    }
}
class Quadratic
{
    public static void main(String[] args)
    {
        Solution s=new Solution();
        s.input();
        s.solve();
    }
}

SimpleInterest Program in Applet

import java.awt.*;
import javax.swing.JOptionPane;
import java.applet.Applet;
/*<applet code="Interest" width=200 height=100>
  <param name=rate value=monthly>
  </applet>*/
public class Interest extends Applet
{
    String rate;
    public void start()
    {
        String s=JOptionPane.showInputDialog("enter principal amount");
        int p=Integer.parseInt(s);
        s=JOptionPane.showInputDialog("enter rate");
        int r=Integer.parseInt(s);
        s=JOptionPane.showInputDialog("enter time");
        int t=Integer.parseInt(s);
        rate=getParameter("rate");
        if(rate.equals("monthly"))
        {
            double amount=(p*t*r)/(100*12);
            JOptionPane.showMessageDialog(null,"simple interest="+amount,"simple interst",JOptionPane.INFORMATION_MESSAGE);
        }
        else
        {
            double amount=(p*t*r)/(100);
            JOptionPane.showMessageDialog(null,"simple interest="+amount,"simple interst",JOptionPane.INFORMATION_MESSAGE);   
        }
    }
}
   

MultiThreading Program In java

import java.io.*;
import javax.swing.JOptionPane;
class NewThread implements Runnable
{
    String name;
    Thread t;
    NewThread(String threadname)
    {
        name=threadname;
        t=new Thread(this,name);
        JOptionPane.showMessageDialog(null,"new thread:"+t);
        t.start();
    }
    public void run()
    {
        try
        {
            for(int i=5;i>0;i--)
            {
                JOptionPane.showMessageDialog(null,name+":"+i);
                Thread.sleep(1000);
            }
        }
    catch(InterruptedException e)
    {
        JOptionPane.showMessageDialog(null,name+" interrupted");
    }
    JOptionPane.showMessageDialog(null,name+"exiting");
}
}
class multithread
{
    public static void main(String[] args)
    {
        new NewThread("one");
      new NewThread("two");
      new NewThread("three");
     try
        {
         Thread.sleep(10000);
        }
        catch(InterruptedException e)
        {
            JOptionPane.showMessageDialog(null,"main thread interrupted");
        }
       JOptionPane.showMessageDialog(null,"main thread exiting");
    }
}
   

Mouse Events in Applets


==========================================================================
import java.awt.*;
import java.applet.Applet;
import java.awt.event.*;
/*<applet code="Mouseevents"width=200 height=100>
</applet>*/
public class Mouseevents extends Applet implements MouseListener,MouseMotionListener
{
    String msg="";
    int x=0,y=0;
    public void init()
    {
        addMouseListener(this);
        addMouseMotionListener(this);
    }
    public void mouseClicked(MouseEvent me)
    {
        x=10;
        y=20;
        msg="mouse clicked";
        repaint();
    }
    public void mouseEntered(MouseEvent me)
    {
        x=10;
        y=20;
        msg="mouse entered";
        repaint();
    }
    public void mouseExited(MouseEvent me)
    {
        x=10;
        y=20;
        msg="mouse exited";
        repaint();
    }
    public void mousePressed(MouseEvent me)
    {
        x=me.getX();
        y=me.getY();
        msg="down";
        repaint();
    }
    public void mouseReleased(MouseEvent me)
    {
        x=me.getX();
        y=me.getY();
        msg="up";
        repaint();
    }
    public void mouseDragged(MouseEvent me)
    {
        x=me.getX();
        y=me.getY();
        msg="*";
        showStatus("dragging mouse at"+x+","+y);
        repaint();
    }
    public void mouseMoved(MouseEvent me)
    {
        showStatus("moving mouse at"+me.getX()+","+me.getY());
    }
    public void paint(Graphics g)
    {
        g.drawString(msg,x,y);
    }
}

Tuesday, December 4, 2012

AWT vs SWINGS


When developing a Java program it is important to select the appropriate Java Graphical User Interface (GUI) components. There are two basic sets of components that you will most likely build your Java programs with. These two groups of components are called the Abstract Window Toolkit (AWT) and Swing. Both of these groups of components are part of the Java Foundation Classes (JFC).
An Overview of the AWT
AWT stands for Abstract Window ToolKit. The Abstract Window Toolkit supports GUI Java programming. It is a portable GUI library for stand-alone applications and/or applets. The Abstract Window Toolkit provides the connection between your application and the native GUI. The AWT provides a high level of abstraction for your Java program since it hides you from the underlying details of the GUI your program will be running on.
AWT features include:
  • A rich set of user interface components.
  • A robust event-handling model.
  • Graphics and imaging tools, including shape, color, and font classes.
  • Layout managers, for flexible window layouts that don't depend on a particular window size or screen resolution.
  • Data transfer classes, for cut-and-paste through the native platform clipboard.
The AWT components depend on native code counterparts (called peers) to handle their functionality. Thus, these components are often called "heavyweight" components.
An Overview of Swing
Swing implements a set of GUI components that build on AWT technology and provide a pluggable look and feel. Swing is implemented entirely in the Java programming language, and is based on the JDK 1.1 Lightweight UI Framework.
Swing features include:
  • All the features of AWT.
  • 100% Pure Java certified versions of the existing AWT component set (Button, Scrollbar, Label, etc.).
  • A rich set of higher-level components (such as tree view, list box, and tabbed panes).
  • Pure Java design, no reliance on peers.
  • Pluggable Look and Feel.
Swing components do not depend on peers to handle their functionality. Thus, these components are often called "lightweight" components.
AWT vs. Swing
There are, of course, both pros and cons to using either set of components from the JFC in your Java applications. Here is a summary:

AWT:
Pros
  • Speed: use of native peers speeds component performance.
  • Applet Portability: most Web browsers support AWT classes so AWT applets can run without the Java plugin.
  • Look and Feel: AWT components more closely reflect the look and feel of the OS they run on.
Cons
  • Portability: use of native peers creates platform specific limitations. Some components may not function at all on some platforms.
  • Third Party Development: the majority of component makers, including Borland and Sun, base new component development on Swing components. There is a much smaller set of AWT components available, thus placing the burden on the programmer to create his or her own AWT-based components.
  • Features: AWT components do not support features like icons and tool-tips.

Swing:
Pros
  • Portability: Pure Java design provides for fewer platform specific limitations.
  • Behavior: Pure Java design allows for a greater range of behavior for Swing components since they are not limited by the native peers that AWT uses.
  • Features: Swing supports a wider range of features like icons and pop-up tool-tips for components.
  • Vendor Support: Swing development is more active. Sun puts much more energy into making Swing robust.
  • Look and Feel: The pluggable look and feel lets you design a single set of GUI components that can automatically have the look and feel of any OS platform (Microsoft Windows, Solaris, Macintosh, etc.). It also makes it easier to make global changes to your Java programs that provide greater accessibility (like picking a hi-contrast color scheme or changing all the fonts in all dialogs, etc.).
Cons
  • Applet Portability: Most Web browsers do not include the Swing classes, so the Java plugin must be used.
  • Performance: Swing components are generally slower and buggier than AWT, due to both the fact that they are pure Java and to video issues on various platforms. Since Swing components handle their own painting (rather than using native API's like DirectX on Windows) you may run into graphical glitches.
  • Look and Feel: Even when Swing components are set to use the look and feel of the OS they are run on, they may not look like their native counterparts.

In general, AWT components are appropriate for simple applet development or development that targets a specific platform (i.e. the Java program will run on only one platform).
For most any other Java GUI development you will want to use Swing components. Also note that the Borland value-added components included with JBuilder, like dbSwing and JBCL, are based on Swing components so if you wish to use these components you will want to base your development on Swing.

Wednesday, November 28, 2012

Calculator Program in JAVA using AWT & Swings

package Calculator;

import java.awt.*;
import java.lang.*;
import java.awt.event.*;
import java.applet.Applet;
import java.awt.datatransfer.*;

public class calculator extends Applet
{

    private static final long serialVersionUID = 1L;

public void init()
 {
  calf calWindow = new calf("Java Calculator");
  calWindow.setSize(200, 250);
  calWindow.setVisible(true);
  calWindow.setResizable(false);
 }
}

class calf extends Frame implements WindowListener, ActionListener, KeyListener
{
 
    private static final long serialVersionUID = 1L;
String command, copy, arg, chg, txt;
  double result;
  String number = "123456789.0";
  String operator = "/*-+=";
  CopyPaste cp;

  Menu Menu1;
  MenuBar Menubar1;
  MenuItem menuitem1, menuitem2, menuitem3;
  TextField entrytext;
  Button numbut []; //Number buttons
  Button combut []; //Command buttons
  Panel companel, numpanel;

  public static void main(String[] arguments)
  {
   calf calWindow = new calf("Java Calculator");
   calWindow.setSize(200, 250);
   calWindow.setVisible(true);
  }

  public calf(String title)
  {
   super(title);
   addWindowListener(this);
   addKeyListener(this);

   cp = new CopyPaste();
   //cp.clip = getToolkit().getSystemClipboard();

   setBackground(Color.blue);
   setLayout(new GridLayout(1, 1));
   Menubar1 = new MenuBar();
   Menu1 = new Menu("Edit");
   menuitem1 = new MenuItem("&Copy");
   Menu1.add(menuitem1);
   menuitem1.addActionListener(this);
   menuitem2 = new MenuItem("&Paste");
   Menu1.add(menuitem2);
   menuitem2.addActionListener(this);
   menuitem3 = new MenuItem("&Exit");
   Menu1.add(menuitem3);
   menuitem3.addActionListener(this);
   Menubar1.add(Menu1);
   setMenuBar(Menubar1);
   GridBagLayout gridbag = new GridBagLayout();
   GridBagConstraints constraints = new GridBagConstraints();
   setLayout(gridbag);
   constraints.weighty = 1;
   constraints.weightx = 1;
   //constraints.fill = GridBagConstraints.BOTH;
   Font bigFont = new Font("Courier",Font.BOLD, 14);
   entrytext = new TextField(20);
   constraints.gridwidth = GridBagConstraints.REMAINDER;
   gridbag.setConstraints(entrytext,constraints);
   add(entrytext);
   entrytext.setFont(bigFont);
   entrytext.setEditable(false);
   entrytext.setForeground(Color.black);
   entrytext.setBackground(Color.white);
   entrytext.addKeyListener(this);
   entrytext.requestFocus();

   constraints.weighty = 1;
   constraints.weightx = 1;
   companel = new Panel();

   constraints.gridwidth = GridBagConstraints.REMAINDER;
   gridbag.setConstraints(companel,constraints);
   /*
    Command GridLayout
    ---------------------
    | Back |  CE  |  C |
    ---------------------
   */

   companel.setLayout(new GridLayout(1,3,5,5));

   // Create the buttons
   Font comsFont = new Font("Arial",Font.BOLD, 12);
   String[] coms = { "Back","CE","C"
             };
   combut = new Button[3];
         for (int i=0; i<=2; i++)
      {
       combut[i] = new Button(coms[i]);
       companel.add(combut[i]);
    combut[i].addActionListener(this);
    combut[i].setFont(comsFont);
    combut[i].addKeyListener(this);

   }
   add(companel);
   companel.addKeyListener(this);

   constraints.weighty = 4;
   constraints.weightx = 1;
   numpanel = new Panel();
   constraints.gridwidth = GridBagConstraints.REMAINDER;
   gridbag.setConstraints(numpanel,constraints);
   /*
    Number GridLayout
    ---------------------
    | 7 | 8 | 9 | / |sqr|
    ---------------------
    | 4 | 5 | 6 | * | % |
    ---------------------
    | 1 | 2 | 3 | - |1/x|
    ---------------------
    | 0 |+/-| . | + | = |
    ---------------------
            */
   numpanel.setLayout(new GridLayout(4,5,3,3));
   // Create the buttons
   String[] nums = { "7","8","9","/","sqrt",
              "4","5","6","*","%",
              "1","2","3","-","1/x",
              "0","+/-",".","+","="
             };
   numbut = new Button[20];
   for (int i=0; i<=19; i++)
       {
       numbut[i] = new Button(nums[i]);
       numpanel.add(numbut[i]);
    numbut[i].addActionListener(this);
    numbut[i].addKeyListener(this);
    if(operator.indexOf(nums[i]) > -1)
    {
     numbut[i].setForeground(Color.red);
    }
    else
    {
     numbut[i].setForeground(Color.blue);
    }

   }
   add(numpanel);
   numpanel.addKeyListener(this);

   //initialize global variables.
   command = "+";
   copy = "";
   chg = "N";
   txt = "";
   arg = "";
   result = 0;
  }

  public void actionPerformed(ActionEvent e)
  {
   if (e.getActionCommand() == "&Exit")
   {
    setVisible(false);
    System.exit(0);
   }
   else if (e.getActionCommand() == "&Copy")
         {
    String txt = entrytext.getText();
    if (txt != null)
          {
              cp.doCopy(txt);
          }
   }
   else if (e.getActionCommand() == "&Paste")
         {
          cp.doPaste();
    if (cp.ctxt != null)
          {
     entrytext.setText(cp.ctxt);
    }
   }
   else if (e.getActionCommand() == "Back") back_space();
   else if (e.getActionCommand() == "CE") entrytext.setText("");
   else if (e.getActionCommand() == "C")
   {
    result = 0;
    command = "+";
    entrytext.setText("");
   }
   else
   {
    arg = e.getActionCommand();
    txt = entrytext.getText();
    if(number.indexOf(arg) > -1)
    {
     if (chg == "Y") txt = "";
     txt = txt + arg;
     entrytext.setText(txt);
     chg = "N";
    }
    else check_entry();
   }
  }

  public void keyPressed(KeyEvent k){}
  public void keyReleased(KeyEvent k)
  {
   int ikey = k.getKeyCode();
   if (ikey == 127) entrytext.setText("");
  }
  public void keyTyped(KeyEvent k)
  {
   int ikey = k.getKeyChar();
   if (ikey == 8) back_space();
   else if (ikey == 10)
   {
    arg = "=";
    txt = entrytext.getText();
    display_ans();
   }
   else
   {
    txt = entrytext.getText();
    char ckey = (char) ikey;
    arg = String.valueOf(ckey);
    if(number.indexOf(arg) > -1)
    {
     if (chg == "Y") txt = "";
     txt = txt + arg;
     entrytext.setText(txt);
     chg = "N";
    }
    else check_entry();
   }
  }

  public void back_space()
  {
   txt = entrytext.getText();
   int l = txt.length();
   if (l > 0)
   {
    txt = txt.substring(0,l-1);
    entrytext.setText(txt);
   }
  }
  public void display_ans()
  {
   entrytext.setText(compute_tot(txt,command));
   chg = "Y";
   command = "+";
   result = 0;
  }
  public void check_entry()
  {
   if(arg.equals("=")) display_ans();
   else if(arg.equals("%"))
   {
    entrytext.setText(compute_tot(txt,arg));
    chg = "Y";
   }
   else if(operator.indexOf(arg) > -1)
   {
    entrytext.setText(compute_tot(txt,command));
    command = arg;
    chg = "Y";
   }
   else if(arg == "sqrt")
   {
    entrytext.setText(compute_tot(txt,arg));
    chg = "Y";
    command = "";
   }
   else if(arg == "+/-")
   {
    Double tnum = Double.valueOf(txt);
    double num = tnum.doubleValue();
    num = num * -1;
    entrytext.setText(String.valueOf(num));
    chg = "Y";
   }
   else if(arg == "1/x")
   {
    entrytext.setText(compute_tot(txt,arg));
    chg = "Y";
   }
  }
  String compute_tot(String t, String c)
  {
   Double tnum = Double.valueOf(t);
   double num = tnum.doubleValue();

   if (c.equals("+")) result = result + num;
   else if (c.equals("-")) result = result - num;
   else if (c.equals("*")) result = result * num;
   else if (c.equals("/")) result = result / num;
   else if (c.equals("%")) result = num / 100;
   else if (c.equals("+/-")) result = num * -1;
   else if (c.equals("1/x")) result = 1.000 / num;
   else if (c.equals("sqrt")) result = Math.sqrt(num);
   return String.valueOf(result);
  }

  public void windowClosing(WindowEvent we)
  {
   setVisible(false);
   System.exit(0);
  }
  public void windowClosed(WindowEvent we) {}
  public void windowDeiconified(WindowEvent we) {}
  public void windowIconified(WindowEvent we) {}
  public void windowOpened(WindowEvent we) {}
  public void windowActivated(WindowEvent we) {}
  public void windowDeactivated(WindowEvent we) {}
}


class CopyPaste implements ClipboardOwner
{

    Clipboard clip;
    String ctxt;

    CopyPaste()
    {
  clip = new Clipboard("clip");
        ctxt = null;
    }

    void doCopy(String txt)
    {
        StringSelection trans = new StringSelection(txt);
        clip.setContents(trans, this);
    }

    void doPaste()
    {
  ctxt = null;
        Transferable toPaste = clip.getContents(this);
        if (toPaste != null)
        {
            try
            {
                ctxt = (String)toPaste.getTransferData(
                    DataFlavor.stringFlavor);
            }
            catch (Exception e)
            {
             System.out.println("Error -- " + e.toString());
   }
        }

    }

    public void lostOwnership(Clipboard clip,
        Transferable contents) {
    }
}

Monday, November 26, 2012

Nesting Interfaces



Interfaces may be nested within classes and within other interfaces.[34] This reveals a number of very interesting features:
//: c08:nesting:NestingInterfaces.java
package c08.nesting;

class A {
  interface B {
    void f();
  }
  public class BImp implements B {
    public void f() {}
  }
  private class BImp2 implements B {
    public void f() {}
  }
  public interface C {
    void f();
  }
  class CImp implements C {
    public void f() {}
  }
  private class CImp2 implements C {
    public void f() {}
  }
  private interface D {
    void f();
  }
  private class DImp implements D {
    public void f() {}
  }
  public class DImp2 implements D {
    public void f() {}
  }
  public D getD() { return new DImp2(); }
  private D dRef;
  public void receiveD(D d) {
    dRef = d;
    dRef.f();
  }
}

interface E {
  interface G {
    void f();
  }
  // Redundant "public":
  public interface H {
    void f();
  }
  void g();
  // Cannot be private within an interface:
  //! private interface I {}
}

public class NestingInterfaces {
  public class BImp implements A.B {
    public void f() {}
  }
  class CImp implements A.C {
    public void f() {}
  }
  // Cannot implement a private interface except
  // within that interface's defining class:
  //! class DImp implements A.D {
  //!  public void f() {}
  //! }
  class EImp implements E {
    public void g() {}
  }
  class EGImp implements E.G {
    public void f() {}
  }
  class EImp2 implements E {
    public void g() {}
    class EG implements E.G {
      public void f() {}
    }
  }
  public static void main(String[] args) {
    A a = new A();
    // Can't access A.D:
    //! A.D ad = a.getD();
    // Doesn't return anything but A.D:
    //! A.DImp2 di2 = a.getD();
    // Cannot access a member of the interface:
    //! a.getD().f();
    // Only another A can do anything with getD():
    A a2 = new A();
    a2.receiveD(a.getD());
  }
} ///:~
The syntax for nesting an interface within a class is reasonably obvious, and just like non-nested interfaces, these can have public or package-access visibility. You can also see that both public and package-access nested interfaces can be implemented as public, package-access, and private nested classes. 
As a new twist, interfaces can also be private, as seen in A.D (the same qualification syntax is used for nested interfaces as for nested classes). What good is a private nested interface? You might guess that it can only be implemented as a private inner class as in DImp, but A.DImp2 shows that it can also be implemented as a public class. However, A.DImp2 can only be used as itself. You are not allowed to mention the fact that it implements the private interface, so implementing a private interface is a way to force the definition of the methods in that interface without adding any type information (that is, without allowing any upcasting). 
The method getD( ) produces a further quandary concerning the private interface: It’s a public method that returns a reference to a private interface. What can you do with the return value of this method? In main( ), you can see several attempts to use the return value, all of which fail. The only thing that works is if the return value is handed to an object that has permission to use it—in this case, another A, via the receiveD( ) method. 
Interface E shows that interfaces can be nested within each other. However, the rules about interfaces—in particular, that all interface elements must be public—are strictly enforced here, so an interface nested within another interface is automatically public and cannot be made private. 
NestingInterfaces shows the various ways that nested interfaces can be implemented. In particular, notice that when you implement an interface, you are not required to implement any interfaces nested within. Also, private interfaces cannot be implemented outside of their defining classes. 
Initially, these features may seem like they are added strictly for syntactic consistency, but I generally find that once you know about a feature, you often discover places where it is useful. 

Tuesday, September 25, 2012

IP address of localhost from Java Program:

Java networking API provides method to find IP address of localhost from Java program by using java.net. InetAddress class. It’s rare when you need IP address for localhost in Java program. Mostly I used Unix command to find IP address of localhost. For all practical purpose where program doesn’t need IP address but you need to troubleshoot any networking issues, Use DOS or windows command or Use Linux commands. Recently one of my friend faced this question in a core Java interview, where they are expecting Java developer with some socket programming experience, But until you know or you have done it before its hard to answer this fact based question, which motivates me to write this post. In this Java tutorial we will see How to find IP address of localhost from Java program. By the way it’s also good to remember list of Unix networking commands to troubleshoot any networking issues related to Java application in Unix environment.

IP Address of localhost from Java program

How to find IP address of localhost in Java program
As I said InetAddress from java.net package is used to represent an IP address in Java. an IP address is a 32 or 128 bit unsigned number used by IP protocol which is backbone of many popular protocols like TCP and UDP. There are two kinds of IP address IPv4 and IPv6 and IP address is associated with host which can be find by host name resolution process. Hostname resolution is performed by combining local machine configuration and network naming services such as the  DNS(Domain name system) and NIS(Network Information Service). InetAddress has method to resolve hostname and IP address and vice versa. Here is a complete code example of finding IP address from Java program.


import java.net.UnknownHostException;

/**
 * Simple Java program to find IP Address of localhost. This program uses

 * InetAddress from java.net package to find IP address.
 *
 * @author Javin Paul
 */
public class IPTest {
 
 
    public static void main(String args[]) throws UnknownHostException {
   
        InetAddress addr = InetAddress.getLocalHost();
     
        //Getting IPAddress of localhost - getHostAddress return IP Address

        // in textual format
        String ipAddress = addr.getHostAddress();
     
        System.out.println("IP address of localhost from Java Program: " + ipAddress);
     
        //Hostname
        String hostname = addr.getHostName();
        System.out.println("Name of hostname : " + hostname);
     
    }
 
}

Output:
IP address of localhost from Java Program: 190.12.209.123
Name of hostname : PCLOND3433


That’s all on How to find IP address of localhost from Java. Its nice tip to know but as I said java.net is not a common package like java.lang or java.util. Best way to learn and remember networking concepts in Java is to write some client server program which uses these essential classes.



Thursday, August 23, 2012

Retriving Check values from HTML to JSP


Sports.html
===========
<HTML>
<body>
<FORM method="POST" ACTION="sports.jsp">
<center>
Select your favorite sport(s): <br><br>
<table>
<tr>
    <td>
        <input TYPE=checkbox name=sports VALUE=Cricket>
    </td>   
    <td>   
        Cricket
    </td>
</tr>

<tr>
    <td>
        <input TYPE=checkbox name=sports VALUE=Football>
    </td>   
    <td>   
        Football
    </td>
</tr>

<tr>
    <td>
        <input TYPE=checkbox name=sports VALUE=Tennis>
    </td>   

    <td>   
        Tennis
    </td>
</tr>

<tr>
    <td>
        <input TYPE=checkbox name=sports VALUE=Rugby>
    </td>   

    <td>   
        Rugby
    </td>
</tr>

<tr>
    <td>
        <input TYPE=checkbox name=sports VALUE=Basketball>
    </td>   

    <td>   
        Basketball
    </td>
</tr>
</table>
<br> <INPUT TYPE=submit name=submit Value="Submit">
</center>
</FORM>
</BODY>
</HTML>


================
Sports.jsp
==========

<html>
<body>
<%! String[] sports; %>
<center>You have selected:
<%
   sports = request.getParameterValues("sports");
   if (sports != null)
   {
      for (int i = 0; i < sports.length; i++)
      {
         out.println ("<b>"+sports[i]+"<b>");
      }
   }
   else out.println ("<b>none<b>");
%>
</center>
</body>
</html>


output:
========


You have selected: Cricket Football Tennis