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);