Monday, August 13, 2012
AWT:
Pros

1.  Speed: use of native peers speeds component performance. 
2. Applet Portability: most Web browsers support AWT classes so
AWT applets can run without the Java plugin.
3. Look and Feel: AWT components more closely reflect the look
and feel of the OS they run on.
Cons 
1. Portability: use of native peers creates platform specific
limitations. Some components may not function at all on some
platforms.
2. 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.
3.  Features: AWT components do not support features like icons and tool-tips.
Swing:
Pros 

1. Portability: Pure Java design provides for fewer platform specific
limitations.
2. 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.
3. Features: Swing supports a wider range of features like icons and
pop-up tool-tips for components.
4. Vendor Support: Swing development is more active. Sun puts
much more energy into making Swing robust.
5. 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
1. Applet Portability: Most Web browsers do not include the Swing
classes, so the Java plugin must be used.
2. 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.
3. 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.
Tuesday, August 7, 2012
This post is for all who has just started learning java or planning to do so. If you are from a C/C++ background then you will see that you didn't have to do all these things. You only had to install TurboC. But in Java it is necessary to set the path as without it you cannot compile or run a java program from command prompt if your source file resides in a different location as that of the compiler. At that situation windows won't be able to recognize javac as a command. Many of you will think that they can compile or run from an IDE like Eclipse,NetBeans,JCreator or BlueJ. But you will understand later that many things can't be done from here which can be done from your command prompt. Follow these steps carefully :




1 : Download and install the latest version of jdk(i.e. jdk7) in order to keep yourself always updated.
2 : Go to the location where you have installed jdk and look for bin folder. the path may look like this C:\Program Files\Java\jdk1.7.0\bin. Just copy this path from the location bar.
 3 : Now right click on My Computer and select Properties. It will open the system window.
  
4 : Now select Advanced System Settings from the window as shown
5 : Now select Environment variables
6 : Now look for Path under System Variable. Either double click it or select edit after choosing it.
7 : Now go the beginning and paste the path that you have copied earlier and then give a semi-colon.
WARNING : Do not change any other things and don't forget to give the semi-colon as either of this will cause system problems.
8 : Now press OK and give Administrator permission while doing it. You will have to press OK for two times to close the other dialogs that were already open. That's it. You have successfully set the path and compile from anywhere with javac command. If still windows can't recognize the javac command then you have done some mistake in the procedure. Plz check it.
Saturday, August 4, 2012
#include directive makes the compiler go to the C/C++ standard library and copy the code from the header files into the program. As a result, the program size increases, thus wasting memory and processor’s time.
import statement makes the JVM go to the Java standard library, execute the code there , and substitute the result into the program. Here, no code is copied and hence no waste of memory or processor’s time.hence import is an efficient mechanism than #include.
Friday, August 3, 2012
Today I am going to post a program that will create bubbles or a bubbling effect. Here I have used Ellipse2D class. A method calculates random coordinates,sizes and strokes of the ellipses. The size of the ellipses goes on increasing till it reaches its maximum value after which it starts from beginning. Each ellipse reaches its maximum size at different times. Each repainting is done after sleep of every 50ms. Related video is given below
Here is the code for you

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

public class Bubbles extends JPanel{
  
    private Ellipse2D.Float[] ellipses;
    private double esize[];
    private float estroke[];
    private final double MAX_SIZE=40;
   
    public Bubbles() {
        ellipses = new Ellipse2D.Float[75];
        esize    = new double[ellipses.length];
        estroke  = new  float[ellipses.length];
        for (int i = 0; i < ellipses.length; i++) {
            ellipses[i] = new Ellipse2D.Float();
            getRandomXY(i, 20 * Math.random(),getWidth()-60,getHeight()-60);
        }
    }
    public void build(){
        while(true){
           for (int i = 0; i < ellipses.length; i++) {
            estroke[i] += 0.025f; //increasing stroke
            esize[i]++; //increasing size
            if (esize[i] > MAX_SIZE)
//new values if reaches maximum
                getRandomXY(i, 20 * Math.random(),getWidth()-60,getHeight()-60);
            else
                ellipses[i].setFrame(ellipses[i].getX(), ellipses[i].getY(),
                                     esize[i], esize[i]);
           }
           repaint();
//repainting
            try {
               Thread.sleep(50);
//sleeping
             }catch (Exception ex) {}
        }
    }
    public void getRandomXY(int i, double size, int w, int h) {
        esize[i] = size;
        estroke[i] = 1.0f;
//setting size.strokes,coordinates
        double x = Math.random() * (getWidth()-(MAX_SIZE/2));
        double y = Math.random() * (getHeight()-(MAX_SIZE/2));
        ellipses[i].setFrame(x, y, size, size);
//setting ellipse
    }
   
