Drawing a String at an angle

Hi,
I have use the Graphics class to develope a map of streets etc and I wish to place the name of the streets running parallel to the streets themselves.
The drawString method allows me to specifiy the string and start co-ordinates but can anyone tell me how I can specify the strings baseline or the start and end co-ordinates of the string in order to display the string parallel to the street.
Thanks

Assuming your using Swing and not AWT...
1. Convert your graphics object into a graphics2D object;
Graphics2D g2 = (Graphics) g;
2. use translate(x, y) to recenter your world. In general, I like to return to the center when I'm done with operations at that point
3. useGraphics2D.rotate(...) to rotate your string drawing. Always remember that strings draw from the bottom left hand corner.

Similar Messages

  • Draw a string with one character in a different color

    This problem sounds trivially simple, but I don't have a clue on how to implement it.
    What I'm basically trying to do, is use Graphics2D.drawString() to draw a string...but I want one letter to be in a different color. Guessing from the API this could be possible with an AttributedCharacterIterator, but I don't know how to set 'color' as one of the attributes.
    Does anyone with knowledge of Java 2D havy any solution for this?

    keeskist wrote:
    This problem sounds trivially simple, but I don't have a clue on how to implement it.
    What I'm basically trying to do, is use Graphics2D.drawString() to draw a string...but I want one letter to be in a different color. Guessing from the API this could be possible with an AttributedCharacterIterator, but I don't know how to set 'color' as one of the attributes.
    Does anyone with knowledge of Java 2D havy any solution for this?Here's an example using AttributedString/AttributedCharacterIterator:
    import java.awt.*;
    import java.awt.font.TextAttribute;
    import java.text.AttributedString;
    import javax.swing.*;
    public class AttributedCharacterIteratorDemo extends JFrame {
         public AttributedCharacterIteratorDemo() {
              AttributedString as = new AttributedString("Hello, world!");
              as.addAttribute(TextAttribute.FOREGROUND, Color.RED, 2, 3);
              JPanel cp = new ACRPanel(as);
              cp.setPreferredSize(new Dimension(300,300));
              setContentPane(cp);
              setTitle("AttributedCharacterIterator Demo");
              setDefaultCloseOperation(EXIT_ON_CLOSE);
              pack();
         public static void main(String[] args) {
              SwingUtilities.invokeLater(new Runnable() {
                   public void run() {
                        new AttributedCharacterIteratorDemo().setVisible(true);
         private class ACRPanel extends JPanel {
              private AttributedString as;
              public ACRPanel(AttributedString as) {
                   this.as = as;
              protected void paintComponent(Graphics g) {
                   g.drawString(as.getIterator(), 40,40);
    }

  • How to draw 2 Strings one after the other?

    Hello,
    I have this code, and I would like to know how can I draw the string "s2" right after the first string "s1" on this panel, so that it comes right behind it while they're moving?
    Also, how can I make some of the strings drawn clickable (Like links) so that when I press on them some action is performed?
    Thanks a lot.
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    public class VertMovingTextPanel extends JPanel implements ActionListener {
        Timer t = new Timer(5,this);
        int x = 10 , y = 0 ;
        public VertMovingTextPanel()
        public void paintComponent (Graphics g){
            super.paintComponent(g);
            String s1 = "Alert number 1";
            String s2 = "Alert number 2";
            g.drawString(s1, x, y);
            //g.drawString(s2, x, y);
            t.start();
        public void actionPerformed (ActionEvent e)
            if (y < 0 || y > 600 )
                y = 0;
            y ++;
            repaint();
        public static void main(String[] args) {
          JFrame frame = new JFrame("Alerts");
          VertMovingTextPanel vp = new VertMovingTextPanel();
          frame.add(vp);
          frame.setVisible(true);
          frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
          frame.setSize(600,600);
    }

    Use g.getFontMetrics().stringWidth(s1) to get width of the s1. Add the number to the x2.
    To have it clickable create Rectangle(s) for the string bounds. When user clicks use x and y position and check if the rectangle contains the point.

  • Graphic2D.drawString() isn't drawing my strings.  Help!!

    Hello everybody, thanks for looking.
    I'm writing a program that creates and prints out schedules for a sports league. I am having a very annoying problem with drawString().
    The incredibly annoying part of this is that one method in my object prints its strings correctly, whereas exactly the same code in another method doesn't print anything.
    O.K., here's the code for calling both these methods:
    drawLeagueNameWeek ( g2, leagueWeek );
    drawLeagueGameList ( g2, leagueWeek );This code comes from the print method of my object, which implements Printable, and g2 is the Graphics2D object that I typecast from the Graphics object in print().
    Here's the text of the first method, drawLeagueNameWeek, which works perfectly.
    void drawLeagueNameWeek ( Graphics2D g2, int weekNumber )
    // This method draws the name of the league and the current week
    // being printed at the top of each page.  It'll be nicely centered,
    // as well. 
    String leagueNameString, leagueWeekString;
    FontRenderContext leagueContext;
    int fontSize;
    double fontXCenter;
    float xValue, yValue;
    leagueNameString = printRecord.getLeagueName();
    leagueNameString = leagueNameString + LEAGUE_TITLE_STRING;
    // I need the plus one because of 0..n array offsets.  Trust me, it's necessicary.
    leagueWeekString = WEEK_TITLE_STRING + Integer.toString( weekNumber + 1 );
    Font leagueFont;
    // First, create the font
    fontSize = (int) Math.round( divisionSize / 2 );
    leagueFont = new Font ("Serif", Font.BOLD, fontSize );
    g2.setFont ( leagueFont );
    leagueContext = g2.getFontRenderContext();
    fontXCenter = leagueFont.getStringBounds(leagueNameString, leagueContext).getWidth();
    xValue = ( float ) ( myPF.getImageableX() + ( ( WIDTH / 2 ) - ( fontXCenter / 2 ) ) );
    yValue = (float) ( myPF.getImageableY() + ( divisionSize ) );
    System.out.println("xValue and yValue for leagueNameString" );
    System.out.println("xValue -- " + xValue + ", yValue -- " + yValue );
    g2.drawString ( leagueNameString, xValue, yValue );       
    // Having drawn the League Name, now draw the league week under it. 
    fontXCenter = leagueFont.getStringBounds ( leagueWeekString, leagueContext).getWidth();
    xValue = ( float ) ( myPF.getImageableX() +  ( ( WIDTH / 2 ) - ( fontXCenter / 2 ) ) );
    yValue = ( float ) ( myPF.getImageableY() + ( 2 * divisionSize ) );
    System.out.println("xValue and yValue for leagueWeekString" );
    System.out.println("xValue -- " + xValue + ", yValue -- " + yValue );
    g2.drawString ( leagueWeekString, xValue, yValue );
    } // end of drawLeagueNameWeekThis method, as I say, draws the text that i want beautifully. It's nicely centered at the top of the page, and prints out the week number correctly.
    The second method, drawLeagueGameList(), though, doesn't seem to do anything. The println statements all print, they show me the strings and ints and everything else that I want and everything seems fine.
    Except the calls to g2.drawString() simply refuse to print anything. And I have no idea why.
    Here's the code for that one.
    void drawLeagueGameList ( Graphics2D g2, int leagueWeek )
    // This method is the heart and soul of the BasicBBPrinter class. 
    // One thing to keep in mind, I can only print 5 games per page, so
    // I need to keep track of what games to print next. 
    // That information in stored in the variable gameCount.  
    Font gameFont;
    FontRenderContext gameContext;
    int fontSize, pageGameCount, lineSpacing, numberGames;
    double fontXCenter;
    float xValue, yValue;
    String teamString, gameString;
    LeagueGameRecord printGame;
    printRecord.updateLeagueStandings();
    gameContext = g2.getFontRenderContext();
    numberGames = printRecord.getNumberGames( leagueWeek );
    // First, create the font
    //          fontSize = (int) Math.round( divisionSize / 3 );
              fontSize = 30;
    System.out.println("fontSize is " + fontSize );
    gameFont = new Font ("Serif", Font.BOLD, fontSize );
    lineSpacing = Math.round ( divisionSize / 3 );
    g2.setFont( gameFont );
    g2.setColor ( Color.BLACK );
    pageGameCount = 0;
    // Since the league title and the league week take up the top two divisions,
    // I need to make sure the other games get the proper offset.  Each game
    // gets two divisions for space. 
    // First, is our loop for getting our games...
    while ( ( pageGameCount < 5 ) && ( gameCount < numberGames ) )
    // First, get our game record...
    printGame = printRecord.getGameRecord( leagueWeek,
                                  ( gameCount ) );
    System.out.println("I'm getting game " + gameCount + " in week " + leagueWeek );
    // Next, calculate the location of our game text.
    xValue = (float) myPF.getImageableX() + 30;
    yValue = ( float ) myPF.getImageableY() + ( ( ( pageGameCount * 2 ) + 2 ) * divisionSize );
    System.out.println("xValue is " + xValue + ", yValue is " + yValue );
    // With that done, we can start figuring out where the text goes. 
    if ( printGame != null )
    System.out.println("In printGame != null statement" );
    if ( printGame.isByeWeek() == true )
    gameString = BYE_WEEK_STRING;
    else
    // Make the string for our game. 
    // Plus 1 for offsets, remember. 
    gameString = GAME_TITLE_STRING + Integer.toString ( gameCount + pageGameCount + 1 );
    // Print out our game number...
    //=====
    System.out.println("gameString is " + gameString );
    fontXCenter = gameFont.getStringBounds( gameString, gameContext).getWidth();
    xValue = ( float ) ( myPF.getImageableX() + ( ( WIDTH / 2 ) - ( fontXCenter / 2 ) ) );
    g2.drawString( gameString, xValue, yValue );
    //=======
    // Now, whether the game is a bye week or not, we need to
    // print out the name of the first team. 
    teamString = printRecord.getTeamName( printGame.getLeagueTeam1() ) + "  ( " + standingsRecord.getTeamWinRecord( printGame.getLeagueTeam1() ) +      " - " + standingsRecord.getTeamLossRecord( printGame.getLeagueTeam1() ) + " - " + standingsRecord.getTeamTieRecord( printGame.getLeagueTeam1() ) +      " ) ";
    yValue = ( float ) myPF.getImageableY() + ( ( pageGameCount + 2 ) * divisionSize );
    yValue = yValue + lineSpacing;
    System.out.println("team 1's string is " + teamString );
    g2.setColor ( Color.RED );
    g2.drawString( teamString, xValue, yValue );
    testLine = new Line2D.Float ( xValue, yValue, xValue + 200, yValue );
    g2.draw( testLine );
    if ( printGame.isByeWeek() == false )
    // Print out the versus and the other team name...
    yValue = yValue + lineSpacing;
    g2.drawString( VERSUS_STRING, xValue, yValue );
    g2.setColor ( Color.GREEN );
    testLine = new Line2D.Float ( xValue, yValue, xValue + 200, yValue );
    g2.draw( testLine );
    System.out.println("versus string is " + VERSUS_STRING );
    // And then, draw the other team name...
    teamString = printRecord.getTeamName( printGame.getLeagueTeam2() );
    // Now, add the record for the team onto the teamString...
    // Team wins...
    teamString = teamString + "  ( " + standingsRecord.getTeamWinRecord( printGame.getLeagueTeam2() );
    // Team losses...
    teamString = teamString + " - " + standingsRecord.getTeamLossRecord( printGame.getLeagueTeam2() );
    // Team ties...
    teamString = teamString + " - " + standingsRecord.getTeamTieRecord( printGame.getLeagueTeam2() );
    teamString = teamString + " )";
    yValue = yValue + lineSpacing;
    g2.drawString( teamString, xValue, yValue );
    g2.setColor( Color.BLUE );
    testLine = new Line2D.Float ( xValue, yValue, xValue + 200, yValue );
    g2.draw( testLine );
    System.out.println("team 2's string is " + teamString );
    } // end of if ( isByeWeek == false )
    } // end of if ( printGame != null )
    else
    System.out.println("record was a null" );
    // Finally, increment gameCount and pageGameCount
    gameCount++;
    pageGameCount++;
    System.out.println("gameCount is now " + gameCount );
    System.out.println("pageGameCount is also now " + pageGameCount );
    } // end of for loop           
    } // end of drawLeagueGameList Now, here's a copy of a run-through trying to print a league schedule.
    width is 612.0
    height is 792.0
    There are 4 games
    xValue and yValue for leagueNameString
    xValue -- 92.639984, yValue -- 96.0
    xValue and yValue for leagueWeekString
    xValue -- 250.56, yValue -- 156.0
    fontSize is 30
    I'm getting game 0 in week 0
    xValue is 66.0, yValue is 156.0
    In printGame != null statement
    gameString is Game #1
    team 1's string is Gonzo ( 2 - 0 - 0 )
    versus string is -- versus --
    team 2's string is Fozzie ( 1 - 1 - 0 )
    gameCount is now 1
    pageGameCount is also now 1
    I'm getting game 1 in week 0
    xValue is 66.0, yValue is 276.0
    In printGame != null statement
    gameString is Game #3
    team 1's string is Sweetums ( 0 - 2 - 0 )
    versus string is -- versus --
    team 2's string is Kermit ( 2 - 0 - 0 )
    gameCount is now 2
    pageGameCount is also now 2
    I'm getting game 2 in week 0
    xValue is 66.0, yValue is 396.0
    In printGame != null statement
    gameString is Game #5
    team 1's string is Robin ( 1 - 1 - 0 )
    versus string is -- versus --
    team 2's string is Miss Piggy ( 0 - 1 - 0 )
    gameCount is now 3
    pageGameCount is also now 3
    I'm getting game 3 in week 0
    xValue is 66.0, yValue is 516.0
    In printGame != null statement
    gameString is Bye week
    team 1's string is Statler ( 0 - 1 - 0 )
    gameCount is now 4
    pageGameCount is also now 4
    xValue and yValue for leagueNameString
    xValue -- 92.639984, yValue -- 96.0
    xValue and yValue for leagueWeekString
    xValue -- 250.56, yValue -- 156.0
    fontSize is 30
    numberGames is now -1
    From the trace lines, my team strings seem to be being built perfectly, my x and y locations seem to be fine, since I'm using values less then the width and height, and the text in drawLeagueNameWeek(() works fine, but it simply refuses to print anything that's in drawLeagueGameList, even the test lines.
    I even tried copying all the code from drawLeagueGameList into drawLeagueGameWeek and, while all the game week stuff printed correctly, the gameList stuff still refused to do anything.
    I've been working on this for three or four days and have no idea at all what might be wrong. I figure it's something simple and stupid, but I can't seem to find it.
    Any and all help is appreciated.
    And if you need any more information on anything, let me know.
    Thanks again.

    Hi, again.
    I think I managed to solve this problem with help from another friend, and I'll post it here in case somebody with a similar problem comes across my post.
    I've managed to get drawString to draw the strings in drawLeagueGameList by removing the while loop from around them.
    This requires that I rebuild this method as a series of if-else statements, but I'm certinally willing to do that if that's what it takes to get it to work.
    I still do not know why drawString isn't working inside that loop, it might be a bug of some kind in drawString or in the Graphics2D library.
    If anybody has any idea on why it didn't work in the loop, I'm still interested in hearing theories.
    Thanks again for looking.

  • Drawing a String using Graphics Object

    When I am printing a long String using the following method
    String currentMessage // The size of the String is large
    g.drawString(currentMessage, x, y, Graphics.BOTTOM | Graphics.HCENTER);
    only the middle of the String is shown on the sreen.The first and last parts are stripped off because of the size of the screen.
    Anyone knows how to specify the size of the font, or how to force the string to continue on a new line if its size is bigger than the width of the screen?
    Cheers

    There is not native support for line wrapping in drawString().
    You can change the font by using g.setFont(),
    Create your on font, and specify the font size as small.
    The Font class includes a method to determine the length of a string. You can use this method to check the length of the String if the string is longer than the screen width, you can break the String into parts (substrings) and draw each of the parts.
    Alternatively, you can use this line wrapping class http://hostj2me.com/appdetails.html?id=6

  • How find shape containing all pixels in string drawn at angle?

    I've drawn a string on a JPanel at an angle using the code below. I want the mouse to turn into a hand when hovering over it but I don't know how to find the shape that an angled string comprises. (I can do it if it's written horizontally). How would I calculate that?
    double theta = Math.toRadians( angle );
    AffineTransform transform = AffineTransform.getRotateInstance( theta );
    ( ( Graphics2D ) graphics ).setTransform( transform );
    graphics.drawString( text, x, y );

    For the String you can create a Rectangle where the String is contained when it has no rotation. After that you can create Area (see java.awt.geom.Area) from the Rectangle and use transform() method of area to get a rotated one. Then just use contains() method.
    Regards,
    Stas

  • Very Urgent - Draw a string in a rectangle with a given width

    Hi
    I have a jtextArea and I have set its width to a fixed value. I set the wrap line property to tru and the word wrap true so as if the word is too large it will be displayed on the next line of the jtextArea. I read a string value and give it to the JTextArea.
    I want to know the height of the JTextarea after the String is wrapped in it. The string may be of a single line but after it is wrapped, in the JTextArea it may appear as multiple line. All the methods of the JTextarea tell me that the JTextarea has a string of one line and the rectangle it returns does not match the true one.
    I want to know either the real values of the rectangle after the string is wrapped or the number of lines the string is divided as it appears in the textareas.
    My email address is [email protected]
    Thx.. and please help..

    See this example of line numbering in JEditorPane.
    I think in the text area it's the same
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    import javax.swing.text.*;
    import javax.swing.text.rtf.*;
    class Test extends JFrame
    public Test()
    super("Test");
    JEditorPane edit = new JEditorPane();
    edit.setEditorKit(new MyRTFEditorKit());
    edit.setEditable(true);
    JScrollPane scroll=new JScrollPane(edit);
    getContentPane().add(scroll);
    setSize(300,300);
    setVisible(true);
    public static void main(String a[])
    new Test();
    class MyRTFEditorKit extends RTFEditorKit
    public ViewFactory getViewFactory()
    return new MyRTFViewFactory();
    class MyRTFViewFactory implements ViewFactory
    public View create(Element elem)
    String kind = elem.getName();
    if (kind != null)
    if (kind.equals(AbstractDocument.ContentElementName)) {
    return new LabelView(elem);
    } else if (kind.equals(AbstractDocument.ParagraphElementName)) {
    // return new ParagraphView(elem);
    return new MyParagraphView(elem);
    } else if (kind.equals(AbstractDocument.SectionElementName)) {
    // return new BoxView(elem, View.Y_AXIS);
    return new MySectionView(elem, View.Y_AXIS);
    } else if (kind.equals(StyleConstants.ComponentElementName)) {
    return new ComponentView(elem);
    } else if (kind.equals(StyleConstants.IconElementName)) {
    return new IconView(elem);
    // default to text display
    return new LabelView(elem);
    class MySectionView extends BoxView {
    public MySectionView(Element e, int axis)
    super(e,axis);
    public void paintChild(Graphics g,Rectangle r,int n) {
    if (n>0) {
    MyParagraphView child=(MyParagraphView)this.getView(n-1);
    int shift=child.shift+child.childCount;
    MyParagraphView current=(MyParagraphView)this.getView(n);
    current.shift=shift;
    super.paintChild(g,r,n);
    class MyParagraphView extends javax.swing.text.ParagraphView
    public int childCount;
    public int shift=0;
    public MyParagraphView(Element e)
    super(e);
    short top=0;
    short left=20;
    short bottom=0;
    short right=0;
    this.setInsets(top,left,bottom,right);
    public void paint(Graphics g, Shape a)
    childCount=this.getViewCount();
    super.paint (g,a);
    int rowCountInThisParagraph=this.getViewCount(); //<----- YOU HAVE REAL ROW COUNT FOR ONE PARAGRAPH}
    System.err.println(rowCountInThisParagraph);
    public void paintChild(Graphics g,Rectangle r,int n) {
    super.paintChild(g,r,n);
    g.drawString(Integer.toString(shift+n+1),r.x-20,r.y+r.height-3);
    best regards
    Stas

  • Help with drawing strings on JFrame?!?!

    Hey guys, I'm really new to Java (just started AP Comp Sci last month), and we had a project to build a Mastermind application using numbers, which I did. However, I'm trying to learn more on my own, and was hoping to use the example code my teacher gave me to output what I want to say to a JFrame instead of just the command prompt.
    Here is the code for my Mastermind class:
    Code:
    import javax.swing.*;
    import java.awt.*;
    import java.awt.event.*;
    public class Mastermind extends JFrame
         public static void main(String args[])
              int master[] = new int[4];
              int win = 0;
              for(int x = 0; x<4; x++)
                   master[x] = (int)(Math.random()*10);
              System.out.println();
              do {
                   int guess[] = new int[4];
                   int countMaster[] = new int[4];
              String numguess = JOptionPane.showInputDialog("Enter your guess (4 digits, please)");
              for (int x = 0;x<4;x++)
                   guess[x] = (numguess.charAt(x)-48);
              int correctlyPlaced = 0;
              int correct = 0;
              for (int x = 0;x<4;x++)
                   if(master[x] == guess[x])
                        correctlyPlaced += 1;
              for (int x = 0; x<4;x++)
                             for (int y = 0; y<4;y++)
                                  if((guess[x]==master[y]) && (countMaster[y]==0)) {
                                       correct++;
                                       countMaster[y]=1;
                                       y=5;
              System.out.print("Guess:\t\t\t");
              for (int x = 0;x<4;x++) {
                   System.out.print(guess[x]);
              System.out.println();
              System.out.println("Correct:\t\t"+correct);
              System.out.println("Correctly Placed:\t"+correctlyPlaced);
              if (correctlyPlaced==4) {
                   win=1;
         } while(win<1);
         System.out.println("You win!");
              System.exit(0);
    And here is the example code that my teacher gave me for how to draw a string on a JFrame:
    Code:
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    public class Fonts extends JFrame {
         public Fonts()
              super("Using Fonts");
              setSize(420,125);
              show();
         public void paint(Graphics g)
              super.paint(g);
              g.setFont(new Font("Serif", Font.BOLD, 12));
              g.drawString("Serif 12 point bold.",20,50);
         public static void main(String args[])
              Fonts application = new Fonts();
              application.setDefaultCloseOperation (
                   JFrame.EXIT_ON_CLOSE);
    I would like to be able to put "Guess," "Correct," and "Correctly Placed," on a JFrame, with their respective variables. Any ideas? Thank you!!!

    800045 wrote:
    And DrClap, I get that, but I'm not sure how to put my existing code into the class file that uses the JFrame.You wouldn't put your existing code in there. Your existing code is designed to run as a console app and most of it is concerned with the machinery of getting input from the user. If you want to write it as a Swing app, then you wouldn't need any code which writes to a JFrame in the first place.
    So if your goal for learning on your own is to write GUI applications instead of console applications, then go off and read the Swing tutorials. Right now you're going down the wrong road. However if you're trying to learn something else on your own (I can't tell what that might be) then explain what it is you're trying to learn.

  • How to find the total length of the string drawed in a rect?

    Hello Everybody,
    I am drawing a string in on one rect using drawInRect method. This drawInRect method gives us a return value as size of the rect. I need length of the string that is did draw in that rect, but didn't find any api to do this.
    Can anyone tell me , how find the length of the string which we did draw in rect?
    Any help regarding this issue , is highly appreciable.
    Thanks,
    Pandit

    Hi Adreas,
    First of all, very thanks for the response.
    Actually , I am looking for other thing. Using drawInRect method I am drawing contentString in self.rect like below.
    //code
    [contentString drawInRect:self.rect withFont:[UIFont fontWithName:@"Verdana" size:14.0] lineBreakMode:UILineBreakModeWordWrap alignment:UITextAlignmentLeft];
    //End
    My contentString is much larger string, so I am not able to draw it in rect(length: 320.0 height: 460.0) completely. My rect is showing only a part of a contentString. So I need to get that part of string which did draw in the rect, so that I can process my contentString to get the remaining string to draw it a next rect.
    The above code statement is returning me the CGSIZE , it is giving the size of the rect but not giving any information of the string which get draw in that rect.Do you have any idea how to do this?
    Any information on this is highly appreciable.
    Thanks,
    Pandit

  • Drawing a color string with swing and Graphics2D

    hi guys,
    I am trying to draw a string on a JPanel, and can do so successfully with plain boring text using drawString(string, int, int). How can I change the font and color? Thanks!

    Read the API for java.awt.Graphics.
    db

  • Draw string in center

    Hi,
    I would like to draw a string into center of my own Lable component. How can I know what position of x , y ?
    I'm using g.drawString(mytext, x , y ); in paintComponent() method.

    I guess you could use one of these:
    - Font.getStringBounds()
    - TextLayout.getBounds()
    - FontMetrics.getStringBounds()

  • Havin probs drawing a simple string

    hi 2 all
    i've got this simple applet,but it doesn't really what i want!i only see a gry rect!but he has to draw a string!
    import java.applet.*;
    import java.net.*;
    import java.io.*;
    import java.awt.*;
    public class CCounter1 extends Applet {
    Font anzeiger;
    public void init() {
    anzeiger=new Font("Arial",Font.BOLD,16);
    public String readFile(String f) {
    try {
    String zahl1="";
    String aLine = "";
    URL source = new URL(getCodeBase(), f);
    BufferedReader br =new BufferedReader(new InputStreamReader(source.openStream()));
    while(null != (aLine = br.readLine()))
    zahl1.concat(zahl1);
    br.close();
    return aLine;
    catch(Exception e) {
    e.printStackTrace();
    return null;
    public void paint(Graphics g){
    setBackground(Color.gray);
    g.setColor(Color.white);
    setFont(anzeiger);
    g.fillRect(100,100,100,100);
    g.drawString(readFile("besucher.hansi"),10,20);
    g.drawString("Hallo",200,200);

    You set the color to white... fill the area and then paint a string (with the same white color)
    first... set a color... fill it... then set another color... draw your string... done
    Grtz David

  • How to draw string vertically?

    Hi,
    The java drawString() method draws string horizontally by default, but I want to draw the string vertically, see an example below: I want to draw the string "abcdef" as below format:
    a
    b
    c
    d
    e
    f
    so, I thought of the AffineTransform, but I can not work it out.
    Who can help me? If you have other ways, they are welcome too.
    Thanks. Robin

    import java.awt.*;
    import java.awt.font.*;
    import java.awt.geom.AffineTransform;
    import java.awt.image.BufferedImage;
    import javax.swing.*;
    public class VText {
        public static void main(String[] args) {
            int w = 200, h = 300;
            BufferedImage image = new BufferedImage(w,h,BufferedImage.TYPE_INT_RGB);
            Graphics2D g2 = image.createGraphics();
            g2.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING,
                                RenderingHints.VALUE_TEXT_ANTIALIAS_ON);
            g2.setBackground(UIManager.getColor("OptionPane.background"));
            g2.clearRect(0,0,w,h);
            g2.setPaint(Color.black);
            Font font = g2.getFont().deriveFont(18f);
            g2.setFont(font);
            FontRenderContext frc = g2.getFontRenderContext();
            String text = "Hello World";
            g2.drawString(text, 50, h - 25);
            String[] s = text.split("(?<=[\\w\\s])");
            float y = 25f;
            for(int j = 0; j < s.length; j++) {
                float width = (float)font.getStringBounds(s[j], frc).getWidth();
                LineMetrics lm = font.getLineMetrics(s[j], frc);
                float x = (w - width)/2;
                AffineTransform at = AffineTransform.getTranslateInstance(x, y);
                g2.setFont(font.deriveFont(at));
                g2.drawString(s[j], 0, 0);
                y += lm.getAscent();// - lm.getDescent();
            g2.dispose();
            JOptionPane.showMessageDialog(null, new ImageIcon(image), "",
                                          JOptionPane.PLAIN_MESSAGE);
    }

  • Zooming on a large drawing

    Can someboby, please, help me to manage the zooming of an area of size 30x30 pixels of a large drawing.
    The drawing contains a number of shapes, but in the code that I will be posting I will be using only one shape. The drawing is made up of more than 500 shapes, reason for which has to be scaled to fit on a monitor.
    What I would like to happen is : when mouse clicked anywhere on the drawing a small area of 30x30 pixels should zoom out so the label for the shape to be clear. At this zoomed stage I should also be able to click on a chosen shape and open some frame.
    I will post the code I wrote bellow. Could somebody please be so kind and help me!
    import java.awt.*;
    import java.awt.event.*;
    import java.awt.image.*;
    import java.awt.geom.*;
    import javax.swing.*;
    public class drawHarp
         AffineTransform at=new AffineTransform();
         AffineTransform saveForm;
         GeneralPath r;
         Graphics smallcomp;
         String text,stat;
         int ax,ay,h,w;
         int angle ;
         boolean scaled;
         public drawHarp(Graphics2D g2D,int inax,int inay,String status,String intext,double angle,boolean scale )
              text=intext;
              ax=inax;
              ay=inay;
              scaled = scale;
              stat = status;
              saveForm = g2D.getTransform();
              initShape();
              if((scale==true)&&(angle==0)){
                        setScale();
                        setTransform(g2D);
                   }else if((scale==false)&&(angle==0)){
                        drawShape(g2D);
                   }else if((scale==false)&&(angle!=0)){
                        setRotate(angle);
                        setTransform(g2D);
                   }else if((scale==true)&&(angle!=0)){
                        setScale();
                        setRotate(angle);
                        setTransform(g2D);
         public void initShape(){
              r=new GeneralPath(GeneralPath.WIND_NON_ZERO,12);
                                       r.moveTo(ax, ay+5);
                                       r.lineTo(ax+20,ay+5);
                                       r.moveTo(ax, ay+10);
                                       r.lineTo(ax+20,ay+10);
                                       r.moveTo(ax, ay+15);
                                       r.lineTo(ax+20,ay+15);
                                       r.moveTo(ax+5, ay);
                                       r.lineTo(ax+5,ay+20);
                                       r.moveTo(ax+10, ay);
                                       r.lineTo(ax+10,ay+20);
                                       r.moveTo(ax+15, ay);
                                       r.lineTo(ax+15,ay+20);
                                       r.closePath();
         public void drawShape(Graphics2D g2D){
              /*     g2D.setStroke(new BasicStroke(1.0f));
                   g2D.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
                                                                               RenderingHints.VALUE_ANTIALIAS_ON);*/
                   g2D.draw(r);
                   g2D.setColor(Color.black);
                   g2D.drawString(text,ax-90,ay+15 );
         public void setTransform(Graphics2D g2D){
                                  AffineTransform toCenterAt = new AffineTransform();
                        toCenterAt.concatenate(at);
                                  Rectangle rect = r.getBounds();
                        toCenterAt.translate(-(rect.width/2),-(rect.height/2));
                        g2D.setTransform(toCenterAt);
                                  drawShape(g2D);
                                  g2D.setTransform(saveForm);
         public void setRotate(double angle){
                        at.rotate(Math.toRadians(angle),ax,ay);
         public void setScale(){
                   at.scale(0.3, 0.3);
    import java.awt.image.*;
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    public class DisplayArea extends JApplet {
    public void init() {
    public static void main(String[] args) {
    DisplayPanel first = new DisplayPanel();
    JFrame f = new JFrame();
    f.addWindowListener(new WindowAdapter() {
    public void windowClosing(WindowEvent e) {
    System.exit(0);
    f.getContentPane().add(first, BorderLayout.CENTER);
    f.setSize(new Dimension(500,400));
    f.setLocation(600,350);
    f.setVisible(true);
    class DisplayPanel extends JPanel implements MouseListener {
    public int w, h, i;
         Graphics smallcomp;
         String shape;
         BufferedImage bi;
         Graphics g;
         Graphics2D g2;
              //     boolean[] scale= {  false,          false,    false,     false,          false,     false,          false,     false,     false,          false};
                   boolean[] scale= {  true,          true,    true,     true,          true,     true,          true,     true,     true,          true};
                   String[] stat = { "on",          "off",      "true", "false",      "0",     "1",          "on",      "off",     "on",          "off"};
                   int[] ang =           { 300,           275,      160,      275,           90,     275,          180,     275,     275,          275};
                   String[] forms = {"hp",     "hp",     "hp",     "hp",          "hp",     "hp",          "hp",     "hp",     "hp",          "hp"};
                   String[] lab =           { "B1K",          "PO",     "BKO 3","STX+Y 2K",     "HP 3K","STX+Y 3K",     "Q1K",     "Q2K",     "Q3K",          "CCP 4K"};
                   int[] ax =                { 185,          210,          235,            260,       285,      310,          335,     360,     385,          410};
                   int[] ay =                { 203,     207,     209,          211,          213,          215,           217,       219,      221,            223};
    public DisplayPanel(){
                   setBackground(Color.lightGray);
                   addMouseListener(this);
                   bi = new BufferedImage(5,5,BufferedImage.TYPE_INT_RGB);
                   g = bi.createGraphics();
         public void mouseClicked(MouseEvent e){
         System.out.println("mouseClicked "+ e.getX() +" "+ e.getY());
         int xx = e.getX();
         int yy = e.getY();
              for(int j=0; j<forms.length; j++)
              if(xx>ax[j] && yy>ay[j] && xx<ax[j+10] && yy<ay[j+10])
                   System.out.println("less");
    public void mouseExited(MouseEvent e){}
         public void mouseEntered(MouseEvent e){}
         public void mouseReleased(MouseEvent e){}
    public void mousePressed(MouseEvent e){}
    public void paintComponent(Graphics g) {
    super.paintComponent(g);
    Graphics2D g2 = (Graphics2D) g;
              g2.setFont(new Font("SansSerif",Font.BOLD,12));
                   g2.setStroke(new BasicStroke(1.0f));
                   g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
                                                                RenderingHints.VALUE_ANTIALIAS_ON);
                   for(int i =0; i < forms.length; i++)
                        if(stat.equals("on")||stat[i].equals("1")||stat[i].equals("true"))
                             g2.setColor(Color.green);
                        else{
                                  g2.setColor(Color.red);
                        shape = forms[i];
                        if(shape.equals("hp"))
                                  new drawHarp(g2,ax[i],ay[i],stat[i],lab[i],ang[i],scale[i]);

    you probably want to do something like this.
    Override your paint method in your zoom window
    public void paint (Graphics g) {
    Graphics2D g2 = (Graphics2D)mainPanel.getGraphics();
    g2.translate(x,y); //whereever you want to start your zoom area
    g2.scale (dx, dy);
    }

  • Please enhance my code so that it can rotate text at the given angle

    public class ShapeDrawD extends JApplet
    Image img,imgback;
    static Image someimg2;
    ShapeCanvas canvas;
    ShapeCanvas backcanvas;
    public static int txtimgflag = -1,size,angle;
    public static String stringToDraw = "";
    public static int fontSize;
    public static String fontName;
    public static String fontStyle;
    public static String imgName;
    public static ImageObserver io;
    public static Shape shapeBeingDraggedtemp = null;
    public static Shape shapeBeingEdited = null;
    static Font fontmain;
    static Color colormain;
    static Color frocolor;
    public static String color;
    static Shape s = null;
    static JLabel l1 = new JLabel("");
    static String msg="";
    static JSObject js;
    public static URL url;
    public static URLConnection conn;
    public static String hostname;
    public static int port;
    static int addnew = 0;
    public static String str1;
    public static int str2;
    public static int zx, zy, oldy, zwidth,zheight;
    public static float scalingfactor;
    //Method which is called from Java Script taking parameters related to string and used for drawing strings
    public void printSomething(String str,String lname,String lstyle,String lsize,String lcolor,String lmsg,String frcol,String ang)
    try
    addnew = 1;
    colormain= new Color((Integer.decode("0X".concat(lcolor))).intValue());
    frocolor= new Color((Integer.decode("0X".concat(frcol))).intValue());
    fontmain = new Font(lname,Integer.parseInt(lstyle),Integer.parseInt(lsize));
    stringToDraw = str;
    size=Integer.parseInt(lsize);
    angle=Integer.parseInt(ang);
    msg=lmsg;
    str1=lname;
    str2=Integer.parseInt(lstyle);
    txtimgflag=0;
    drawIt();
    repaint();
    catch(NumberFormatException nfe)
    System.out.println("Please Enter Proper Numeric values");
    public void strdelete()
    if(canvas.isVisible() && shapeBeingEdited != null)
    //System.out.println("3inggggggggg "+ ((StringShape)shapeBeingEdited).Mystring);
    canvas.deleteit(shapeBeingEdited);
    addnew = 0;
    drawIt();
    repaint();
    else if(backcanvas.isVisible() && shapeBeingEdited != null)
    //System.out.println("Deletinggggggggg "+ ((StringShape)shapeBeingEdited).Mystring);
    backcanvas.deleteit(shapeBeingEdited);
    addnew = 0;
    drawIt();
    repaint();
    //Method which is called from Java Script taking parameters related to Editing string and used for drawing Edited strings
    public void editText(String str,String lname,String lstyle,String lsize,String lcolor,String lmsg,String frcol,String ang)
    addnew=0;
    //System.out.println("addnew "+ addnew);
    colormain= new Color((Integer.decode("0X".concat(lcolor))).intValue());
    frocolor= new Color((Integer.decode("0X".concat(frcol))).intValue());
    fontmain = new Font(lname,Integer.parseInt(lstyle),Integer.parseInt(lsize));
    stringToDraw = str;
    size=Integer.parseInt(lsize);
    msg=lmsg;
    angle=Integer.parseInt(ang);
    txtimgflag = 0;
    if(shapeBeingEdited != null && shapeBeingEdited instanceof StringShape)
    ((StringShape)shapeBeingEdited).Mystring=stringToDraw;
    ((StringShape)shapeBeingEdited).Mycolor=colormain;
    ((StringShape)shapeBeingEdited).Myfont=fontmain;
    ((StringShape)shapeBeingEdited).msg=msg;
    ((StringShape)shapeBeingEdited).frcolor=frocolor;
    ((StringShape)shapeBeingEdited).Siz=new Integer(size);
    ((StringShape)shapeBeingEdited).ang=new Integer(angle);
    drawIt();
    repaint();
    //Method Called from JavaScript used To Draw an Image takes Image name as param
    public void setImgName(String limgName)
    txtimgflag = 1;
    addnew = 1;
    imgName = limgName;
    someimg2 = getImage(getDocumentBase(),imgName);
    //System.out.println("Path -- >"+getDocumentBase() + imgName);
    MediaTracker mt = new MediaTracker(this);
    mt.addImage(someimg2,1);
    try
    mt.waitForAll();
    catch(Exception e)
    e.printStackTrace();
    drawIt();
    repaint();
    public void setImageWidthHeight(String lparamwidth,String lparamHeight)
    int width = Integer.parseInt(lparamwidth);
    int height = Integer.parseInt(lparamHeight);
    if(shapeBeingEdited != null && shapeBeingEdited instanceof ImageShape)
    addnew=0;
    ((ImageShape)shapeBeingEdited).htwtimg(width,height);
    drawIt();
    repaint();
    /*Method to save Image on the Server .
    this methos makes a call to servlet and passes ImageIcon to it which is then saved
    as a jpeg file on given path
    public void uploadImage(BufferedImage fimg,BufferedImage bimg)
    try
    String path = "http://"+hostname+":"+port+"/javatool/sampleServlet";
    url = new URL(path);
    //System.out.println("after url");
    //System.out.println("Path--->"+path);
    conn = url.openConnection();
    conn.setDoInput(true);
    conn.setDoOutput(true);
    conn.setUseCaches(false);
    conn.setRequestProperty("Content-type", "application/x-java-serialized-object");
    BufferedImage bi = fimg;
    Image imgg=(Image)bi;
    ImageIcon imgc = new ImageIcon(imgg);
    ObjectOutputStream out = new ObjectOutputStream(conn.getOutputStream());
    out.writeObject(imgc);
    bi = null;
    imgg= null;
    imgc= null;
    out.flush();
    bi = bimg;
    imgg=(Image)bi;
    imgc = new ImageIcon(imgg);
    out.writeObject(imgc);
    out.flush();
    out.close();
    //System.out.println("file saved...");
    InputStream ins = conn.getInputStream();
    ObjectInputStream objin = new ObjectInputStream(ins);
    String msg = (String)objin.readObject();
    //System.out.println(msg.toString());
    catch (java.io.IOException io)
    //System.out.println("IOException ----->" + io);
    catch (Exception e)
    //System.out.psrintln("Exception " + e);
    }//End of Upload
    //Applet Init()
    public void init()
    js = JSObject.getWindow(this);
    hostname = getCodeBase().getHost();
    port = getCodeBase().getPort();
    //System.out.println("HostName -->" + hostname );
    //System.out.println("port -->" + port);
    JButton buttcolor = new JButton("Choose Color");
    JButton front = new JButton("Front");
    JButton back = new JButton("Back");
    /*JButton save = new JButton("Save");*/
    img = getImage(getDocumentBase(),getParameter("img"));
    //System.out.println(getDocumentBase() +" \\ "+getParameter("img"));
    canvas = new ShapeCanvas(img);
    imgback = getImage(getDocumentBase(),getParameter("imgback"));
    backcanvas = new ShapeCanvas(imgback);
    scalingfactor = (float) 1.0;
    // txtimgflag = 2;
    getContentPane().setLayout(null);
    getContentPane().setSize(325,300);
    io = (ImageObserver)this;
    addMouseListener(canvas);
    addMouseListener(backcanvas);
    JPanel top = new JPanel();
    JPanel bottom = new JPanel();
    top.add(front);
    top.add(back);
    top.setSize(425,50);
    top.setLocation(0,0);
    final JColorChooser colorchooser = new JColorChooser();
    final JFrame internalfrm = new JFrame("Please Choose the Colors");
    internalfrm.setSize(450,320);
    internalfrm.setVisible(false);
    internalfrm.getContentPane().add(colorchooser);
    canvas.setSize(425,370);
    canvas.setLocation(0,50);
    backcanvas.setSize(425,370);
    backcanvas.setLocation(0,50);
    backcanvas.setVisible(false);
    bottom.setLayout(null);
    buttcolor.setLocation(175,10);
    buttcolor.setSize(120,30);
    /*save.setLocation(220,10);
    save.setSize(120,30);*/
    l1.setLocation(10,45);
    l1.setSize(300,30);
    bottom.add(l1);
    bottom.add(buttcolor);
    /*bottom.add(save);*/
    bottom.setSize(425,100);
    bottom.setLocation(0,420);
    bottom.setBackground(Color.lightGray);
    getContentPane().add(top);
    getContentPane().add(bottom);
    getContentPane().add(backcanvas);
    getContentPane().add(canvas);
    //sets Background of two panels i.e front and back
    colorchooser.getSelectionModel().addChangeListener(new ChangeListener()
    public void stateChanged(ChangeEvent e)
    canvas.setBackground(colorchooser.getColor());
    backcanvas.setBackground(colorchooser.getColor());
    //Shows Color Chooser
    buttcolor.addActionListener(new ActionListener()
    public void actionPerformed(ActionEvent e)
    internalfrm.setVisible(true);
    //Show back panel and hide front
    back.addActionListener(new ActionListener()
    public void actionPerformed(ActionEvent e)
    canvas.setVisible(false);
    backcanvas.setVisible(true);
    //backcanvas.repaint();
    //Show front panel and hide back
    front.addActionListener(new ActionListener()
    public void actionPerformed(ActionEvent e)
    backcanvas.setVisible(false);
    canvas.setVisible(true);
    *Save Image a call to UploadIamge
    save.addActionListener(new ActionListener()
    public void actionPerformed(ActionEvent e)
    uploadImage(canvas.bimg,backcanvas.bimg);
    drawIt();
    repaint();
    } //End of Applet Init();
    //Generates a Action Event calling ActionPerformed
    public void drawIt()
    ActionEvent evt=new ActionEvent(this,1,"HTML");
    if(canvas.isVisible())
    canvas.actionPerformed(evt);
    else
    backcanvas.actionPerformed(evt);
    //Paint of Applet
    public void paint(Graphics g)
    super.paint(g);
    //Update of Applet
    public void update(Graphics g)
    paint(g);
    //A panel Implemented to have Images Drawn on it
    static class ShapeCanvas extends JPanel implements ActionListener, MouseListener, MouseMotionListener,Runnable
    ArrayList shapes = new ArrayList();
    Color currentColor = Color.red;
    Image limg;
    BufferedImage bimg = new BufferedImage(430,400,BufferedImage.TYPE_INT_ARGB);
    Thread t = new Thread(this);
    ShapeCanvas(Image img)
    limg = img;
    addMouseListener(this);
    addMouseMotionListener(this);
    this.setBackground(Color.white);
    // t.start();
    zx = this.size().width / 2;
    zy = this.size().height / 2;
    zwidth = limg.getWidth(this);
    zheight =limg.getHeight(this);
    System.out.println("The parameter are"+zwidth+"and"+zheight);
    t.start();
    public void run()
    try
    for(int i=0;i<25;i++)
    repaint();
    t.sleep(250);
    repaint();
    catch(InterruptedException iee)
    public void updateComponent(Graphics g)
    paintComponent(g);
    public void deleteit(Shape shapetodelete)
    if(shapeBeingEdited != null)
    shapes.remove(shapeBeingEdited);
    repaint();
    public void paintComponent(Graphics go)
    //System.out.println("Called");
    super.paintComponent(go);
    go.drawImage(bimg,0,0,this);
    Graphics g = bimg.getGraphics();
    g.setColor(getBackground());
    g.drawRect(0,0,getSize().width,getSize().height);
    g.fillRect(0,0,getSize().width,getSize().height);
    g.drawImage(limg,0,0,this);
    /*zx = limg.size().width / 2;
    zy = this.size().height / 2;
    zwidth = limg.getWidth(this);
    zheight =limg.getHeight(this);*/
    zwidth *= scalingfactor;
    zheight *= scalingfactor;
    zx -= zwidth / 2;
    zy -= zheight /2;
    System.out.println("The values are"+zwidth);
    g.drawImage(limg, zx, zy, zwidth, zheight, this);
    int top = shapes.size();
    for (int i = 0; i < top; i++)
    s = (Shape)shapes.get(i);
    s.draw(g);
    g.dispose();
    go.dispose();
    public void actionPerformed(ActionEvent evt)
    //System.out.println(evt.getActionCommand());
    if(addnew == 1)
    //System.out.println("in new obj addnew "+ addnew);
    currentColor=Color.decode("1024");
    if(txtimgflag==0)
         System.out.println("string Function called");
    addShape(new StringShape(stringToDraw,fontmain,colormain,frocolor,msg,size,angle,str1,str2));
    else if(txtimgflag == 1)
    System.out.println("image function called");
    addShape(new ImageShape(someimg2));
    else if(txtimgflag==2)
    addShape(new ImageString(stringToDraw,fontmain,colormain,angle,size));
    System.out.println("txtimgflag in if else="+txtimgflag);
    else if(txtimgflag==3)
    addShape(new StyledString(stringToDraw,colormain,angle,size,str1,str2));
    System.out.println("txtimgflag in if else="+txtimgflag);
    repaint();
    void addShape(Shape shape)
    shape.setColor(currentColor);
    if(txtimgflag == 0)
    shape.reshape(150,80,100,20);
    shapes.add(shape);
    else if(txtimgflag == 1)
    shape.reshape(150,50,shape.width,shape.height);
    shapes.add(shape);
    else if(txtimgflag == 2)
    shape.reshape(150,50,100,100);
    shapes.add(shape);
    System.out.println("Image shape="+txtimgflag);
    else if(txtimgflag == 3)
    shape.reshape(150,60,100,100);
    shapes.add(shape);
    System.out.println("Image shape="+txtimgflag);
    repaint();
    Shape shapeBeingDragged = null;
    int prevDragX;
    int prevDragY;
    public boolean handleEvent (Event e)
    System.out.println("In zooming section");
    switch (e.id)
    case (Event.MOUSE_DOWN):
    oldy = e.y;
    return super.handleEvent(e);
    case (Event.MOUSE_UP):
    if (oldy > e.y)
    scalingfactor += (float) .1;
    else scalingfactor -= (float) .1;
    if (scalingfactor > (float) 5.0)
    scalingfactor = (float)5.0;
    if (scalingfactor < (float) .1)
    scalingfactor = (float).1;
    oldy = e.y;
    repaint();
    return super.handleEvent(e);
    default:
    return super.handleEvent(e);
    public void mousePressed(MouseEvent evt)
    int x = evt.getX();
    int y = evt.getY();
    for ( int i = shapes.size() - 1; i >= 0; i-- )
    Shape s = (Shape)shapes.get(i);
    if (s.containsPoint(x,y))
    shapeBeingDragged = s;
    shapeBeingDraggedtemp =s;
    shapeBeingEdited = s;
    prevDragX = x;
    prevDragY = y;
    // shapeBeingEdited = s;
    if(shapeBeingEdited instanceof ImageShape)
    try
    Object obj[] = new Object[2];
    obj[0]=new Integer(((ImageShape)shapeBeingEdited).width);
    obj[1]=new Integer(((ImageShape)shapeBeingEdited).height);
    js.call("setValuesimg",obj);
    System.out.println("found Image shape");
    catch (JSException ex)
    else if(shapeBeingEdited instanceof StringShape)
    try
    String foreColor=Integer.toHexString(((StringShape)shapeBeingEdited).Mycolor.getRGB() );
    foreColor=( foreColor.substring(2)).toUpperCase();
    String backColor=Integer.toHexString(((StringShape)shapeBeingEdited).frcolor.getRGB() );
    backColor=( backColor.substring(2)).toUpperCase();
    //System.out.println("found string shape");
    Object obj[] = new Object[7];
    obj[0] = ((StringShape)shapeBeingEdited).Mystring;
    obj[1] = ((StringShape)shapeBeingEdited).Myfont.getFontName();
    obj[2] = foreColor;
    obj[3] = ((StringShape)shapeBeingEdited).msg;
    obj[4] = backColor;
    obj[5] = ((StringShape)shapeBeingEdited).Siz;
    obj[6] = ((StringShape)shapeBeingEdited).ang;
    js.call("setValues",obj);
    catch (JSException ex)
    else if(shapeBeingEdited instanceof ImageString)
    System.out.println("bulls eye");
    if (evt.isShiftDown())
    shapes.remove(s);
    shapes.add(s);
    repaint();
    if(evt.isAltDown())
    shapes.remove(s);
    repaint();
    else
    l1.setText("");
    if(evt.isControlDown())
    if(s instanceof ImageShape)
    if(evt.getButton() == MouseEvent.BUTTON1)
    s.htwt((s.width+1),(s.height+1));
    repaint();
    else if(evt.getButton() == MouseEvent.BUTTON3)
    s.htwt((s.width-1),(s.height-1));
    repaint();
    return;
    }//end of if
    else
    //shapeBeingEdited = null;
    public void mouseDragged(MouseEvent evt)
    int x = evt.getX();
    int y = evt.getY();
    if (shapeBeingDragged != null)
    shapeBeingDragged.moveBy(x - prevDragX, y - prevDragY);
    prevDragX = x;
    prevDragY = y;
    repaint();
    /*if(globalGrahics == null)
    System.out.println("globalGrahics is null ");
    globalGrahics = this.getGraphics();
    else
    globalGrahics.setColor(Color.CYAN);
    globalGrahics.drawRect(shapeBeingEdited.left,shapeBeingEdited.top,shapeBeingEdited.width+10,shapeBeingEdited.height);
    public void mouseReleased(MouseEvent evt)
    int x = evt.getX();
    int y = evt.getY();
    if (shapeBeingDragged != null) {
    shapeBeingDragged.moveBy(x - prevDragX, y - prevDragY);
    if ( shapeBeingDragged.left >= getSize().width || shapeBeingDragged.top >= getSize().height ||
    shapeBeingDragged.left + shapeBeingDragged.width < 0 ||
    shapeBeingDragged.top + shapeBeingDragged.height < 0 )
    //shapes.remove(shapeBeingDragged);
    if(x <=20 || y <= 20 || x >340 || y >330)
    shapeBeingDragged.left = (150);
    shapeBeingDragged.top = (100);
    repaint();
    shapeBeingDragged = null;
    repaint();
    public void mouseEntered(MouseEvent evt){repaint();}
    public void mouseExited(MouseEvent evt){}
    public void mouseMoved(MouseEvent evt)
    if(evt.isControlDown())
    l1.setText("Left Click on Image to Zoom in , Right to Zoom out");
    else if(evt.isAltDown())
    l1.setText("Click on Image or Text to Delete");
    else if(evt.isShiftDown())
    l1.setText("Click on Image to bring it forward");
    else
    l1.setText("");
    public void mouseClicked(MouseEvent evt)
    int x = evt.getX();
    int y = evt.getY();
    if(evt.getClickCount()>=2)
    for ( int i = shapes.size() - 1; i >= 0; i-- )
    Shape s = (Shape)shapes.get(i);
    if (s.containsPoint(x,y))
    shapeBeingEdited = s;
    }//end of shapeCanvas
    static abstract class Shape
    int left, top;
    int width, height;
    Color color = Color.white;
    void reshape(int left, int top, int width, int height)
    this.left = left;
    this.top = top;
    this.width = width;
    this.height = height;
    void htwt(int width,int height)
    this.width = width;
    this.height = height;
    void moveBy(int dx, int dy)
    left += dx;
    top += dy;
    void setColor(Color color)
    this.color = color;
    boolean containsPoint(int x, int y)
    if (x >= left && x < left+width && y >= top && y < top+height)
    return true;
    else
    return false;
    abstract void draw(Graphics g);
    }//end of abstarct shape class
    static class StringShape extends Shape
    String Mystring;
    Font Myfont ;
    Color Mycolor;
    Color frcolor;
    String msg="",font;
    Integer Siz,ang;
    int font_size;
    int w,size,angle,w1,style;
    int speed= 12;
    StringShape(String lstr,Font lfont,Color lcolor,Color lfcolor,String lmsg,int lsiz,int lang,String lfon,int lsty)
    Mystring = lstr;
    Myfont = lfont;
    Mycolor = lcolor;
    frcolor = lfcolor;
    size=lsiz;
    msg = lmsg;
    angle=lang;
    Siz= new Integer(lsiz);
    style=lsty;
    font=lfon;
    System.out.println("In the String shape");
    int ShiftNorth(int p, int distance)
    return (p - distance);
    int ShiftSouth(int p, int distance)
    return (p + distance);
    int ShiftEast(int p, int distance)
    return (p + distance);
    int ShiftWest(int p, int distance)
    return (p - distance);
    BufferedImage bimg,temp,bimg1,bimg2,bimg3;
    void draw(Graphics g)
    g.setColor(Mycolor);
    g.setFont(this.Myfont);
    int wt=g.getFontMetrics().stringWidth(Mystring);
    int ht=g.getFontMetrics().getHeight();
    this.htwt(wt,ht);
    int h1=size ;
    temp = new BufferedImage(10,10,BufferedImage.TYPE_INT_ARGB);
    Graphics lgimg = temp.getGraphics();
    Graphics2D gimg = (Graphics2D)lgimg;
    gimg.setFont(Myfont);
    gimg.setColor(Mycolor);
    int w2=g.getFontMetrics().stringWidth(Mystring);
    int len=Mystring.length();
    int w1=(w2*len);
    this.htwt(w1,w2);
    System.out.println("The length"+len);
    bimg = new BufferedImage(w1,w1,BufferedImage.TYPE_INT_ARGB);
    temp=null;
    lgimg = bimg.getGraphics();
    gimg = (Graphics2D)lgimg;
    gimg.setFont(Myfont);
    gimg.setColor(Mycolor);
    if(msg.equals("outlined"))
    w2=g.getFontMetrics().stringWidth(Mystring);
    System.out.println("tWidth"+w2+"theight"+h1);
    len=Mystring.length();
    w1=(w2*len);
    bimg1 = new BufferedImage(w1,w1,BufferedImage.TYPE_INT_ARGB);
    lgimg = bimg1.getGraphics();
    gimg = (Graphics2D)lgimg;
    System.out.println("Message --> " + msg);
    gimg.setColor(Mycolor);
    gimg.drawString(this.Mystring, ShiftWest((left+5), 1), ShiftNorth((top+Myfont.getSize()), 1));
    gimg.drawString(this.Mystring, ShiftWest((left+5), 1), ShiftSouth((top+Myfont.getSize()), 1));
    gimg.drawString(this.Mystring, ShiftEast((left+5), 1), ShiftNorth((top+Myfont.getSize()), 1));
    gimg.drawString(this.Mystring, ShiftEast((left+5), 1), ShiftSouth((top+Myfont.getSize()), 1));
    g.drawImage(bimg1,left+5,top,null);
    gimg.setColor(frcolor);
    gimg.drawString(this.Mystring, ShiftEast((left+5), 1), ShiftSouth((top+Myfont.getSize()), 1));
    g.drawImage(bimg1,left+5,top,null);
    else if(msg.equals("segment"))
    System.out.println("Message --> " + msg);
    int w = (g.getFontMetrics()).stringWidth("Segment");
    int h = (g.getFontMetrics()).getHeight();
    int d = (g.getFontMetrics()).getDescent();
    g.setColor(Mycolor);
    g.drawString(this.Mystring, (left+5), (top+Myfont.getSize()));
    g.setColor(frcolor);
    for (int i = 0; i < h; i += 3)
    g.drawLine((left+5), (top+Myfont.getSize()) + d - i, (left+wt) + w, (top+Myfont.getSize()) + d - i);
    else if(msg.equals("3d"))
    w2=g.getFontMetrics().stringWidth(Mystring);
    System.out.println("tWidth"+w2+"theight"+h1);
    len=Mystring.length();
    w1=(w2*len);
    bimg2 = new BufferedImage(w1,w1,BufferedImage.TYPE_INT_ARGB);
    lgimg = bimg2.getGraphics();
    gimg = (Graphics2D)lgimg;
    Color top_color = new Color(200, 200, 0);
    System.out.println("Message --> " + msg);
    for (int i = 0; i < 5; i++)
    gimg.setColor(top_color);
    gimg.drawString(this.Mystring, ShiftEast((left+4), i), ShiftNorth(ShiftSouth((top+Myfont.getSize()), i), 1));
    gimg.setColor(frcolor);
    gimg.drawString(this.Mystring, ShiftWest(ShiftEast((left+4), i), 1), ShiftSouth((top+Myfont.getSize()), i));
    gimg.setColor(Mycolor);
    gimg.drawString(this.Mystring, ShiftEast((left+4), 5), ShiftSouth((top+Myfont.getSize()), 5));
    g.drawImage(bimg2,left+10,top,null);
    else if(msg.equals("flow"))
    System.out.println("Message"+msg);
    int len1=Mystring.length();
    int lsize=size;
    int lleft =25;
    int ltop = g.getFontMetrics().getHeight();
    w1=g.getFontMetrics().stringWidth(Mystring);
    System.out.println("The value of w1 is"+w1);
    for(int j=0;j<Mystring.length();j++)
         w1=w1+size;
         System.out.println("Size"+w1);
    bimg3 = new BufferedImage(w1,w1,BufferedImage.TYPE_INT_ARGB);
    lgimg = bimg3.getGraphics();
    gimg = (Graphics2D)lgimg;
    gimg.setFont(new Font(font,style,lsize));
    gimg.setColor(Mycolor);
    for (int i = 0; i<Mystring.length(); i++)
    gimg.setFont(new Font(font,style,lsize));
    ltop= ltop+5;
    gimg.drawString(""+Mystring.charAt(i),lleft,ltop);
    //gimg.drawRect(lleft,ltop-20,gimg.getFontMetrics().charWidth(Mystring.charAt(i)),gimg.getFontMetrics().getHeight());
    lleft=lleft+gimg.getFontMetrics().charWidth(Mystring.charAt(i));
    lsize = lsize + 5;
    g.setColor(Mycolor);
    // g.drawRect(left+5,top,bimg.getWidth(),bimg.getHeight());
    g.drawImage(bimg3,left+5,top,null);
    else
         // g.drawString(this.Mystring,(left+5),(top+Myfont.getSize()));
    gimg.drawString(Mystring,30,10);
    g.drawImage(bimg,left+10,top,null);
    }//end of Draw Function
    static class ImageShape extends Shape
    Image someimg;
    ImageShape(Image lsomeimg)
    someimg = lsomeimg;
    width = someimg.getWidth(null);
    height = someimg.getHeight(null);
    System.out.println("constr width "+width+ " height"+ height);
    this.htwtimg(width,height);
    void htwtimg(int width,int height)
    this.width = width;
    this.height = height;
    System.out.println("its from image");
    void draw(Graphics g)
    g.drawImage(this.someimg,left,top,width,height,io);
    }//END OF IMageShape Class
    static class ImageString extends Shape
    String bstring;
    int ang,siz;
    Font lfont;
    Color lcolor;
    ImageString(String istr,Font lfon,Color lclr,int lang,int lsiz)
         bstring=istr;
         ang=lang;
         siz=lsiz;
         lfont=lfon;
         lcolor=lclr;
    BufferedImage bimg,temp;
    public void draw(Graphics g)
    int h=siz;
    temp = new BufferedImage(10,10,BufferedImage.TYPE_INT_ARGB);
    Graphics lgimg = temp.getGraphics();
    Graphics2D gimg = (Graphics2D)lgimg;
    gimg.setFont(lfont);
    System.out.println("Font is"+lfont);
    gimg.setColor(lcolor);
    int w=g.getFontMetrics().stringWidth(bstring);
    System.out.println("tWidth"+w+"theight"+h);
    int len=bstring.length();
    int w1=(w*len);
    System.out.println("The length"+len);
    bimg = new BufferedImage(w1,w1,BufferedImage.TYPE_INT_ARGB);
    temp=null;
    lgimg = bimg.getGraphics();
    gimg = (Graphics2D)lgimg;
    gimg.setFont(lfont);

    can you tell in short what are you doing and what you wish to do.

Maybe you are looking for