Difficulty Rotating Text w/ Java 1.4

I've used the following code to rotate a line of text successfully
using Java 1.3. However, when I run the same code under 1.4, the
text is not rotated. Anyone have any idea why, and some suggestions
for a successful workaround?
Thanks in advance!
Jeff
import javax.swing.JFrame;
import java.awt.Container;
import java.awt.Color;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.geom.AffineTransform;
import java.awt.font.FontRenderContext;
import java.awt.font.TextLayout;
import java.awt.Font;
import javax.swing.JPanel;
public class AffineTransformTest extends JPanel
public void paintComponent(Graphics g)
super.paintComponent(g);
Graphics2D g2d = (Graphics2D)g;
AffineTransform af = new AffineTransform();
af.setToRotation(Math.PI/2);
FontRenderContext renderContext = new FontRenderContext(af, false, false);
TextLayout layout = new TextLayout("This text should be rotated 90 degrees from horizontal." , g2d.getFont(), renderContext);
layout.draw(g2d, 100, 50);
public static void main(String [] args)
AffineTransformTest app = new AffineTransformTest();
JFrame frame = new JFrame("Affine Transform Test");
frame.getContentPane().add(app);
frame.setSize(300,400);
frame.setVisible(true);
}

Apply both a translation and rotation transform to g2d, leaving the RenderContext transform null and the drawing coordinates 0,0.    public void paintComponent(Graphics g) {
        super.paintComponent(g);
        Graphics2D g2d = (Graphics2D) g;
        AffineTransform af = new AffineTransform();
        af.translate(100.,50.);
        af.rotate(Math.PI / 2);
        FontRenderContext renderContext = new FontRenderContext(null, false, false);
        g2d.transform(af);
        TextLayout layout =
            new TextLayout(
                "This text should be rotated 90 degrees from horizontal.",
                g2d.getFont(),
                renderContext);
        layout.draw(g2d, 0, 0);
    }Note that you can create the FontRenderContext outside of paintComponent since it never changes.

