Friday, 27 July 2012

Important News to all followers

Over 150+ requests have come to me via email to set up a seperarte blog that deals only with java codes. So keeping in mind of all your requests I have decided to set up a new blog that will deal only with Java programs. This blog will contain posts covering most of the topics of core java and their related codes to help you out about most of the topics. So from now on you can get all related posts on my new blog at Java Code House( But I will still continue posting on this blog.

Thursday, 5 July 2012

Rotate Text in Java using Graphics2D

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. 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;
    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
         Font font =  new Font("serif",Font.BOLD,50);
//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();
        Rectangle rect = this.getBounds();
drawing the axis
        AffineTransform affineTransform = new AffineTransform(); //
creating instance
       //set the translation to the mid of the component
//rotate with the anchor point as the mid of the text
       affineTransform.rotate(Math.toRadians(angdeg), 0, 0);
       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.setSize(500, 500);
//sleeping then increasing angle by 5
             angdeg=(angdeg>=360)?0:angdeg+5; //
//repainting the surface