    @Override
    public void paintComponent(Graphics g){
        Graphics2D g2d=(Graphics2D)g;
       
//clearing previous trails
        g2d.setColor(Color.black);
        g2d.fillRect(0,0,this.getWidth(),this.getHeight());
        for (int i = 0; i < ellipses.length; i++) {              
               g2d.setStroke(new BasicStroke(estroke[i]));
               int red=(int)(Math.random()*256);
               int green=(int)(Math.random()*256);
               int blue=(int)(Math.random()*256);
               g2d.setColor(new Color(red,green,blue));
               g2d.draw(ellipses[i]);
//drawing ellipses
        }
    }
    public static void main(String[] args) {
        JFrame f=new JFrame("Bubbles");
        Bubbles b=new Bubbles();
        f.getContentPane().add(b);
        f.setSize(350,350);
        f.setVisible(true);
        f.setLocationRelativeTo(null);
        f.setDefaultCloseOperation(f.EXIT_ON_CLOSE);
        b.build();
    }
}
You can also download source file from below links
DOWNLOAD the source from Mediafire
DOWNLOAD the source from 4shared 
Thursday, August 2, 2012
Today I will post how to continously rotate a text i.e string in Java Graphics2D. As you know that there are 4 types of transformation available in Java which are translation,rotation,scaling and shearing. Here I will use translation and rotation for this purpose. The text will be placed exactly at the center of the screen such that mid-point of text and screen coincide. Then the text will be rotated with screen center as the anchor point of rotation. Video of output is given here

Here is the code for you ->

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

public class RotateText extends JPanel{
    static int angdeg=0;
  
    @Override
    public void paint(Graphics g){
        Graphics2D g2d = (Graphics2D) g;
        g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING,                         RenderingHints.VALUE_ANTIALIAS_ON);
         g2d.setColor(Color.white); //
to remove trail of painting
         g2d.fillRect(0,0,getWidth(),getHeight());
         Font font =  new Font("serif",Font.BOLD,50);
         g2d.setFont(font); 
//setting font of surface
         FontRenderContext frc = g2d.getFontRenderContext();
         TextLayout layout = new TextLayout("JAVA", font, frc);
        
//getting width & height of the text
         double sw = layout.getBounds().getWidth();
         double sh = layout.getBounds().getHeight();
        
//getting original transform instance
        AffineTransform saveTransform=g2d.getTransform();
        g2d.setColor(Color.black);
        Rectangle rect = this.getBounds();
        //
drawing the axis
        g2d.drawLine((int)(rect.width)/2,0,(int)(rect.width)/2,rect.height);
        g2d.drawLine(0,(int)(rect.height)/2,rect.width,(int)(rect.height)/2);
        AffineTransform affineTransform = new AffineTransform();    /*
creating instance set the translation to the mid of the component*/
       affineTransform.setToTranslation((rect.width)/2,(rect.height)/2);
      
//rotate with the anchor point as the mid of the text
       affineTransform.rotate(Math.toRadians(angdeg), 0, 0);
       g2d.setTransform(affineTransform);
       g2d.drawString("JAVA",(int)-sw/2,(int)sh/2);
       g2d.setTransform(saveTransform); //
restoring original transform
    }
   
    public static void main(String[] args) throws Exception{
         JFrame frame = new JFrame("Rotated text");
         RotateText rt=new RotateText();
        frame.add(rt);
        frame.setSize(500, 500);
   frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
      frame.setLocationRelativeTo(null);
      frame.setVisible(true);
      while(true){
             Thread.sleep(10);
//sleeping then increasing angle by 5
             angdeg=(angdeg>=360)?0:angdeg+5; //
             rt.repaint();
//repainting the surface
         }
    }
}


