3/19/2015

How to print asp.net panel contents using javascript

How to print asp.net panel contents using javascript



In this article explained how to print the contents of ASP.Net Panel control using JavaScript.
< html xmlns="http://www.w3.org/1999/xhtml">
< head>
< title>< /title >
        < script type = "text/javascript">
        function PrintPanel() {
        var panel = document.getElementById("ctl00_ContentPlaceHolder1_Panel1<%=Panel1.ClientID %>");
        var printWindow = window.open('', '', 'height=400,width=800');
        printWindow.document.write('');
        printWindow.document.write('');
        printWindow.document.write(panel.innerHTML);
        printWindow.document.write('');
        printWindow.document.close();
        setTimeout(function () {
                                                printWindow.print();
                                            }, 500);
        return false;
        }
        < /script>
< /head>
< body>
        < form id="form1" >
        < asp : Panel id="Panel1" >
                < span style="font-size: 10pt; font-weight:bold; font-family: Arial">HI ,
                    This is < span style="color: #18B5F0">EasyWay Programming. < /span>
                    EasywayProgramming.com
                    easywayprogramming.blogspot.in < /span>
        < /asp:Panel>

        < asp:Button ID="btnPrint" Text="Print" OnClientClick = "return PrintPanel();" />
        < /form>
< /body>
< /html>

In the above HTML Markup has an ASP.Net Panel control Panel1 whose contents needs to be printed and an ASP.Net Button btnPrint which has an OnClientClick event which will call the JavaScript method PrintPanel() to print the contents of the Panel

3/18/2015



Storage classes in C Programming


A storage class defines the scope(visibility) and liftime of variables and/or functions within a C program. These specifiers precede the type that they modify. There are following storage classes that can be used in c program.
  • auto
  • register
  • static
  • extern
The auto Storage Class :
        The auto storage class is default storage class of all local variables.
    {
           int sum;
           auto int sum1;
    }
      The example above defines two variables with the same storage class, auto can only be used within functions, i.e., local variables.

The register Storage Class :
        The register storage class is used to define local variables that should be stored in a register instead of RAM. This means that variable has a maximum size equal to the register size(usually one word).
    {
           register int sum;
    }
      The register should only be used for variables that requires quick access such as counters. Is should also be noted that defining 'register' does not mean that the variable will be stored in a register. It means that it MIGHT be stored in register depending on hardware and implementation restrictions.

The static Storage Class :
        The static storage class iinstruct compiler to keep a local variables in existance during the lifetime of the programm istead of creating and destroying it each time it comes into and goes out of scope. Therefore making local variables static allows them to maintain their values between function calls.
The static modifier may also applied to global variables. When this is done, it causes that variable scope to be resricted to the file in which it is declared.

#include
/* function declaration */
void func();
static int count = 5; /* global variable */