Similar Messages

  • Rotate text using java 1.1

    Hi...i need to rotate text using only java 1.1...no Affine Transformations.
    Does anyone ever had to do this?
    Please give some ideas.
    Thanks.

    Hrm. You could always create an extension of Label's paint that provides the super method with a Graphics object and then, in your implementation, paint the rotation yourself...

  • Java 3d rotating text snapshot problem

    Hi guys !
    I have searched for a method which captured a 3d rotating text and print it on the screen ,but i didn`t found it.
    I have to this exercise :
    Write a Java 3D program showing two panels and a button. The first panel displays a scene of a rotating 3D text string. When the button is clicked, the image of the 3D scene is captured and the still image is displayed in the second panel.
    Can anybody help me or write me the source code???
    thank you

    Only a fool will do your homework for you.
    But I can't help noticing that the assignment specifically mentions Java3d, and you're asking on an applet forum. It seems unlikely that you're supposed to implement your assignment as an applet.
    Most likely, the assignment tells you how to obtain Java3d. Either that or an earlier hand-out in your class says how to.
    You should re-read your assignment and other class notes, get the Java3D library, and then read the Java3D documentation. Write a simple "hello world" type program using Java3d. At that point, this assignment will probably be pretty simple for you.

  • How to Rotate Text 90 Degree?

    I tried to rotate text so that it reads from bottom to
    top of the screen (vertically). How to do it?
    I tried w/ Graphics2D and AffineTransform class but fail.
    Here is my code:
    AffineTransform af = new AffineTransform(0.0, 1.0, 1.0,
    0.0, 0.0, 0.0);
    Graphics2D newg = (Graphics2D) g;
    g.setTransform(af);
    g.drawString("Rotated Text", 70.0f, 70.0f);
    Anybody do text rotation please post reply.
    Thanks!

    Turns out the bug still persists, and I post new Q on
    this forum. Please check it out.
    But here is the my entire code, if you would like to see
    and try:
    import javax.swing.DefaultCellEditor;
    import javax.swing.JScrollPane;
    import javax.swing.SwingConstants;
    import javax.swing.JPanel;
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    import java.util.*;
    import java.text.NumberFormat;
    import java.text.DecimalFormat;
    import java.awt.Graphics2D;
    import java.awt.geom.AffineTransform;
    public class CompJFC
    static JFrame frame1;
    static final int cWidth = 500;
    static final int cHeight = 500;
    Object[] ctable = {"Usage Graph for Users",
    "Usage Graph for Servers",
    "Usage Graph for Appliances",
    "Top 20 Users (Last 30 Days)",
    "Top 20 Users (Last 60 Days)",
    "Top 20 Users (Last 90 Days)"};
    JComboBox ccombo = new JComboBox(ctable);
    JPanel panel1, panel2, panel3;
    JCanvas canvas;
    public class JCanvas extends JComponent
    Insets insideBorder;
    JCanvas()
    super();
    JCanvas(int cWidth, int cHeight)
    insideBorder = new Insets(cHeight-150, 50, 50, cWidth-60);
    public void paintComponent(Graphics g)
    super.paintComponent(g);
    Graphics2D g2 = (Graphics2D) g;
    AffineTransform af1 = g2.getTransform();
    int xp = insideBorder.left-35;
    int yp = insideBorder.top-100;
    AffineTransform af2 =
    AffineTransform.getRotateInstance(Math.toRadians(270), xp, yp);
    g2.setTransform(af2);
    g2.drawString("Number of Online Users", xp, yp);
    g2.setTransform(af1);
    public void AddComp()
    panel1 = new JPanel();
    panel1.add(ccombo);
    ccombo.addItemListener(new ItemListener()
    public void itemStateChanged(ItemEvent evt)
    String selected;
    panel2.remove(canvas);
    canvas = new JCanvas(cWidth, cHeight);
    panel2.add(canvas, BorderLayout.CENTER);
    panel2.repaint();
    frame1.setVisible(true);
    canvas = new JCanvas(cWidth, cHeight);
    panel2 = new JPanel(new BorderLayout());
    panel2.add(canvas, BorderLayout.CENTER);
    panel3 = new JPanel(new BorderLayout());
    panel3.add(panel1, BorderLayout.NORTH);
    panel3.add(panel2, BorderLayout.CENTER);
    JTabbedPane tpane = new JTabbedPane();
    tpane.addTab("Chart", panel3);
    frame1.getContentPane().add(tpane);
    public static void main(String args[])
    CompJFC jc = new CompJFC();
    frame1 = new JFrame("Swing GUI Exercise");
    frame1.setSize(cWidth, cHeight);
    frame1.setDefaultCloseOperation(frame1.EXIT_ON_CLOSE);
    frame1.getContentPane().setLayout(new BorderLayout());
    jc.AddComp();
    frame1.setVisible(true);

  • Rotating text

    is there a method that will rotate the text? I am new to java and cannot figure out how to do this. Help please!
    Mike

    Hi,
    Try doing a forum search for 'rotating text'. I tried it a minute ago, and came up with all kinds of information you might find useful.
    Hope that helps.

  • Drawing rotated text revisited.....

    Hello again,
    I've recently started fiddling with an app that had a method to draw Strings at given Points on a custom JComponent, now I'm trying to extend it to draw the same strings, but throw in an angle should the user choose to do so. But... now here's the part thats foxing me, I want the Point specified to be the center of the String....., i've had a couple of goes, but as soon as the rotation comes in, it goes pair shaped (not literally ;-) , metaphorically).
    Here's some of the code I'm working on, feel free to point bad coding and glaringly obvious problems! I'm aware it doesn't quite do "exactly what it says on the tin", but its definitely a step in the right direction. It should work, but it doesn't. Thoughts anyone?
    /** Method to draw a text label to a specified graphics context.
         @param g2 The graphics context to draw to.
         @param text The label text to draw.
         @param font The font in which to draw the label.
         @param color The color of the label.
         @param angle The angle at which to draw , 0 = horizontal, 90 = vertical.
         @param position The Point at which to draw the label.*/
    public static void drawLabel(Graphics2D g2, String text, Font font, Color color, int angle, Point position)
    //get x,y coordinates from Point
    int x = new Double(position.getX()).intValue();
    int y = new Double(position.getY()).intValue();
    //rotate the point by the required angle
    x = (new Double((x*Math.cos(Math.toRadians(angle)))-(y*Math.sin(Math.toRadians(angle)))).intValue());
    y = (new Double((-x*Math.sin(Math.toRadians(angle)))+(y*Math.cos(Math.toRadians(angle)))).intValue());
    // get the current transform
    AffineTransform startMatrix = g2.getTransform();
    // make a new one...
    AffineTransform rotationMatrix = new AffineTransform();
    // set the text layout
    TextLayout tl = new TextLayout(text,font,g2.getFontRenderContext());
    // rotate the shiny new transform
    rotationMatrix.rotate(Math.toRadians(angle));
    // appy it to g2
    g2.transform(rotationMatrix);
    //set the color of the label
    g2.setPaint(color);
    //draw the label
    tl.draw(g2,x,y);
    //restore the transform for g2
    g2.setTransform(startMatrix);
    }Also I haven't sorted the drawing relative to the center of the string bit yet, so any advice on how to do this would be great.
    Cheers,
    Tom

    This is straightforward, once you understand transforms. I'm surprised no one's answered this yet. Here's an example:
    import java.awt.*;
    import java.awt.event.*;
    import java.awt.font.*;
    import java.awt.geom.*;
    public class TestRotate extends Frame {
        public static void main(String[] args) {
            new TestRotate().setVisible(true);
        private TestRotate() {
            super("Rotated Text");
            addWindowListener(new WindowAdapter() {
                    public void windowClosing(WindowEvent e) {
                        System.exit(0);
            setFont(new Font("default", Font.PLAIN, 24));
            setSize(300, 300);
        public void paint(Graphics g) {
            Graphics2D g2d = (Graphics2D)g;
            TextLayout layout = new TextLayout(
                "This is a string to rotate",
                g2d.getFont(),
                g2d.getFontRenderContext());
            Insets ins = getInsets();
            Dimension dim = getSize();
            Point center = new Point(
                ins.left + (dim.width - ins.left - ins.right) / 2,
                ins.top + (dim.height - ins.top - ins.bottom) / 2);
            g2d.translate(center.x, center.y);
            g2d.rotate(Math.PI / 4);
            layout.draw(g2d, -layout.getAdvance() / 2, 0);

  • How to print a text in java?

    How to print a text in java?

    of corse, i have JTextField in my frame that i want to extract the text and print it on a paper with a printer.

  • How to print "Text" in JAVA(TM)....

    Does anyone know how to print "text" using Java?
    - Here's an example output...
    NOTE: # == 'empty spaces'
    --------------------------- <- Paper
    |###################|
    |####Welcome#########|
    |###################|
    |########to##########|
    |###########JAVA(TM)##|
    |###################|
    |#######Programming####|
    |###################|
    Please post a complete << SAMPLE CODE >> for printing the "text" (Welcome to JAVA(TM) Programming. Including the indentions. So it will not be like this...
    -------------------- <- Paper
    |Welcome |
    |to |
    |JAVA(TM) |
    |Programming |
    | |
    | |
    | |
    | |
    Thanks.

    Please read How To Ask Questions The Smart Way

  • How to output money number by text in java?

    How to output money number by text in java?
    Example: input: 1234 $
    output: one thousand two hundred thirty four dollar.

    try this...
    import java.text.DecimalFormat;
    public class EnglishNumberToWords {
      private static final String[] tensNames = {
        " ten",
        " twenty",
        " thirty",
        " forty",
        " fifty",
        " sixty",
        " seventy",
        " eighty",
        " ninety"
      private static final String[] numNames = {
        " one",
        " two",
        " three",
        " four",
        " five",
        " six",
        " seven",
        " eight",
        " nine",
        " ten",
        " eleven",
        " twelve",
        " thirteen",
        " fourteen",
        " fifteen",
        " sixteen",
        " seventeen",
        " eighteen",
        " nineteen"
      private static String convertLessThanOneThousand(int number) {
        String soFar;
        if (number % 100 < 20){
          soFar = numNames[number % 100];
          number /= 100;
        else {
          soFar = numNames[number % 10];
          number /= 10;
          soFar = tensNames[number % 10] + soFar;
          number /= 10;
        if (number == 0) return soFar;
        return numNames[number] + " hundred" + soFar;
      public static String convert(long number) {
        // 0 to 999 999 999 999
        if (number == 0) { return "zero"; }
        String snumber = Long.toString(number);
        // pad with "0"
        String mask = "000000000000";
        DecimalFormat df = new DecimalFormat(mask);
        snumber = df.format(number);
        // XXXnnnnnnnnn
        int billions = Integer.parseInt(snumber.substring(0,3));
        // nnnXXXnnnnnn
        int millions  = Integer.parseInt(snumber.substring(3,6));
        // nnnnnnXXXnnn
        int hundredThousands = Integer.parseInt(snumber.substring(6,9));
        // nnnnnnnnnXXX
        int thousands = Integer.parseInt(snumber.substring(9,12));   
        String tradBillions;
        switch (billions) {
        case 0:
          tradBillions = "";
          break;
        case 1 :
          tradBillions = convertLessThanOneThousand(billions)
          + " billion ";
          break;
        default :
          tradBillions = convertLessThanOneThousand(billions)
          + " billion ";
        String result =  tradBillions;
        String tradMillions;
        switch (millions) {
        case 0:
          tradMillions = "";
          break;
        case 1 :
          tradMillions = convertLessThanOneThousand(millions)
          + " million ";
          break;
        default :
          tradMillions = convertLessThanOneThousand(millions)
          + " million ";
        result =  result + tradMillions;
        String tradHundredThousands;
        switch (hundredThousands) {
        case 0:
          tradHundredThousands = "";
          break;
        case 1 :
          tradHundredThousands = "one thousand ";
          break;
        default :
          tradHundredThousands = convertLessThanOneThousand(hundredThousands)
          + " thousand ";
        result =  result + tradHundredThousands;
        String tradThousand;
        tradThousand = convertLessThanOneThousand(thousands);
        result =  result + tradThousand;
        // remove extra spaces!
        return result.replaceAll("^\\s+", "").replaceAll("\\b\\s{2,}\\b", " ");
       * testing
       * @param args
      public static void main(String[] args) {
        System.out.println("*** " + EnglishNumberToWords.convert(0));
        System.out.println("*** " + EnglishNumberToWords.convert(1));
        System.out.println("*** " + EnglishNumberToWords.convert(16));
        System.out.println("*** " + EnglishNumberToWords.convert(100));
        System.out.println("*** " + EnglishNumberToWords.convert(118));
        System.out.println("*** " + EnglishNumberToWords.convert(200));
        System.out.println("*** " + EnglishNumberToWords.convert(219));
        System.out.println("*** " + EnglishNumberToWords.convert(800));
        System.out.println("*** " + EnglishNumberToWords.convert(801));
        System.out.println("*** " + EnglishNumberToWords.convert(1316));
        System.out.println("*** " + EnglishNumberToWords.convert(1000000));
        System.out.println("*** " + EnglishNumberToWords.convert(2000000));
        System.out.println("*** " + EnglishNumberToWords.convert(3000200));
        System.out.println("*** " + EnglishNumberToWords.convert(700000));
        System.out.println("*** " + EnglishNumberToWords.convert(9000000));
        System.out.println("*** " + EnglishNumberToWords.convert(9001000));
        System.out.println("*** " + EnglishNumberToWords.convert(123456789));
        System.out.println("*** " + EnglishNumberToWords.convert(2147483647));
        System.out.println("*** " + EnglishNumberToWords.convert(3000000010L));
         *** zero
         *** one
         *** sixteen
         *** one hundred
         *** one hundred eighteen
         *** two hundred
         *** two hundred nineteen
         *** eight hundred
         *** eight hundred one
         *** one thousand three hundred sixteen
         *** one million
         *** two millions
         *** three millions two hundred
         *** seven hundred thousand
         *** nine millions
         *** nine millions one thousand
         *** one hundred twenty three millions four hundred
         **      fifty six thousand seven hundred eighty nine
         *** two billion one hundred forty seven millions
         **      four hundred eighty three thousand six hundred forty seven
         *** three billion ten
    }

  • I am having difficulty including text with iPhotos I want to share through email.  I get a red exclamation mark along with a statement stating that the text doesn't fit into the designated text area.  This is so frustrating.

    I am having difficulty including text with iPhotos I want to share through email.  I get a red exclamation mark along with a statement stating that the text doesn't fit into the designated text area.  This is so frustrating. Before iLire11 I was easily able to share photos with email messages.  Arghhhh!

    In the iPhoto preferences you can set Apple Mail as your e-mail client and then it will work exactly as before
    LN

  • Missing rotated text in PDF created via FPDF

    Hi guys,
    I have a weird problem which is preventing some rotated text to be viewed in adobe reader, while every other reader like foxit, google pdf viewer and scrib are doing just fine!
    if you create a flyer using following link
    http://www.erupert.ca/classifieds/create_flyer/ad/32_1306248214
    the generated PDF displays just fine in google document viewer but if I download and open the same in Adobe reader the pull tab text (text rorated 90 degrees) vanish, again the PDF is just fine in foxit reader as well!
    What am I doing wrong, any ideas would be much appriciated.
    Also here is the code to rotate text I'm using by extending the FPDF class
    function Rotate($angle,$x=-1,$y=-1)
    if($x==-1) $x=$this->x;
            if($y==-1) $y=$this->y; //echo "{$this->x} - {$this->y}";die();
            if($angle!=0) $this->_out('Q');
            $angle=$angle;
            if($angle!=0)
    $angle*=M_PI/180;
    $c=cos($angle);
    $s=sin($angle);
    $cx=$x*$this->k;
    $cy=($this->h-$y)*$this->k;
    $this->_out(sprintf('q %.5f %.5f %.5f %.5f %.2f %.2f cm 1 0 0 1 %.2f %.2f cm',$c,$s,-$s,$c,$cx,$cy,-$cx,-$cy));
    OS: Windows Any ( >= XP)
    Adobe version X (latest updates)
    Thanks,
    Anupam

    Hello anupam,
    I know this is a particularly old thread, however i thought i'd post the solution here for others who may have been searching around for a solution to this very same problem and come across this thread.
    As George has correctly stated it is an issue with the unbalanced q and Q operators. I recognise the provided piece of code, it is of course a snippet from a generation class such as FPDF or TCPDF or HTML2PDF, the error occurs when the rotation is not returned to 0 before finalising the document.
    i.e. You would have used something like $pdf -> Rotate(270,60,50) or $this -> Rotate(270,60,50) where 270=the degree of rotation , 60=the x coordinate , 50=the y coordinate.
    Once you've completed writing all your text, lines, images, cells you need to make sure to reset the rotate i.e. $pdf -> Rotate(0) prior to Outputting the pdf to screen or saving it as a file.

  • How do I rotate text within a table Pages 4.3?

    Does anyone know how to rotate text within a cell in a Pages 4.3 table?

    You would have to use a floating text box over the cell. Make sure text wrap is turned off.

  • How to create a xml element for Text with Java?

    Hi @ all,
    I want to tag a part of a text with Java.
    Like the InDesign function "Tag für Text" (maybe "tag for text" in english)
    Is there a way to tag text with Java?
    I tried to autoTag and to markup the text with an existing xml, but only got IdsExceptions.
    here the code where to tag the text:
    XMLElement newXML = parentXML.addXMLElement(VariableTypeUtils.createString("newXML"),OptArg.noVariableType());
    Text[] texts = para.findText(OptArg.noBoolean());
    for (Text text : texts)
       //TODO tag text
    Exception throwing code:
    text.autoTag();
    text.markup(newXML);
    newXML.markup(VariableTypeUtils.createObject(text));

    This is not a Web Dynpro specific question. This forum is for Web Dynpro specifc development aspects. There are other forums for general ABAP development as well as other specific aspects of ABAP development.
    I strong suggest that you review the rules of engagement for forum involvement, Derek.  You have had multiple violations of the rules in the last week.

  • Can't change rotating text on revoltion theme after I delete the menu text.

    So I export a slideshow to iDVD. By default you have the revolution theme. There is text that says revolution main in the body of the menu and it says revolution main on the rotating text. There is also a button for my slideshow. So I change the revolution main text to what I want the rotating text to be then delete that text on the main menu. The rotating text then stays. But if I want to then change it, I can't see any way to do so because I deleted the button. What was it that I deleted? How do I get it back. I thought it was the title menu, so I add a new title menu button and try to change the text but the rotating text won't change. I am probably missing something simple, but I can't for the life of me figure it out.
    Thanks in advance,
    Brian

    Hi,
    Count me in.
    Same issue,
    Once deleted the title can't [it appears] be changed from the default of 'Revolution Extras' .. which is a nuisance as the rest of the project I'm working on is finished ... I thought i'd wait till the end to name it but find I am struggling to find out how.
    can anyone help?
    kindest,
    becca

  • Rotating text without embedding fonts - how?

    No doubt same or similar question was asked and most likely answered but I could not
    find anything that would match...
    I want to draw column headers of my ADG vertically. So, I need rotate column text 90 degree
    and adjust position.
    Is it true that it can be achieved with embedded font only? If it is true how can it be done for
    Unicode code, which includes ranges for Japanese, Chinese, etc characters. The size of
    swf is going to be huge. Several sites like this
    http://www.forestandthetrees.com/2009/06/29/rotating-text-without-embedding-fonts/
    claims that they have a solution for the problem without embedding fonts.
    Note: I am still using Flex 3.3 SDK with no TLF. By the way, do TLF libraries work with
    3.3 SDK.?
    Thanks in advance

    Draw your text onto a bitmap image (or take an ImageSnapshot of a Label), then rotate the image.

Maybe you are looking for

  • IPhone bluetooth Windows 7 not working correctly.

    Just upgraded my computer to an Asus P8P67 which has built in bluetooth (Atheros). Was messing around trying to see what features I had connecting my iPhone to my computer via bluetooth. When I try to pair it the pair seems to work however when it in

  • ITunes 11 - Get Info greyed out for movies on external drive

    With iTunes 10, my itunes movies and TV shows grew to about 1.2TB of data, and I shifted them to an external drive. I was able to edit the information via 'get info' until upgrading to iTunes 11. Now all the information, bar the 'five stars' field ar

  • Inheritance problems

    I'm trying to work out a problem with a project I'm working on that uses inheritance. the superclass consists of a prebuild GUI using swing, when more then one class enherits from the superclass for some reason its like they are sharing the subclass,

  • I accidently removed my iphone 2g operating system now it wont open how to solve this

    i think my son did something and removed the operating syste in my iphone 2g n now its not opening and i see only the boot icon n it stuck there how to get my os back in my iphone 2g

  • Very very urgent - foreign curency valuation

    Hi when i am not assigning the cost centre to vendor in FB 60 then the foreign currency valuation is working properly. but when i assigned the cost centre then i am getting following error Posting for general ledger account 15201001 amount