You can also download full source from below links

DOWNLOAD the source from Mediafire 
DOWNLOAD the source from 4shared 
Wednesday, August 1, 2012
Today I am going to post a program to draw partially transparent image using Graphics2D in Java. In this example I am going to paint the background first by drawing ellipses with different colors .The image is broken into tiles using BufferedImage and each tile is given a separate transparency(alpha value) and then drawn above the background. Screenshots are given below
Original Image
Transparent Image
--------------------------------------------------------------------------------------------------------------------------
 SOURCE CODE
--------------------------------------------------------------------------------------------------------------------------
import java.awt.*;
import java.awt.geom.*;
import java.awt.image.BufferedImage;
import java.io.*;
import javax.swing.*;
import com.sun.image.codec.jpeg.*;

public class TransparentImage extends JPanel {
     private BufferedImage mImage;
     public static void main(String[] args) {
       try {
         String filename = "Image.jpeg";
         JFrame f = new JFrame("TransparentImage v1.0");
         TransparentImage showOff = new TransparentImage(filename);
         f.getContentPane().add(showOff);
         f.setSize(f.getPreferredSize());
         f.setResizable(false);
         f.setDefaultCloseOperation(f.EXIT_ON_CLOSE);
         f.setVisible(true);
       }catch (Exception e) {
           System.out.println(e);
           System.exit(0);
       }
  }
  public TransparentImage(String filename) throws Exception{
        
// Get the specified image.
         InputStream in = getClass().getResourceAsStream(filename);
         JPEGImageDecoder decoder = JPEGCodec.createJPEGDecoder(in);
         mImage = decoder.decodeAsBufferedImage();
         in.close();
        
// Set our size to match the image's size.
         setPreferredSize(new Dimension((int)mImage.getWidth(), (int)mImage.getHeight()));
    }
   
    @Override
    public void paintComponent(Graphics g) {
        Graphics2D g2 = (Graphics2D)g;
       
// Turn on antialiasing
 g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING,RenderingHints.VALUE_ANTIALIAS_ON);
        drawBackground(g2);
        drawImageTile(g2);
    }
   
    private void drawBackground(Graphics2D g2) {
       
// Draw circles of different colors
        int side = 45;
        int width = getSize().width;
        int height = getSize().height;
        Color[] colors = { Color.yellow, Color.cyan, Color.orange,
                      Color.pink, Color.magenta, Color.lightGray };
        for (int y = 0; y < height; y += side) {
            for (int x = 0; x < width; x += side) {
              Ellipse2D ellipse = new Ellipse2D.Float(x, y, side, side);
              int index = (x + y) / side % colors.length;
              g2.setPaint(colors[index]);
              g2.fill(ellipse);
            }
        }
    }
    
    private void drawImageTile(Graphics2D g2) {
         int side = 36;
         int width = mImage.getWidth();
         int height = mImage.getHeight();
         for (int y = 0; y < height; y += side) {
            for (int x = 0; x < width; x += side) {
              
// Calculate an appropriate transparency value
               float xBias = (float)x / (float)width;
               float yBias = (float)y / (float)height;
               float alpha = 1.0f - Math.abs(xBias - yBias);
               g2.setComposite(AlphaComposite.getInstance(
AlphaComposite.SRC_OVER, alpha));
               
// Draw the subimage
                int w = Math.min(side, width - x);
                int h = Math.min(side, height - y);
                BufferedImage tile = mImage.getSubimage(x, y, w, h);
                g2.drawImage(tile, x, y, null);
            }
         }
        
// Reset the composite.
 g2.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_OVER));
     }
}

NOTE : in order to run this program perfectly you must have a Image.jpeg file in the same directory as that of your java file.
--------------------------------------------------------------------------------------------------------------------------
RELATED POSTS
--------------------------------------------------------------------------------------------------------------------------
 Change brightness of image using RescaleOp

Total Pageviews

Followers


Labels

Popular Posts

free counters