main()
{
while(count--)
    {
           func();
    }
}
/* function declaration */
void func()
{
static int i = 5; /* local static variable */
i++;

printf(" i is %d and count is %d\n", i, count);

      When the above code is compiled and executed, it produces the following result:
i is 6 and count is 4
i is 7 and count is 3
i is 8 and count is 2
i is 9 and count is 1
i is 10 and count is 0

The extern Storage Class :
        The extern storage class is used to give reference of global variables that is visible to ALL the program files. When u use 'extern', the variable cannot be initialized as all it does is point the variable name at a storage location that has been previously defined.
When u have multiple files and you define a global variable or function, which will be used in other files also, then extern will be used in another file to give reference of defined variable or function in another file. Example is as below.
    {
           register int sum;
    }
      The register should only be used for variables that requires quick access such as counters. Is should also be noted that defining 'register' does not mean that the variable will be stored in a register. It means that it MIGHT be stored in register depending on hardware and implementation restrictions.

Datatypes in C Programming easyway

Datatypes in C easyway:

C has a concept of 'data types' which are used to define a variable before its use. The definition of a variable will assign storage for the variable and define the type of data that will be held in the location.
The value of a variable can be changed any time. C has the following basic built-in datatypes.
  • int
  • float
  • double
  • char
Please note that there is not a boolean data type. C does not have the traditional view about logical comparison, but thats another story.
int - data type
is used to define integer numbers.
{
    int Count;
    Count = 5;
}
float - data type
float is used to define floating point numbers.
{
    float Miles;
    Miles = 5.6;
}
double - data type
 double is used to define BIG floating point numbers. It reserves twice the storage for the number. On PCs this is likely to be 8 bytes.
{
    double Atoms;
    Atoms = 2500000;
}
char - data type
char defines characters.
{
    char Letter;
    Letter = 'x';
}
Modifiers The data types explained above have the following modifiers.
  • short
  • long
  • signed
  • unsigned
          modifiers define the amount of storage allocated to the variable. The amount of storage allocated is not cast in stone. ANSI has the following rules:    
                    short int <=        int  <= long int
                          float <= double  <= long double
What this means is that a 'short int' should assign less than or the same amount of storage as an 'int' and the 'int' should be less or the same bytes than a 'long int'. What this means in the real world is:

                            Type       Bytes                     Range
---------------------------------------------------------------------

                            short int     2                 -32,768  ->  +32,767                 (32kb)
            unsigned short int      2                           0  ->  +65,535                 (64Kb)
                     unsigned int      4                           0  ->  +4,294,967,295     ( 4Gb)
                                     int     4     - 2,147,483,648  ->  +2,147,483,647    ( 2Gb)
                             long int     4      -2,147,483,648  ->  +2,147,483,647    ( 2Gb)
                      signed char     1                       -128  ->  +127
                  unsigned char     1                            0  ->  +255
                                  float     4
                              double     8
                      long double     12

These figures only apply to todays generation of PCs. Mainframes and midrange machines could use different figures, but would still comply with the rule above.
You can find out how much storage is allocated to a data type by using the sizeof operator discussed in Operator Types Session.
Here is an example to check size of memory taken by various datatypes.
int main()
{
    printf("sizeof(char) == %d\n", sizeof(char));
    printf("sizeof(short) == %d\n", sizeof(short));
    printf("sizeof(int) == %d\n", sizeof(int));
    printf("sizeof(long) == %d\n", sizeof(long));
    printf("sizeof(float) == %d\n", sizeof(float));
    printf("sizeof(double) == %d\n", sizeof(double));
    printf("sizeof(long double) == %d\n", sizeof(long double));
    printf("sizeof(long long) == %d\n", sizeof(long long));

    return 0;
}
Qualifiers
A type qualifier is used to refine the declaration of a variable, a function, and parameters, by specifying whether:
The value of a variable can be changed.
The value of a variable must always be read from memory rather than from a register
Standard C language recognizes the following two qualifiers:
  • const
  • volatile
The const qualifier is used to tell C that the variable value can not change after initialisation.
const float pi=3.14159;
Now pi cannot be changed at a later time within the program.
Another way to define constants is with the #define preprocessor which has the advantage that it does not use any storage
The volatile qualifier declares a data type that can have its value changed in ways outside the control or detection of the compiler (such as a variable updated by the system clock or by another program). This prevents the compiler from optimizing code referring to the object by storing the object's value in a register and re-reading it from there, rather than from memory, where it may have changed. You will use this qualifier once you will become expert in "C". So for now just proceed.

What are Arrays:
We have seen all baisc data types. In C language it is possible to make arrays whose elements are basic types. Thus we can make an array of 10 integers with the declaration.
    int x[10];
The square brackets mean subscripting; parentheses are used only for function references. Array indexes begin at zero, so the elements of x are:
Thus Array are special type of variables which can be used to store multiple values of same data type. Those values are stored and accessed using subscript or index.
Arrays occupy consecutive memory slots in the computer's memory.
    x[0], x[1], x[2], ..., x[9]
If an array has n elements, the largest subscript is n-1.
Multiple-dimension arrays are provided. The declaration and use look like:

    int name[10] [20];
    n = name[i+j] [1] + name[k] [2];

Subscripts can be arbitrary integer expressions. Multi-dimension arrays are stored by row so the rightmost subscript varies fastest. In above example name has 10 rows and 20 columns.

Same way, arrays can be defined for any data type. Text is usually kept as an array of characters. By convention in C, the last character in a character array should be a `\0' because most programs that manipulate character arrays expect it. For example, printf uses the `\0' to detect the end of a character array when printing it out with a `%s'.

Here is a program which reads a line, stores it in a buffer, and prints its length (excluding the newline at the end).

main( ) {
    int n, c;
    char line[100];
    n = 0;
    while( (c=getchar( )) != '\n' ) {
    if( n < 100 )
    line[n] = c;
    n++;
    }
    printf("length = %d\n", n);
}

Array Initialization
As with other declarations, array declarations can include an optional initialization
Scalar variables are initialized with a single value
Arrays are initialized with a list of values
The list is enclosed in curly braces

int array [8] = {2, 4, 6, 8, 10, 12, 14, 16};
The number of initializers cannot be more than the number of elements in the array but it can be less in which case, the remaining elements are initialized to 0.if you like, the array size can be inferred from the number of initializers by leaving the square brackets empty so these are identical declarations:
int array1 [8] = {2, 4, 6, 8, 10, 12, 14, 16};
int array2 [] = {2, 4, 6, 8, 10, 12, 14, 16};
An array of characters ie string can be initialized as follows:
char string[10] = "Hello";

9/27/2012

How to create a jar file of application created in java

 easywayprogramming.com how to create jar file of application in java

Step 1:- Copy all the class files & file & folders required for application in folder

Step 2:- Setting environmental variable
             Open command prompt. Go to folder where your application exists.
             Set environmental variable by executing following command
             set path="c:/program files/ java/ jdk 1.5/ bin"; 
where path string is path of jdk/bin installed in your PC

Step 3:- Creating a jar file:
             Execute following command at command prompt.
             jar cvf application_name.jar *.*
             press enter. Your jar file is created.

Step 4:- Now open that jar file with winrar.
             Open manifest.mf file in notepad. manifest.mf file exists in folder META-INF folder. Write following line in last of file
             Main-Class: Name of first opening frame main class file of your application without .class extension without extension, for example password screen.
             Example, Main-Class: password_screen

             save changes to file.

                Double click on jar file. See what happens.

8/29/2012

Example of Java 2D Graphics

easywayprogramming.com example of 2D graphics in java 

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

/** An example of drawing/filling shapes with Java 2D in
* Java 1.2 and later.
*/

public class ShapeExample extends JPanel
{
    private Ellipse2D.Double circle =
    new Ellipse2D.Double(10, 10, 350, 350);
    private Rectangle2D.Double square =
    new Rectangle2D.Double(10, 10, 350, 350);

    public void paintComponent(Graphics g)
    {
        //clear(g);
        Graphics2D g2d = (Graphics2D)g;
        g2d.setPaint(Color.black);
        g2d.fill(circle);
        g2d.draw(square);
    }

    /*protected void clear(Graphics g)
    {
        super.paintComponent(g);
    }*/

    protected Ellipse2D.Double getCircle()
    {
        return(circle);
    }

    public static void main(String[] args)
    {
        ShapeExample se=new ShapeExample();
        JFrame frm=new JFrame("Shape");
        Container c=frm.getContentPane();
        c.add(se);
        frm.setContentPane(c);
        frm.setSize(380,400);
        frm.setVisible(true);
    }
}

Java 2D graphics in Java

easywayprogramming.com 2D graphics in java 

public void paintComponent(Graphics g)
{
         // Clear background if opaque
          super.paintComponent(g);

        // Cast Graphics to Graphics2D
         Graphics2D g2d = (Graphics2D)g;

        // Set pen parameters
         g2d.setPaint(fillColorOrPattern);
         g2d.setStroke(penThicknessOrPattern);
         g2d.setComposite(someAlphaComposite);
         g2d.setFont(anyFont);
         g2d.translate(...);
         g2d.rotate(...);
         g2d.scale(...);
         g2d.shear(...);
         g2d.setTransform(someAffineTransform);

        // Allocate a shape
        SomeShape s = new SomeShape(...);

       // Draw shape
        g2d.draw(s); // outline
        g2d.fill(s); // solid
}

Drawing Shapes in 2D Graphics:
            With the AWT, you generally drew a shape by calling the drawXxx or fillXxx
method of the Graphics object. In Java 2D, you generally create a Shape object,
then call either the draw or fill method of the Graphics2D object, supplying the
Shape object as an argument. For example:
public void paintComponent(Graphics g)
{
        super.paintComponent(g);
        Graphics2D g2d = (Graphics2D)g;
        // Assume x, y, and diameter are instance variables.
       Ellipse2D.Double circle = new Ellipse2D.double(x, y, diameter, diameter);
       g2d.fill(circle);
...
}

Most of the Shape classes define both a Shape.Double and a Shape.Float version
of the class. Depending on the version of the class, the coordinate locations are
stored as either double precision numbers (Shape.Double) or single precision
numbers (Shape.Float). The idea is that single precision coordinates might be
slightly faster to manipulate on some platforms. You can still call the familiar
drawXxx methods of the Graphics class if you like; the Graphics2D object inherits
from the Graphics object. This approach is necessary for drawString and
drawImage and possibly is convenient for draw3DRect.
Shape Classes

public Ellipse2D.Float(float left, float top, float width,
float height)
public Ellipse2D.Double(double left, double top,
double width, double height)

These constructors create an ellipse bounded by a rectangle of dimension
width by height. The Ellipse2D class inherits from the Rectangular-
Shape class and contains the same methods as common to Rectangle2D and
RoundRectangle2D.

public GeneralPath()
A GeneralPath is an interesting class because you can define all the line segments
to create a brand-new Shape. This class supports a handful of methods
to add lines and Bézier (cubic) curves to the path: closePath, curveTo,
lineTo, moveTo, and quadTo. Appending a path segment to a General-
Path without first performing an initial moveTo generates an IllegalPath-
StateException. An example of creating a GeneralPath follows:
GeneralPath path = new GeneralPath();
path.moveTo(100,100);
path.lineTo(300,205);
path.quadTo(205,250,340,300);
path.lineTo(340,350);
path.closePath();

public Line2D.Float(float xStart, float yStart, float xEnd,
float yEnd)
public Line2D.Double(double xStart, double yStart,
double xEnd, double yEnd)

These constructors create a Line2D shape representing a line segment from
(xStart, yStart) to (xEnd, yEnd).

public QuadCurve2D.Float(float xStart, float yStart,
float pX, double pY,
float xEnd, float yEnd)
public QuadCurve2D.Double(double xStart, double yStart,
double pX, double pY,
double xEnd, double yEnd)

These constructors create a Shape representing a curve from (xStart,
yStart) to (xEnd, yEnd). The point (pX, pY) represents a control point
impacting the curvature of the line segment connecting the two end points.

public Rectangle2D.Float(float top, float left, float width,
float height)
public Rectangle2D.Double(double top, double left,
double width, double height)

These constructors create a Rectangle2D shape with the upper-left corner
located at (top, left) and a dimension of width by height.

public RoundRectangle2D.Float(float top, float left,
float width, float height,
float arcX, float arcY)
public RoundRectangle2D.Double(double top, double left,
double width, double height,
double arcX, double arcY)

These two constructors create a RectangleShape with rounded corners. The
upper-left corner of the rectangle is located at (top, left), and the dimension
of the rectangle is width by height. The arguments arcX and arcY represent
the distance from the rectangle corners (in the respective x direction and y
direction) at which the rounded curve of the corners start.

Most of the code examples throughout this chapter are presented as Java applications.
To convert the examples to applets, follow the given template:
import java.awt.*;
import javax.swing.*;
public class YourApplet extends JApplet {
public void init() {
JPanel panel = new ChapterExample();
panel.setBackground(Color.white);
getContentPane().add(panel);
}
}


Click here:
Example of java 2D graphics

7/14/2012

How to copy Mysql databse from one Computer to another / backup database using mysqldump

             We can take backup of MySQL database by using musqldump.
             We can transfer a MySQL database from one PC to another PC using mysqldump command. We have to create dump file of database to transfer database from one PC to another PC.
          MySQL databse is not portable database i.e. we cannot transfer it from one PC to another PC by copying and pasting it. We can use following method to transfer database.

1.   Creating a dumpfile from database/ Taking backup of MySQL database:
-  Open command prompt.
-  Execute following commands to change directory
>c:  “press enter”
>cd  program files/MySQL/MySQL Server 5.1/ bin “press enter”
>mysqldump -u root  -p databse_name > database_name.sql  “press enter”
  Enter password: password of MySQL

Copy sql file and paste it in PC where you want to transfer database.

.          2. Dumping sql file into database:-
          - Open MySQL  command line client command prompt.
          - Execute following command to create database.
                 >create database database_name;  “press enter”
Database name is must as that of your database _name.
Copy that sql file into location “c:/program files/MySQL/MySQL Server 5.1/bin”

          - Now open command prompt and execute following commands.
                >C: “press enter”
                >cd program files/MySQL/MySQL Server5.1/bin “press enter”
                >mysql –u root –p database_name < database_name.sql “press enter”

           Your database is created on PC.
           Now in MySQL command prompt check your database.  

7/11/2012

Java database connectivity with MySQL Server Databse

easywayprogramming.com java database connectivity with mysql database

Before executing following program follow instruction in following link:
database connectivity instruction 

my_sql.java
import java.sql.*;
import java.io.*;

public class my_sql
{
    public my_sql()
    {
        try
        {
            Class.forName("com.mysql.jdbc.Driver").newInstance();
            System.out.println("Driver loaded!!!!!!!!!");
            Connection con = DriverManager.getConnection("jdbc:mysql://localhost/employee","root","ashu");
            System.out.println("connection made!!!!!!!!!");
            Statement stmt = con.createStatement();
            ResultSet rs = stmt.executeQuery("select *from emp");

            while (rs.next())
            {
                 System.out.println(rs.getInt(1)+"\t"+rs.getString(2)+"\t\t\t"+rs.getString(3)+"\t\t\t"+rs.getString(4));
            } //end while

            con.close();
        }
        catch(Exception e)
        {
            e.printStackTrace();
        }
    }

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


click here: Back to Tricks/Solution

6/15/2012

sending image object through socket in java classic example


easywayprogramming.com sending image object through socket in java classic example 

       Sending image through socket connection in java is not so difficult task. Many peoples found it difficult to do it. many times we need to send images through network socket from one computer to another computer. Now we are going to see how we can send image through socket in java. It is very interesting.

client side coding:
GreetingClient.java
import java.net.*;
import java.io.*;
import java.awt.*;
import javax.imageio.*;

public class GreetingClient
{
    Image newimg;
    BufferedImage bimg;
    byte[] bytes;

   public static void main(String [] args)
   {
      String serverName = "localhost";
      int port = 6066;
      try
      {
         System.out.println("Connecting to " + serverName
                             + " on port " + port);
         Socket client = new Socket(serverName, port);

         System.out.println("Just connected to "
                      + client.getRemoteSocketAddress());

        DataInputStream in=new DataInputStream(client.getInputStream());
        System.out.println(in.readUTF());
        System.out.println(in.readUTF());

         DataOutputStream out =
                       new DataOutputStream(client.getOutPutStream());

         out.writeUTF("Hello from "
                      + client.getLocalSocketAddress());
         out.writeUTF("client: hello to server")

         ImageIcon img1=new ImageIcon("Ashish.jpg");
         Image img = img1.getImage();
         Image newimg = img.getScaledInstance(100, 120,  java.awt.Image.SCALE_SMOOTH);
         ImageIcon newIcon = new ImageIcon(newimg);

         bimg = ImageIO.read(new File("D:\adi-siddhi\DSC02503.JPG"));

         ImageIO.write(bimg,"JPG",client.getOutputStream());
         System.out.println("Image sent!!!!");
         client.close();
      }catch(IOException e)
      {
         e.printStackTrace();
      }
   }
}

severside coding:
GreetingSever.java
import java.net.*;
import java.io.*;

public class GreetingServer extends Thread
{
       private ServerSocket serverSocket;
       Socket server;

       public GreetingServer(int port) throws IOException, SQLException, ClassNotFoundException, Exception
       {
          serverSocket = new ServerSocket(port);
          serverSocket.setSoTimeout(180000);
       }

       public void run()
       {
           while(true)
          {
               try
               {
                  server = serverSocket.accept();
                  DataInputStream din=new DataInputStream(server.getInputStream());
                  DataOutputStream dout=new DataOutputStream(server.getOutputStream());

                  dout.writeUTF("server: -i am greeting server");
                  dout.writeUTF("server:- hi! hello client");

                  System.out.println(din.readUTF());
                  System.out.println(din.readUTF());

                  BufferedImage img=ImageIO.read(ImageIO.createImageInputStream(socket.getInputStream()));

                  System.out.println("Image received!!!!");
                  //lblimg.setIcon(img);
              }
             catch(SocketTimeoutException st)
             {
                   System.out.println("Socket timed out!");
                  break;
             }
             catch(IOException e)
             {
                  e.printStackTrace();
                  break;
             }
             catch(Exception ex)
            {
                  System.out.println(ex);
            }
          }
       }
      
       public static void main(String [] args) throws IOException, SQLException, ClassNotFoundException, Exception
       {
              //int port = Integer.parseInt(args[0]);
              Thread t = new GreetingServer(6066);
              t.start();
       }
}

Run the program as it is. first run greetingserver. java,  then greetingclient.java.

http://easywayprogramming.com/Java/sending-image-object-through-socket-in-java-classic-example.aspx?code=6&lan=j 

Follow the important rules given in post

6/10/2012

drawing image through graphics in java

 easywayprogramming.com drawing image through graphics in java

we are going to see how we can draw a image into frame using graphics

print.java

import java.awt.Canvas;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.PrintJob;
import java.awt.Toolkit;
import java.awt.Color;

import javax.swing.JFrame;
import java.util.Properties;

public class print extends JFrame
{
      PrintCanvas my_canvas = new PrintCanvas();

      public print()
      {
        add("Center", my_canvas);
        setSize(500, 500);
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        setTitle("Ashish Wagh");
        setVisible(true);
        String name = "Ashish Wagh";

        Properties properties = new Properties();
        PrintJob pj = Toolkit.getDefaultToolkit().getPrintJob(print.this, name, properties);
        if (pj != null)
        {
              my_canvas.printAll(pj.getGraphics());
              pj.end();
        }
      }

      public static void main(String args[])
      {
        print p= new print();
      }
}

class PrintCanvas extends Canvas
{
  public void paint(Graphics g)
  {
    Dimension size = getSize();
    int width = size.width;
    int height = size.height;
    int x1 = (int) (width * 0.1);
    int x2 = (int) (width * 0.9);
    int y1 = (int) (height * 0.1);
    int y2 = (int) (height * 0.9);

    g.setColor(Color.YELLOW);
    g.fillRect(x1, y1, x2 - x1, y2 - y1);
    g.setColor(Color.GREEN);
    g.drawRect(x1, y1, x2 - x1, y2 - y1);
    g.drawOval(x1, y1, x2 - x1, y2 - y1);
    g.setColor(Color.RED);
    g.drawLine(x1, y1, x2, y2);
    g.drawLine(x2, y1, x1, y2);
    g.setColor(Color.BLACK);
    String text = "Ashish!";
    text += text;
    text += text;
    g.drawString(text, x1, (int) ((y1 + y2) / 2));
    g.drawString("Ashish",(int)(width/2)-(width/20), (int)(y1+(y2/4)));
    g.drawString("Ashish",(int)(width/2)-(width/20), (int)(y1+((3*y2)/4)));

    Image img = new ImageIcon("Ashish_photo.JPG").getImage();    
    Image newimg = img.getScaledInstance(100, 120,  java.awt.Image.SCALE_SMOOTH); 
    ImageIcon newIcon = new ImageIcon(img);    
    g.drawImage(newIcon.getImage(), 250, 70, 100,120, null);
    g.dispose();
  }
}

        In above example we, create a image icon of photo and get image from that photo. Then we create new image from old image by using method getScaledInstance(new Width, new height, java.awt.Image.SCALE_SMOOTH);
        Then we create new image icon from new image, and get image from that ImageIcon.
       now using drawImage(image, position x, position y, new width, new height, null) method in graphics we can draw that image.

how to resize ImageIcon in java

 easywayprogramming.com how to resize imageicon in java

When we apply image icon to any component like button, label or panel, it not apply properly because of size of that image. We can resize that image icon in two ways. 

1. first way: 
Image img = myIcon2.getImage(); Image newimg = img.getScaledInstance(230310,  java.awt.Image.SCALE_SMOOTH);  
newIcon = new ImageIcon(newimg); 

2. second way: 

 Image img = myIcon2.getImage();  BufferedImage bi = new BufferedImage(img.getWidth(null), img.getHeight(null), BufferedImage.TYPE_INT_ARGB);  
newIcon = new ImageIcon(bi);

5/27/2012

All about arrays in java

  •  Arrays are way to store a list of items. Each slot of an array holds an individual element, and you can place into or change the contents of those slots as you need to.
  • Arrays can contain any type of element value(primitive types or objects), but you cant store different types in single array. You can have array of integers, or arrays of string.
  • To create an array in Java, you use three steps :
  1.        Declare a variable to hold the array. 
  2.        Create a new array object and  assign it to the array variable.
  3.        Store things in that array. 

Declaring array variables:
  • The first step in creating an array is creating an variable that will hold the array, just as you would any other variable.
  • Array variables indicate the type of object the array will hold and the name of the array, followed by empty square brackets [].
  • Following are the examples of Array declarations:
                int values[];
                float cost[];
                String months[];
  • There is another way to declare the array allowed in java as shown below:
                String[] names;
                int[] numbers;

Creating array object:
         The second step is to create an array object and assign it to that variable. There are two ways to do this :
  • using new
  • Directly initializing the contents of that array
The first way is to use the new operator to create new instance of an array:
      int[] values=new values[10];
This will creates anew array of int with size10.
  • When you create a new array object using new, you must indicate how many slots that array will hold.
  • You can create & initialize array at same time. Instead of using new to create the new array object, enclose the elements of the array inside braces, separated by commas:
                   int[] values={1,2,3,4,5};
  • Each of the elements inside the braces must be of the same type as the variable that holds that array.
  • An array the size of the number of elements you've included will be automatically created for you.
Accessing array elements:
  • Once you have array with an initial values, you can test and change the values in each subscript of that array. To get a value stored within an array, use the array subscript expression:
                      arrayname[subscript];
  • The arrayname is the name of array. The subscript is index of array elements stored in array. Array subscript starts with 0. So an array with 10 elements has 10 array elements accessed using subscript 0 to 9.
  • Note that all array subscripts are checked to make sure that they are inside the boundaries of the array. Note the following two statements, for example:
                       String[] arr=new String[10];
                       arr[10]="Ashish";
  • A program with that last statement in it produces acompiler error at that linewhen you try to compile it. The array stored in arr has size as 10, the element at subscript 10 doesn't exist, and java compiler will check for that.
  • If the array subscript calculated  at run-time & ends up outside the boundaries of the array, the java interpreter also produces an error.
Changing array elements:
  • To assign a particular value array slot, merely put an assignment statement after the array access expression:
                            values[2]= 45;
                            months[3]="March";

Example of arrays:
//program of sorting of array
class IntSorting
{
         public static void main(String args[])
        {
                  int num[]={55,40,80,65,01,71};
                  int n=num.length;
                  System.out.print("Give list as :");
                  for(int i=0 ; i<n ; i++)
                          System.out.print(" "+num[i]);
                  System.out.println("\n");

                  for(int i=0; i<n ; i++)
                  {
                          for(int j=i+1; j<n; j++)
                          {
                                   if(num[i]>num[j])
                                    {
                                              int temp=num[i];
                                              num[i]=num[j];
                                              num[j]=temp;
                                    }
                          }
                  }

                  System.out.print("Sorted list: ");
                  for(int k=0; k<num.length; k++)
                          System.out.print(" "+num[k]);
                  System.out.println("\n");
        } 
}

Output:
Given list: 55 40 80 65 1 71
Sorted list: 1 40 55 65 71 80

5/23/2012

How to print contents of JFrame in java

easywayprogramming.com How to print contents of jframe in java
How to print contents of jframe in java?

Many developers found it difficult to print contents of jframe in java.
Following example shows how to do it.

print.java

import java.awt.Canvas;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.PrintJob;
import java.awt.Toolkit;
import java.awt.Color;

import javax.swing.JFrame;
import java.util.Properties;

public class print extends JFrame
{
      PrintCanvas my_canvas = new PrintCanvas();

      public print()
      {
        add("Center", my_canvas);
        setSize(500, 500);
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        setTitle("Ashish Wagh");
        setVisible(true);
        String name = "Ashish Wagh";

        Properties properties = new Properties();
        PrintJob pj = Toolkit.getDefaultToolkit().getPrintJob(print.this, name, properties);
        if (pj != null)
        {
              my_canvas.printAll(pj.getGraphics());
              pj.end();
        }
      }

      public static void main(String args[])
      {
        print p= new print();
      }
}

class PrintCanvas extends Canvas
{
  public void paint(Graphics g)
  {
    Dimension size = getSize();
    int width = size.width;
    int height = size.height;
    int x1 = (int) (width * 0.1);
    int x2 = (int) (width * 0.9);
    int y1 = (int) (height * 0.1);
    int y2 = (int) (height * 0.9);

    g.setColor(Color.YELLOW);
    g.fillRect(x1, y1, x2 - x1, y2 - y1);
    g.setColor(Color.GREEN);
    g.drawRect(x1, y1, x2 - x1, y2 - y1);
    g.drawOval(x1, y1, x2 - x1, y2 - y1);
    g.setColor(Color.RED);
    g.drawLine(x1, y1, x2, y2);
    g.drawLine(x2, y1, x1, y2);
    g.setColor(Color.BLACK);
    String text = "Ashish!";
    text += text;
    text += text;
    g.drawString(text, x1, (int) ((y1 + y2) / 2));
    g.drawString("Ashish",(int)(width/2)-(width/20), (int)(y1+(y2/4)));
    g.drawString("Ashish",(int)(width/2)-(width/20), (int)(y1+((3*y2)/4)));
    g.dispose();
  }
}

5/22/2012

socket programming java basic classic example

easywayprogramming.com Socket programming in java basic classic example

Here is the classic example of socket programming in java.
GreetingSever.java
import java.net.*;
import java.io.*;

public class GreetingServer extends Thread
{
       private ServerSocket serverSocket;
       Socket server;

       public GreetingServer(int port) throws IOException, SQLException, ClassNotFoundException, Exception
       {
          serverSocket = new ServerSocket(port);
          serverSocket.setSoTimeout(180000);
       }

       public void run()
       {
           while(true)
          {
               try
               {
                  server = serverSocket.accept();
                  DataInputStream din=new DataInputStream(server.getInputStream());
                  DataOutputStream dout=new DataOutputStream(server.getOutputStream());

                  dout.writeUTF("server: -i am greeting server");
                  dout.writeUTF("server:- hi! hello client");

                  System.out.println(din.readUTF());
                  System.out.println(din.readUTF());
              }
             catch(SocketTimeoutException st)
             {
                   System.out.println("Socket timed out!");
                  break;
             }
             catch(IOException e)
             {
                  e.printStackTrace();
                  break;
             }
             catch(Exception ex)
            {
                  System.out.println(ex);
            }
          }
       }
      
       public static void main(String [] args) throws IOException, SQLException, ClassNotFoundException, Exception
       {
              //int port = Integer.parseInt(args[0]);
              Thread t = new GreetingServer(6066);
              t.start();
       }
}

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

public class GreetingClient
{
   public static void main(String [] args)
   {
      String serverName = "localhost";
      int port = 6066;
      try
      {
         System.out.println("Connecting to " + serverName
                             + " on port " + port);
         Socket client = new Socket(serverName, port);

         System.out.println("Just connected to "
                      + client.getRemoteSocketAddress());

        DataInputStream in=new DataInputStream(client.getInputStream());
        System.out.println(in.readUTF());
        System.out.println(in.readUTF());

         DataOutputStream out =
                       new DataOutputStream(client.getOutPutStream());

         out.writeUTF("Hello from "
                      + client.getLocalSocketAddress());
         out.writeUTF("client: hello to server")

         client.close();
      }catch(IOException e)
      {
         e.printStackTrace();
      }
   }
}

**Important notes:
       in greeting client server-name should be "localhost" if client and server are running oh same machines.
       If server and client are on different machines then in client we write a server-name i.e. computer_name of machine on which server is running.
       port number defined on client & server should be same. that means client is connecting to port on server.
       port number on client and server should be greater than 1023 (port  > 1023), because ports 0 to 1023 are well known ports, are used for specific purpose.  

Now we see running process
1.  open command promt or jcreator.
     Compile GreetingServer.java file.
     If no error, then run GreetingServer class.

2. now open another command promt or jcreator
    compile GreetingClient.java file
    if no error, then run GreetingClient class.

see what happens!!!!!!!!!

click here: Socket programming in java theory

5/18/2012

Socket Programming in Java: Basics Theory

 easywayprogramming.com socket programming in java basics theory    

       Hi guys, socket programming in java founds difficult to many peoples. I tried to show it in simple way, so peoples can understand it. First we will see some basic theory.
   
       There are two communication protocols that we can use for socket programming.
                  1. TCP/IP Communication (Stream communication)
                  2. UDP/IP Communication (Datagram communication)

Datagram Communication:
       The datagram communication protocol, known as UDP (user datagram protocol), is a connectionless protocol, meaning that each time you send datagrams, you also need to send the local socket descriptor and the receiving socket's address. As you can tell, additional data must be sent each time a communication is made.

Stream Communication:
       The stream communication protocol known as TCP(transfer communication protocol), i a connection oriented protocol. In order to do communication over the TCP protocol, a connection must first be established between the pair of sockets. While one of the sockets listens for a connection request (server), the other asks for a connection (client). Once two sockets have been connected, they can be used to transmit data in both (or either one of the) directions.
        Now we focus on stream communication.

Socket:
       Socket is one end-point of two way communication channel between two programes that are running on network. A socket is bound to a port number so that the TCP layer can identify the application that data is destined to be sent. It is like end-point of tunnel or pipe-line.The java.net package provides two classes--Socket and ServerSocket--that implement the client side of the connection and the server side of the connection, respectively.

 Server: A server runs on a specific computer and has a socket that is bound to a specific port number. The server just waits, listening to the socket for a client to make a connection request.

 Client: The client knows the hostname of the machine on which the server is running and the port number on which the server is listening. To make a connection request, the client request to the server on the server's machine and port. The client also needs to identify itself to the server so it binds to a local port number that it will use during this connection. This is usually assigned by the system.





If everything goes well, the server accepts the connection. Upon acceptance, the server gets a new socket bound to the same local port and also has its remote endpoint set to the address and port of the client. It needs a new socket so that it can continue to listen to the original socket for connection requests while tending to the needs of the connected client. On the client side, if the connection is accepted, a socket is successfully created and the client can use the socket to communicate with the server.

Example: Socket programming in java: basic example