Dynamically size movieclip to fit text's string height and width

Hello,
I am trying to dynamically size a movieclip to fit the size of a text's string height and width (This text is inside the movieclip)
here is my code so far..
var Font1_ = new Font1();
var Format2:TextFormat = new TextFormat();
Format2.size = 36;
Format2.align = TextFormatAlign.CENTER;
Format2.font = Font1_.fontName;
var MessageBox:MovieClip = new MessageBoxMC();
MessageBox.Text1.defaultTextFormat = Format2;
MessageBox.Text1.embedFonts = true;
MessageBox.Text1.antiAliasType = AntiAliasType.ADVANCED;
MessageBox.Text1.wordWrap = true;
MessageBox.Text1.width = 800;
MessageBox.Text1.height = 400;
MessageBox.Text1.textColor = 0xFFFFFF;
MessageBox.Text1.cacheAsBitmap = true;
MessageBox.Text1.mouseEnabled = false;
MessageBox.Text1.text = String("Use the Arrow Buttons to move");
MessageBox.width = MessageBox.Text1.width;
MessageBox.height = MessageBox.Text1.height;
  MessageBox.x = 400;
  MessageBox.y = 200;
  addChild(MessageBox);
this isn't working for me.. anyone know the best way to do this?
I also want the text to be centered in the movieclip, with a border of around 2-4 pixels
I am also not sure if i should be using text.length? any advice and input is greatly welcomed.
thanks in advance!

Essentially, you need to check for a change in .textWidth or .textHeight, which are different from .width and .height.
This code works for me (assumes a background box called bg and a foreground text instance fg inside a moveclip and an X and Y bounds offset variable to say how far away you want the box from the text and a textFrameNudge to provide a tweak value).
     // Resize background box
     thisBox.bg.x = thisBox.fg.x - boundsOffsetX + textFrameNudge; // I'm using .4 as the tweak value for textFrameNudge
     thisBox.bg.y = thisBox.fg.y - boundsOffsetY;
     thisBox.bg.width = thisBox.fg.textWidth + boundsOffsetX*2 +textFrameNudge*thisBox.fg.getTextFormat().size;
     thisBox.bg.height = thisBox.fg.textHeight + boundsOffsetY*2;

Similar Messages

  • Dynamically read height and width dimensions of .mov

    Hi there!
    I am wondering if anyone knows of a way to dynamically get the height and width dimensions of a quicktime movie, before streaming it?
    The circumstances are this. I have clients who upload quicktime movies to my server. Right now, I use code to embed movies in a fixed size page, but the movies can vary quite dramatically in terms of their dimensions. For example, if the movie is 400px wide, it looks fine in my page. However, if it is 800px wide, it extends out beyond the borders of my page and looks terrible. I could just make a huuge page, but then the tiny movies look ridiculous
    If I could somehow gets the dimensions of a movie before it starts streaming, i could create a large target page for larger movies, and a small target page for small movies. Basically it comes down to being able to somehow dynamically read the dimenions of the movie.
    Is this even possible? Like my boss keeps telling me, it's all just Math isn't it?
    Thanks!!!

    Hmmm...
    I think the movie dimensions are exposed to JavaScript, but only after the movie has opened. So you would have to load the movie into the plugin, then get the dimensions, then use JavaScript to rewrite the page. Which I don't think is quite what you had in mind; you're wanting to collect this information and deal with it before you write the page.
    Let me see if I have this straight...You are allowing clients to upload movies to your server, and then you're hoping to generate an embedded movie page on the fly in PHP to display the movie just uploaded, correct?
    For a library of movies, you could generate a small database of all the movie dimensions, then just look that data up in the table when you generate the page. The trouble is, I don't know of any way to get the movie dimensions except to get them from QuickTime, and to do that you have to load the movie into either the player or the plugin. You could, for instance, have an AppleScript that looks at each movie and populates the database, but I don't see how you could trigger that to run on upload, and I don't know what kind of server you're using.
    Now here's an idea...If you have some way of arbitrarily reading and parsing the QuickTime file, you can get the dimensions out of the file, but it isn't easy. If you are lucky, the moov atom will include a prfl atom (movie profile) which includes the video dimensions. But the prfl atom is not mandatory, which means you have to look at each trak atom that contains video and examine the size *and position* and accommodate the fact that you may have multiple, overlapping video tracks. But you could get the data by parsing the QT atoms yourself. All the data you need to do that is here:
    http://developer.apple.com/documentation/QuickTime/QTFF/QTFFPreface/chapter1_section1.html
    ...and may God have mercy on your soul!
    Seriously, though, you CAN parse a QT file, and that might be the best (though obviously not the easiest!) way to get the data you want dynamically. QuickTime does help you out by giving you all the offsets for all the atoms, but it can be tricky!
    --Dave Althoff, Jr.

  • Dynamically changing the height and width of Stage

    Hi,
              I would like to know how can I change the height and width of stage dynamically. I tried it with the following code:
                             Stage.height = 250;
                             Stage.width = 250;
    during the run time. Initially the Stage is at a height and width of 370 and 450 respectively. Also when I tried to trace the height and width of Stage after resizing the stage width and height, its showing the old value of width and height. That means the width and height not chnaging. Anybody have any idea about this.

    Hi Ross,
                I could understand something about the problem after making a research on this topic. We can't change the width and height of stage from actionscript itself, right? I will explain the way I am planning to do. I don't know whether its right or not. Anyway you just go through it. First the player need to be resized, according to the specified height and width. Then in the object tag, there are two fields named height and width. We should change these value according to the specified height and width of video controller, dynamically. Am I right? But I am confused with two properties of Stage such as: align and scaleMode. The code was actually developed my trainer. There, the scaleMode is set to "noScale" and no align property is used. My doubt is how should I set align and scaleMode properties of Stage. Hope you understood what I meant.
    Regards,
          Sreelash.S.

  • Diagram Optimize Shape Size Height and Width

    What determines the dimensions set by the Jdeveloper 11g menu option of Diagram.Optimize Shape Size.Height and Width while editing a Database Diagram ?
    I was hoping that this option resizes the dimensions of a box that represents a table to fully display all the columns, types and keys within the limits set by Tools.Preferences.Diagrams.Database.Max Compartment Entriesand Max Shape Width.
    I set
    Tools.Preferences.Diagrams.Database.Max Compartment Entries = 100
    Max Shape Width = 1000
    However, what I observe when using this option in a Database Diagram is that the box height is resized to show the first 15 column names and an ellipsis and the box width is less than the width of many of the column name rows.
    Does anyone else think this is a bug? If so, I will open an SR.

    Update:
    The limits set by Tools.Preferences.Diagrams.Database.Max Compartment Entries and Max Shape Width affect the default values for subsequently created shapes and not existing shapes.
    However, a Service Request has confirmed that changing the value for Max Compartment Entries has no effect. This behavior has been filed as a bug that will hopefully be fixed in the next release of Jdeveloper 11g.

  • Adjusting Text Height and Width using the Move Tool...

    I have yet another question about using Type in PSE 5.0. I know you can adjust a particular types size by using the font drop down menu and clicking on any of the listed sizes or you can type in a custom size as well.
    Is it though, ok to expand the Type/Text by selecting it with the Move tool and then enlarging it by using the selection handles located on the Box surrounding the text? I know you can do this, but I am wondering if you run the risk of creating a jagged look or pixalizing the text this way. The text is still vector based at this point, so I am thinking that it shouldn't be a problem, but wanted to know if it could look pixaly upon printing. I have found that I can sometimes get the text to look more the way I want using this method rather than just relying on changing the font size.
    Thanks,
    Lee

    I believe you can achieve this by using the Move Tool, clicking on any one of the resizing handles surrounding the Box which the Move Tool creates when you select an object using it, and then just drag the resizing handles to expand your text to your liking.
    If you press on a corner handle and press the shift-key at the same time while you drag, you should maintain the aspect ratio of your text.
    But that's what my original question is above. By expanding or contracting the text in this way, are you running the risk of things looking jagged and/or pixaly. Is it okay to expand/contract text using the Move Tool or you should you only adjust by setting the Font size.
    Lee

  • Calculating Height and Width of Text String in 6.1

    We have a vi that uses a CIN. It takes in a specified font and string
    and x,y origin and calculates the rectangular area of the given text.
    We have been using this VI since LabVIEW 4. Unfortunately, it will not
    work in LV6.1 and causes the compatexport.cpp error documented at NI.
    It works in 6.0.2, but not in 6.1. I believe that this VI was
    downloaded from somewhere, but the name was changed long ago. I'm
    wondering if anyone has a simiar VI that works with LV 6.1.
    When I choose the create .c file I get:
    * CIN source file
    #include "extcode.h"
    * typedefs
    typedef struct {
    LStrHandle Font_Name_;
    int16 Size;
    LVBoolean Strikeout_;
    LVBoolean Italic_;
    LVBoolean Underline_;
    LVBoolean Outline_;
    LVBool
    ean Shadow_;
    LVBoolean Bold_;
    uInt16 desired_font_application_;
    } TD1;
    typedef struct {
    int16 horizontal;
    int16 vertical;
    } TD2;
    CIN MgErr CINRun(LStrHandle text, TD1 *_user_specified_font_, int32
    *var3, TD2 *origin_0_0_);
    CIN MgErr CINRun(LStrHandle text, TD1 *_user_specified_font_, int32
    *var3, TD2 *origin_0_0_) {
    /* ENTER YOUR CODE HERE */
    return noErr;

    There is a vi in the picture library called "Get Text Rect.vi" that will give you a cluster of the four points that make up the rectangle around a given text string with the provided font. I'm attaching a small example that demonstrates this.
    Brian
    Attachments:
    TextRect.vi ‏47 KB

  • How to get the exact Height and width of the text in TextLayout Framework

    Hello fellow developers,
    I start working with TLF when there is three different SWC's Now I am working with Single SWC with flex 4 and lot of things are changed like
    I use calculateHeight(),calculateWidth()  now these methods are not available.
    Please if anyone know the replacement of these methods then Let me know.
    thanks

    If the text exceeds the container, which can happen in a scrollable container where you have to scroll to see some of the text, then the values getContentBounds returns are estimated values. This is because we don't want to force the text to recompose all the way to the end of a very long TextFlow in order to return a value. However, if you want to get the exact amount, and don't mind taking the time to recompose, call textFlow.flowComposer.composeToPosition(), before calling getContentBounds. This forces all the text to recompose to the end, and then getContentBounds will return the fully calculated value instead of estimating.

  • A script to increase the minimum canvas size? (Like Fit Image, but with just my canvas)

    For starters to be clear, I'm looking to manipulate canvas size. Not image size.
    I want to create a script to automatically increase the width and height of my canvas in Photoshop to a specific size when necessary. I only want this to happen if my canvas is less than that specified size. For example: Let's say my canvas size is 300x250. I want the canvas to be at LEAST 600x600. If I run my action it will increase the canvas size to 600x600 for me. If I run this same script on an image where the canvas size is already 700x700, it won't do anything at all to it because both the width and height are equal to or greater than my target size.
    It would also need to work with the height and width on an individual basis. If my image is 400x800, the action would increase my width from 400 to 600, but it would leave the height of 800 alone. So the final canvas size will end up being 600x800.
    It's kind of like the "Fit Image" option in Photoshop, but I only want to manipulate my canvas size, NOT my image size.

    It is possible.
    But if you hope that the dialog remembers the last settings that would require storing those values (which could be done with a txt-file at some pre-defined location), but it would make the Script a bit more complicated.
    // resize canvas in either direction if it is below a defined minimum;
    // 2011; use it at your own risk;
    #target photoshop
    if (app.documents.length > 0) {
    // dialog;
    var dlg = new Window("dialog", "increase width and height if under", [500,300,750,380]);
    // filter for checking if entry is numeric, thanks to xbytor;
    numberKeystrokeFilter = function() {
              if (this.text.match(/[^\-\.\d]/)) {
                        this.text = this.text.replace(/[^\d]/g, "")
              if (Number(this.text <= 0)) {this.text = 5};
              this.text = Math.round(Number(this.text));
    // fields for entry;
    dlg.hor = dlg.add("edittext", [14,15,88,35], "600", {multiline:false});
    dlg.hor.onChange = numberKeystrokeFilter;
    dlg.horText = dlg.add("statictext", [93,15,118,35], "px", {multiline:false});
    dlg.ver = dlg.add("edittext", [129,15,210,35], "600", {multiline:false});
    dlg.ver.onChange = numberKeystrokeFilter;
    dlg.verText = dlg.add("statictext", [215,15,240,35], "px", {multiline:false});
    dlg.hor.active = true;
    // ok- and cancel-button;
    dlg.buildBtn = dlg.add("button", [13,45,118,68], "OK", {name:"ok"});
    dlg.cancelBtn = dlg.add("button", [128,45,240,68], "Cancel", {name:"cancel"});
    // show dialog;
    dlg.center();
    // show dialog;
    var myReturn = dlg.show ();
    // proceed if ok-ed;
    if (myReturn == 1) {
    var myDocument = app.activeDocument;
    // set to pixels;
    var originalRulerUnits = app.preferences.rulerUnits;
    app.preferences.rulerUnits = Units.PIXELS;
    // set the minimum values;
    var minWidth = Number(dlg.hor.text);
    var minHeight = Number(dlg.ver.text);
    // get current ones;
    var theWidth = myDocument.width;
    var theHeight = myDocument.height;
    // resize canvas;
    myDocument.resizeCanvas(Math.max(minWidth, theWidth), Math.max(minHeight, theHeight), AnchorPosition.MIDDLECENTER);
    // reset;
    app.preferences.rulerUnits = originalRulerUnits;

  • How to crate a dynamic size array, collection

    Hi,
    Can someone point me to some tutorial on how to create a dynamic size array. Actually I have multiple cursors and on different tables and want to loop through each cursor and get some values from each cursor and put it in an array. But don't know how to create or initialize an array as I don't know the size. Is there any other way.
    Here is what I am doing I have 6 cursors on different tables, I loop through each cursor and get some specific data that I need to place at one place after looping through all the cursors which then finally needs to be inserted in one table. But before the insert I need to validate each data so want to have all the data in some array or some other place for temporary storage from it's easier to do the validate and insert rather than while looping through the cursors as there may be duplicates which I am trying to remove.
    As this procedure will be called multiple times so wanted to save the cursor data in temporary array before inserting in the final table. Looking for some faster and efficient way.
    Any help is appreciated.
    Thanks

    guest0012 wrote:
    All the 6 cursors are independent and no relation i.e. can have a join and have one sql as no relationship in tables.If there is no relation, then what are your code doing combining unrelated rows into the same GTT/array?
    Now using GTT when I do an insert how do I make sure the same data doesnot already exists. i.e. GTT will only have one column. Then create a unique index or primary key for the GTT and use that to enforce uniqueness.
    So everytime I iterate over a cursor I have to insert into GTT and then finally again have to iterate over GTT and then do an insert in the final table which maybe a performance issue Which is why using SQL will be faster and more scalable - and if PL/SQL code/logic can be used to glue these "no relationship" tables together, why can't that not be done in SQL?
    that's why i was wondering if can use any kind of array or collection as it will be a collection of numbersAnd that will reside in expensive PGA memory. Which means a limit on the size of the collection/array you can safely create without impacting server performance, or even cause a server crash by exhausting all virtual memory and causing swap space to trash.
    and finally will just iterate ovr array and use FOR ALL for insert but don't know what will be the size of the array as I only know after looping the cursors the total number of records to be stored. So wondering if how to do it through collection/array is there a way to intialize the array and keep populating it with the data with defining the size before hand.You cannot append the bulk collect of one cursor into the collection used for bulk collecting another cursor.
    Collections are automatically sized to the number of rows fetched. If you want to manually size collection, the Extend() method needs to be used, where the method's argument specifies the number of cells/locations to add to the collection.
    From what you describe about the issue you have - collections are not the correct choice. If you are going to put the different tables's data into the same collection, then you can also combine those tables's data using a single SQL projection (via a UNION for example).
    And doing the data crunching side in SQL is always superior in scalability and performance, than doing it in PL/SQL.

  • IDCS3 "page size does not fit w margin/column" error when changing bleed

    Anyone know the source of this problem?
    After deselecting "allow pages to shuffle" my bleed automatically, mysteriously, changes from 0pt to 9pt. When i try to change it back, I get an error: "This page size does not fit with the current margin and column settings. . ."
    This happens on multiple docs.
    The problem occurs in both Tiger and Leopard.
    Help!
    Thanks

    I'm having the same problem in CS4 when I try to create a document. I zeroed out the margins and gutters too but I didn't have any luck. It's also inconsistent in my case. I can create a document the size of a US business card with a margin of 3p0 but when it get's to something bigger than that but smaller than a letter, no gutter or margin will work.
    But that only applies to document creation for some reason. So far, my workaround has been to create a default document and then resize it using the document setup after the fact. It's a pain and it's weird, but that's what I've had to do.
    If you've come up with a better solution since your post, I'm all ears.

  • Shortcut for Fit text on Box?

    Hi guys,
    Is there any way or shortcut for Illustrator CS 5 to Fit Texts as the same lenght of the Box Frame? This is a image sample
    http://www.pixentral.com/show.php?picture=1PwekCEGe3qN6mrq24V3UHC86svK8
    i have a shortcut in InDesign to do this and it is very useful when aligning differente text frames. If the frame does not fit its text content the alignment is not right. I know i can do it by hand, but when you have many blocks is way time consuming.
    Any help or ideas?
    Cheers,
    S

    On the other hand, it is nice the script adjust to the text frame but i guess it would be nicer if the fit would adjust to the right lenght of the text.
    "Length" should be avoided when describing dimensions. It can be interpreted as either horizontal or vertical. Use "height" and "width", not length. Better still, explicitly state horzontal or vertical.
    What would be nicer is for Adobe to take a look at its other vector drawing program (FreeHand) and discover a far superior interface for text objects. Then trash Illustrator's entirely ill-conceived, cumbersome, unintuitive, and limited "Area Type" vs. "Point Type" distinction.
    Enable the user to set any text object to auto-expand and auto-fit its contents either horizontally or vertically. FreeHand users have been able to do this to any text object with a mere double-click for decades. This can also be set to all the text objects in the document at once--a huge advantage for avoiding accidental overset text in map projects where hundreds of street labels are subject to the risk.
    InDesign needs this almost as badly.
    JET

  • Sizing movieclip to fit the dynamic Textfield

    I'm adding text to a movieclip as you can see below. The text is alomost not visible because it's so small. If I don't scale the movieclip then the text becomes clipped. I basically want the movieclip to be a tight container (the same size as the textfield) for the Textfield. The below does not work. How can I do this?
    for(var i:int = 0; i < group.length; i++)
           var t:TextField = new TextField();
           t.name=i.toString();
           t.text=group[i];
           var f:MovieClip = new MovieClip();
           f.addChild(t);
           f.width = t.textWidth;
           f.height = t.textHeight;
           f.y = 50*i;
           addChild(f);

    In case anyone else is having this problem, by adding this
    t.autoSize ="left";
    it fixed it.

  • How do I reference a dynamically created MovieClip from another MovieClip?

    Hi,
    I'd be grateful for any pointers to the following problem:
         I'm having trouble referencing dynamically created MovieClips (links in a side panel on a Flash website, created from an XML file) from the current MovieClip (the currently selected link).
         I wish to freeze the the link/MovieClip in its mouseOver state once it has been clicked - this part works. When a new link/MovieClip is clicked on, I wish to release the previously clicked-on link from its mouseOver state, which is what I've so far been unable to do.
         My problem seems to be referencing the previous link/MoveClip. I've used the trace statement trace(MovieClip(this).name) to determine that the MovieClips are named item0, item1, item2 and so on. However, I've been unable thus far to reference the previous clip thus far. I've tried to trace the route to the MovieClip from the stage, and also tried MovieClip(parent).item0.gotoAndStop and lots of other different permutations, but to no avail. It's the fact they seem to be in a container called 'panel' which is defeating me.
         Here's a live version I've uploaded, which might explain the problem better. Click on "UBER UNS" in the top menu bar to get to the page in question. It's the links on the left-hand side (Historie, Unser Team, etc.) which are the problem. You'll see that once they've been clicked on they remain in their mouseOver state.
         This is the code in question on the fla file, which is a file I did not create myself. The parts in black work fine; it's the red parts where the problem lies:
    import flash.display.MovieClip;
    panel.buttonMode = true;
    var lang:uint = 1;
    var url_Link:String=MovieClip(root).program.websiteXML .language[lang].pages.titlePage[MovieClip(root).program.linkPage].texts.pageList.txt[numT XT].@link;
    var urlPage:Number=Number(MovieClip(root).program.webs iteXML.language[lang].pages.titlePage[MovieClip(root).program.linkPage].texts.pageList.tx t[numTXT].@linkPage);
    var request:URLRequest;
    var linkIndex:uint;
    var lastClickedLink:MovieClip;   //This is supposed to store the last link that has been clicked - it doesn't work
    panel.addEventListener(MouseEvent.CLICK, clicLink);
    panel.addEventListener(MouseEvent.ROLL_OVER, mouseOverLink);
    panel.addEventListener(MouseEvent.ROLL_OUT, mouseOutLink);
    function mouseOverLink(event:MouseEvent):void {
          MovieClip(this).gotoAndPlay('s1');
    function mouseOutLink(event:MouseEvent):void {
          if(numTXT !== (linkIndex - 1)/5){         //freezes mouseOver state if this is the link for the current page
               MovieClip(this).gotoAndPlay('s2');
    function clicLink(event:MouseEvent):void {
          var linkpage:uint = MovieClip(root).program.linkPage;
          if (url_Link) {
               request = new URLRequest(url_Link);
               navigateToURL(request);
          } else {
               linkIndex = numTXT * 5 + 1;
               if(linkpage == 1){
                   MovieClip(root).chPages.cont.page_about_mc.page3Tu  rner_mc.gotoAndStop([linkIndex]);
              } else if (linkpage == 2){
                   MovieClip(root).chPages.cont.page3_mc.page3Turner_  mc.gotoAndStop([linkIndex]);
         lastClickedLink.gotoAndPlay('s2');  // this is supposed to release the previous clicked-on link from it's mouseOver state - doesn't work
         lastClickedLink = MovieClip(this).name;    //this is supposed to set the new link as the last link clicked after the old one has been released from it's mouseOver state - doesn't work
    If anyone can help, that would be great.

    What you might be after for that line is to use:
    lastClickedLink = MovieClip(event.currentTarget);
    For what you show, the name property of an object is a String, so I would expect you to be getting an error regarding trying to get a String to act like a MovieClip when you try to tell it to gotoAndPlay('s2').

  • Expanding text fields to fit text

    I have a customer who would like to be able to put large amounts of text into a text field and have it all print. The amount of text can vary, so he would like to have a box where he can enter the text and have the box size adjust to the amount of text entered, even to the point of adding extra pages if necessary. I have tried using the Expand to Fit option, but all that seems to do it allow the text to scroll while the box stays the same size. Is this something that is even possible? If so, how? Thanks.

    Hi there,
    Usually the "Expand to Fit" option under the Height property of the object is what you need.
    You also would have to make sure that your text field is "Allow Multiple Lines" & Field Format set to "Rich Text"
    Parents objects (subforms & page) are "Allow Page Breaks Within Content" and the Content set to "Flowed"
    And once those settings are set make sure that your text field is Expand to Fit on the Height property!
    Hope this help!

  • Fit the image to window width, window height and  the window size

    hi all
    here we wrote the code for "fit the image to window width, window height and the window size". we are facing some problems in it. and all these operations have to perform even after zooming operations are done.if the below code doesnt satisfy kindly provide appropriate code .
    thanks .
    import java.awt.*;
    import java.awt.event.*;
    import java.awt.image.*;
    import java.awt.image.BufferedImage;
    import java.io.*;
    import javax.imageio.ImageIO;
    import javax.swing.*;
    import java.io.File;
    import javax.swing.filechooser.FileFilter;
    import java.awt.geom.*;
    public class DP extends JFrame implements ActionListener,
                                               MouseListener,
                                               MouseMotionListener {
        private final int PEN_OP = 1;
        private final int CLEAR_OP = 2;
        private int radius;
        private int radius1;
        private int mousex = 0;
        private int mousey = 0;
        private int prevx = 0;
        private int prevy = 0;
        private boolean initialFreeHand = true;
        private boolean initialLine = true;
        private boolean initialEraser = true;
        private int Orx = 0;
        private int Ory = 0;
        private int OrWidth = 0;
        private int OrHeight = 0;
        private int drawX = 0;
        private int drawY = 0;
        private int polyX = 0;
        private int polyY = 0;
        private int eraserLength = 5;
        private int udefRedValue = 255;
        private int udefGreenValue = 255;
        private int udefBlueValue = 255;
        private int opStatus = PEN_OP;
        private int colorStatus = 1;
        private double zoomPercentage=10;
        private Color mainColor = new Color(0, 0, 0);
        private Color xorColor = new Color(255, 255, 255);
        private Color userDefinedColor =
            new Color(udefRedValue, udefGreenValue,udefBlueValue);
        private JButton openButton = new JButton("open");
        private JButton closeButton = new JButton("close");
         private JButton zoominButton = new JButton("ZoomIn");
         private JButton zoomoutButton = new JButton("ZoomOut");
         private JButton zoomto100Button = new JButton("ZoomTo100");
         private JButton fwwButton = new JButton("Fit window width");
         private JButton fwhButton = new JButton("Fit window height");
         private JButton fwButton = new JButton("Fit the window");
        private JButton clearButton = new JButton("Clear");
        private JTextField colorStatusBar = new JTextField(20);
        private JTextField opStatusBar = new JTextField(20);
        private JTextField mouseStatusBar = new JTextField(10);
        private JPanel controlPanel = new JPanel(new GridLayout(18, 1, 0, 0));
        JToolBar jToolbar = new JToolBar();
        private Container container;
        private JScrollBar horizantalSlide=new JScrollBar();
        public BufferedImage image;
        BufferedImage bgImage;
    //    public ImageIcon icon=null;
        JFileChooser fileChooser;
        DrawPanel drawPanel = new DrawPanel(bgImage,zoomPercentage);
        public DP() {
            super("WhiteBoard");
            fileChooser = new JFileChooser(".");
            container = getContentPane();
            container.setBackground(Color.white);
            container.setLayout(new BorderLayout());
            container.add(jToolbar,BorderLayout.NORTH);
            container.add(horizantalSlide);
            jToolbar.add(openButton);
            jToolbar.add(closeButton);
              jToolbar.add(zoominButton);
              jToolbar.add(zoomoutButton);
              jToolbar.add(zoomto100Button);
              jToolbar.add(fwwButton);
              jToolbar.add(fwhButton);
              jToolbar.add(fwButton);
            jToolbar.add(clearButton);
            colorStatusBar.setEditable(false);
            opStatusBar.setEditable(false);
            mouseStatusBar.setEditable(false);
            controlPanel.setBackground(Color.white);
            drawPanel.setBackground(Color.white);
            container.add(controlPanel, "West");
            container.add(drawPanel, "Center");
            openButton.addActionListener(this);
            closeButton.addActionListener(this);
              zoominButton.addActionListener(this);
              zoomoutButton.addActionListener(this);
              zoomto100Button.addActionListener(this);
              fwwButton.addActionListener(this);
              fwhButton.addActionListener(this);
              fwButton.addActionListener(this);
            clearButton.addActionListener(this);
            drawPanel.addMouseMotionListener(this);
            drawPanel.addMouseListener(this);
            addMouseListener(this);
            addMouseMotionListener(this);
            opStatusBar.setText("FreeHand");
            colorStatusBar.setText("Black");
        public void actionPerformed(ActionEvent e) {
            if(e.getActionCommand().equals("open"))
                showDialog();
            if(e.getActionCommand().equals("close"))
                closeDialog();
              if(e.getActionCommand().equals("ZoomIn"))
                   drawPanel.zoom(1);
              if(e.getActionCommand().equals("ZoomOut"))
                   drawPanel.zoom(-1);
              if(e.getActionCommand().equals("ZoomTo100"))
                   drawPanel.zoom(+10);
              if(e.getActionCommand().equals("Fit window width"))
                   drawPanel.fitwindowwidth();
              if(e.getActionCommand().equals("Fit window height"))
                   drawPanel.fitwindowheight();
              if(e.getActionCommand().equals("Fit the window"))
                   drawPanel.fitthewindow();
            if (e.getActionCommand() == "Clear")
                opStatus = CLEAR_OP;
            switch (opStatus) {
                case CLEAR_OP:
                    clearPanel();
        private void showDialog() {
            if(fileChooser.showOpenDialog(this) == JFileChooser.APPROVE_OPTION) {
                File file = fileChooser.getSelectedFile();
                try {
                    bgImage = ImageIO.read(file);
                } catch(IOException e) {
                    System.out.println("IO error: " + e.getMessage());
                clearPanel();
        private void closeDialog() {
            drawPanel.setVisible(false);
            drawPanel.repaint();
        public void clearPanel() {
            opStatusBar.setText("Clear");
            Graphics g = image.getGraphics();
            g.setColor(drawPanel.getBackground());
            g.fillRect(0, 0, drawPanel.getBounds().width, drawPanel.getBounds().height);
            if(bgImage != null)
                g.drawImage(bgImage, 0, 0, this);
            g.dispose();
            drawPanel.repaint();
        public boolean mouseHasMoved(MouseEvent e) {
            return (mousex != e.getX() || mousey != e.getY());
        public void setActualBoundry() {
            if (mousex < Orx || mousey < Ory) {
                if (mousex < Orx) {
                    OrWidth = Orx - mousex;
                    drawX = Orx - OrWidth;
                } else {
                    drawX = Orx;
                    OrWidth = mousex - Orx;
                if (mousey < Ory) {
                    OrHeight = Ory - mousey;
                    drawY = Ory - OrHeight;
                } else {
                    drawY = Ory;
                    OrHeight = mousey - Ory;
            } else {
                drawX = Orx;
                drawY = Ory;
                OrWidth = mousex - Orx;
                OrHeight = mousey - Ory;
        public void setGraphicalDefaults(MouseEvent e) {
            mousex = e.getX();
            mousey = e.getY();
            prevx = e.getX();
            prevy = e.getY();
            Orx = e.getX();
            Ory = e.getY();
            drawX = e.getX();
            drawY = e.getY();
            OrWidth = 0;
            OrHeight = 0;
        public void mouseDragged(MouseEvent e) {
            updateMouseCoordinates(e);
            switch (opStatus) {}
        public void mouseReleased(MouseEvent e) {
            updateMouseCoordinates(e);
            switch (opStatus) {}
        public void mouseEntered(MouseEvent e) {
            updateMouseCoordinates(e);
        public void updateMouseCoordinates(MouseEvent e) {
            String xCoor = "";
            String yCoor = "";
            if (e.getX() < 0)
                xCoor = "0";
            else {
                xCoor = String.valueOf(e.getX());
            if (e.getY() < 0)
                xCoor = "0";
            else {
                yCoor = String.valueOf(e.getY());
            mouseStatusBar.setText("x:" + xCoor + " y:" + yCoor);
        public void mouseClicked(MouseEvent e) { updateMouseCoordinates(e); }
        public void mouseExited(MouseEvent e) { updateMouseCoordinates(e); }
        public void mouseMoved(MouseEvent e) { updateMouseCoordinates(e); }
        public void mousePressed(MouseEvent e) { updateMouseCoordinates(e); }
        public static void main(String[] args) {
            DP wb = new DP();
            wb.setDefaultCloseOperation(EXIT_ON_CLOSE);
            wb.setSize(1024,740);
            wb.setVisible(true);
        private class DrawPanel extends JPanel {
            private double m_zoom = 1.0;
            private double m_zoomPercentage;
            private BufferedImage m_image;
            double theta = 0;
            double thetaInc = Math.PI/2;
            public DrawPanel(BufferedImage imageb,double zoomPercentage) {
                m_image = imageb;
                m_zoomPercentage = zoomPercentage / 100;
            protected void paintComponent(Graphics g) {
                Graphics2D g2d=(Graphics2D)g;
                if(image == null)
                    initImage();
                g2d.setRenderingHint(RenderingHints.KEY_INTERPOLATION,
                                     RenderingHints.VALUE_INTERPOLATION_BICUBIC);
                double x = (1.0 - m_zoom)*getWidth()/2.0;
                double y = (1.0 - m_zoom)*getHeight()/2.0;
                AffineTransform at = AffineTransform.getTranslateInstance(x, y);
                at.rotate(theta,m_zoom*getWidth()/2,m_zoom*getHeight()/2);
                at.scale(m_zoom, m_zoom);
                g2d.drawRenderedImage(image, at);
      public void zoom(int inc) {
            m_zoom += inc * m_zoomPercentage;
            repaint();
              public void fitwindowwidth()
                int w1=drawPanel.getWidth();
                int h1=drawPanel.getHeight();
                BufferedImage image2=image.getScaledInstance(w1,h1,Image.SCALE_DEFAULT);
                drawPanel.setPreferredSize(new java.awt.Dimension(100,image2.getImage().getHeight(null)));
               drawPanel.repaint();
              public void fitwindowheight()
           BufferedImage image2=image.getScaledInstance(500,680,1); 
           drawPanel.setImage(iicon);
           drawPanel.setPreferredSize(new java.awt.Dimension(100,image2.getImage().getHeight(null)));
           drawPanel.repaint();
              public void fitthewindow()
           BufferedImage image2=image.getScaledInstance(1000,680,1);
           drawPanel.setPreferredSize(new java.awt.Dimension(100,image2.getImage().getHeight(null)));
           drawPanel.repaint();
            private void initImage() {
                int w = getWidth();
                int h = getHeight();
                image = new BufferedImage(w, h, BufferedImage.TYPE_INT_RGB);
                Graphics2D g2 = image.createGraphics();
                g2.setPaint(getBackground());
                g2.fillRect(0,0,w,h);
                g2.dispose();
    }

    thank you for giving reply.
    your code is very helpful to us.but i couldn't integrate it in my code.here's my code.
    import java.awt.*;
    import java.awt.event.*;
    import java.awt.image.*;
    import java.awt.image.BufferedImage;
    import java.io.*;
    import javax.imageio.ImageIO;
    import javax.swing.*;
    import java.io.File;
    import javax.swing.filechooser.FileFilter;
    import java.awt.geom.*;
    public class IS extends JFrame implements ActionListener,
                                               MouseListener,
                                               MouseMotionListener {
        private final int PEN_OP = 1;
        private final int CLEAR_OP = 2;
         private     final int DISTORT = 3;
        private final int SCALE   = 4;
        private final int FIT     = 5;
        private final int FILL    = 6;
        int scaleMode = SCALE;
        private int radius;
        private int radius1;
        private int mousex = 0;
        private int mousey = 0;
        private int prevx = 0;
        private int prevy = 0;
        private boolean initialFreeHand = true;
        private boolean initialLine = true;
        private boolean initialEraser = true;
        private int Orx = 0;
        private int Ory = 0;
        private int OrWidth = 0;
        private int OrHeight = 0;
        private int drawX = 0;
        private int drawY = 0;
        private int polyX = 0;
        private int polyY = 0;
        private int eraserLength = 5;
        private int udefRedValue = 255;
        private int udefGreenValue = 255;
        private int udefBlueValue = 255;
        private int opStatus = PEN_OP;
        private int colorStatus = 1;
        private double zoomPercentage=10;
        private Color mainColor = new Color(0, 0, 0);
        private Color xorColor = new Color(255, 255, 255);
        private Color userDefinedColor =
            new Color(udefRedValue, udefGreenValue,udefBlueValue);
        private JButton openButton = new JButton("open");
        private JButton closeButton = new JButton("close");
         private JButton zoominButton = new JButton("ZoomIn");
         private JButton zoomoutButton = new JButton("ZoomOut");
         private JButton zoomto100Button = new JButton("ZoomTo100");
         private JButton fwwButton = new JButton("Fit window width");
         private JButton fwhButton = new JButton("Fit window height");
         private JButton fwButton = new JButton("Fit the window");
        private JButton clearButton = new JButton("Clear");
        private JTextField colorStatusBar = new JTextField(20);
        private JTextField opStatusBar = new JTextField(20);
        private JTextField mouseStatusBar = new JTextField(10);
        private JPanel controlPanel = new JPanel(new GridLayout(18, 1, 0, 0));
        JToolBar jToolbar = new JToolBar();
        private Container container;
        private JScrollBar horizantalSlide=new JScrollBar();
        public BufferedImage image;
        BufferedImage bgImage;
    //    public ImageIcon icon=null;
        JFileChooser fileChooser;
        DrawPanel drawPanel = new DrawPanel(bgImage,zoomPercentage);
        public IS() {
            super("WhiteBoard");
            fileChooser = new JFileChooser(".");
            container = getContentPane();
            container.setBackground(Color.white);
            container.setLayout(new BorderLayout());
            container.add(jToolbar,BorderLayout.NORTH);
            container.add(horizantalSlide);
            jToolbar.add(openButton);
            jToolbar.add(closeButton);
              jToolbar.add(zoominButton);
              jToolbar.add(zoomoutButton);
              jToolbar.add(zoomto100Button);
              jToolbar.add(fwwButton);
              jToolbar.add(fwhButton);
              jToolbar.add(fwButton);
            jToolbar.add(clearButton);
            colorStatusBar.setEditable(false);
            opStatusBar.setEditable(false);
            mouseStatusBar.setEditable(false);
            controlPanel.setBackground(Color.white);
            drawPanel.setBackground(Color.white);
            container.add(controlPanel, "West");
            container.add(drawPanel, "Center");
            openButton.addActionListener(this);
            closeButton.addActionListener(this);
              zoominButton.addActionListener(this);
              zoomoutButton.addActionListener(this);
              zoomto100Button.addActionListener(this);
              fwwButton.addActionListener(this);
              fwhButton.addActionListener(this);
              fwButton.addActionListener(this);
            clearButton.addActionListener(this);
            drawPanel.addMouseMotionListener(this);
            drawPanel.addMouseListener(this);
            addMouseListener(this);
            addMouseMotionListener(this);
            opStatusBar.setText("FreeHand");
            colorStatusBar.setText("Black");
        public void actionPerformed(ActionEvent e) {
            if(e.getActionCommand().equals("open"))
                showDialog();
            if(e.getActionCommand().equals("close"))
                closeDialog();
              if(e.getActionCommand().equals("ZoomIn"))
                   drawPanel.zoom(1);
              if(e.getActionCommand().equals("ZoomOut"))
                   drawPanel.zoom(-1);
              if(e.getActionCommand().equals("ZoomTo100"))
                   drawPanel.zoom(+10);
              if(e.getActionCommand().equals("Fit window width"))
                   //drawPanel.fitwindowwidth();
              drawPanel.scaleImage(0,0,0,0);
              if(e.getActionCommand().equals("Fit window height"))
              drawPanel.scaleImage(0,0,0,0);
              if(e.getActionCommand().equals("Fit the window"))
              drawPanel.scaleImage(0,0,0,0);
            if (e.getActionCommand() == "Clear")
                opStatus = CLEAR_OP;
            switch (opStatus) {
                case CLEAR_OP:
                    clearPanel();
        private void showDialog() {
            if(fileChooser.showOpenDialog(this) == JFileChooser.APPROVE_OPTION) {
                File file = fileChooser.getSelectedFile();
                try {
                    bgImage = ImageIO.read(file);
                } catch(IOException e) {
                    System.out.println("IO error: " + e.getMessage());
                clearPanel();
        private void closeDialog() {
            drawPanel.setVisible(false);
            drawPanel.repaint();
        public void clearPanel() {
            opStatusBar.setText("Clear");
              int w = image.getWidth();
            int h = image.getHeight();
            Graphics g = image.getGraphics();
            g.setColor(drawPanel.getBackground());
            g.fillRect(0, 0, w, h);
            if(bgImage != null) {
                int x = (w - bgImage.getWidth())/2;
                int y = (h - bgImage.getHeight())/2;
                g.drawImage(bgImage, x, y, this);
            g.dispose();
            drawPanel.repaint();
        public boolean mouseHasMoved(MouseEvent e) {
            return (mousex != e.getX() || mousey != e.getY());
        public void setActualBoundry() {
            if (mousex < Orx || mousey < Ory) {
                if (mousex < Orx) {
                    OrWidth = Orx - mousex;
                    drawX = Orx - OrWidth;
                } else {
                    drawX = Orx;
                    OrWidth = mousex - Orx;
                if (mousey < Ory) {
                    OrHeight = Ory - mousey;
                    drawY = Ory - OrHeight;
                } else {
                    drawY = Ory;
                    OrHeight = mousey - Ory;
            } else {
                drawX = Orx;
                drawY = Ory;
                OrWidth = mousex - Orx;
                OrHeight = mousey - Ory;
        public void setGraphicalDefaults(MouseEvent e) {
            mousex = e.getX();
            mousey = e.getY();
            prevx = e.getX();
            prevy = e.getY();
            Orx = e.getX();
            Ory = e.getY();
            drawX = e.getX();
            drawY = e.getY();
            OrWidth = 0;
            OrHeight = 0;
        public void mouseDragged(MouseEvent e) {
            updateMouseCoordinates(e);
            switch (opStatus) {
        public void mouseReleased(MouseEvent e) {
            updateMouseCoordinates(e);
            switch (opStatus) {}
        public void mouseEntered(MouseEvent e) {
            updateMouseCoordinates(e);
        public void updateMouseCoordinates(MouseEvent e) {
            String xCoor = "";
            String yCoor = "";
            if (e.getX() < 0)
                xCoor = "0";
            else {
                xCoor = String.valueOf(e.getX());
            if (e.getY() < 0)
                xCoor = "0";
            else {
                yCoor = String.valueOf(e.getY());
            mouseStatusBar.setText("x:" + xCoor + " y:" + yCoor);
        public void mouseClicked(MouseEvent e) { updateMouseCoordinates(e); }
        public void mouseExited(MouseEvent e) { updateMouseCoordinates(e); }
        public void mouseMoved(MouseEvent e) { updateMouseCoordinates(e); }
        public void mousePressed(MouseEvent e) { updateMouseCoordinates(e); }
        public static void main(String[] args) {
            IS wb = new IS();
            wb.setDefaultCloseOperation(EXIT_ON_CLOSE);
            wb.setSize(1024,740);
            wb.setVisible(true);
        private class DrawPanel extends JPanel {
            private double m_zoom = 1.0;
            private double m_zoomPercentage;
            private BufferedImage m_image;
            double theta = 0;
            double thetaInc = Math.PI/2;
            public DrawPanel(BufferedImage imageb,double zoomPercentage) {
                m_image = imageb;
                m_zoomPercentage = zoomPercentage / 100;
            protected void paintComponent(Graphics g) {
                   super.paintComponent(g);
                Graphics2D g2d=(Graphics2D)g;
                if(image == null)
                    initImage();
                g2d.setRenderingHint(RenderingHints.KEY_INTERPOLATION,
                                     RenderingHints.VALUE_INTERPOLATION_BICUBIC);
                              int w = getWidth();
                    int h = getHeight();
                  int iw = image.getWidth();
                  int ih = image.getHeight();
                  if(scaleMode == SCALE) {
                double x = (w - m_zoom*iw)/2;
                double y = (h - m_zoom*ih)/2;
                AffineTransform at = AffineTransform.getTranslateInstance(x, y);
                at.rotate(theta,m_zoom*getWidth()/2,m_zoom*getHeight()/2);
                at.scale(m_zoom, m_zoom);
                g2d.drawRenderedImage(image, at);
                   else {
                scaleImage(w, h, iw, ih);
              private void scaleImage( int w, int h, int iw, int ih) {
                             Graphics2D g2d = image.createGraphics();
            double xScale = (double)w/iw;
            double yScale = (double)h/ih;
            AffineTransform at = new AffineTransform();
            if(scaleMode == DISTORT) {
                double x = (w - xScale*iw)/2;
                double y = (h - yScale*ih)/2;
                at.setToTranslation(x, y);
                at.scale(xScale, yScale);
            } else {
                double scale = (scaleMode == FIT) ? Math.min(xScale, yScale)
                                                  : Math.max(xScale, yScale);
                double x = (w - scale*iw)/2;
                double y = (h - scale*ih)/2;
                at.setToTranslation(x, y);
                at.scale(scale, scale);
            g2d.drawRenderedImage(image, at);
      public void zoom(int inc) {
            m_zoom += inc * m_zoomPercentage;
            repaint();
            private void initImage() {
                int w = getWidth();
                int h = getHeight();
                image = new BufferedImage(w, h, BufferedImage.TYPE_INT_RGB);
                Graphics2D g2 = image.createGraphics();
                g2.setPaint(getBackground());
                g2.fillRect(0,0,w,h);
                g2.dispose();
    }

Maybe you are looking for

  • Posting the Expenses of Free Goods

    All SD Gurus I have some doubt in SD-Module. We have Trading Business, in that the Trade offers ie 100+10 Like that.... is presently posting in VPRS - Cogs (During PGI) only. But finance wants to post the values of trade offers (10 pcs) to Marketting

  • Saving a file in Vi creates same file but with ~ added [SOLVED]

    Hi, I'm not sure if I pressed a key combination, but when I save a file in Vi I get another file that has the same name as the original file but with the ~ character added to the end of the filename.  For example, if I edit foo.txt and save it, then

  • Can't get javascript to change movie playing in web page

    I'm very new to web page development and scripting, so please bear with me. This is a test page I'm trying to get to work. Eventually there will be several images of different videos, and I want the different videos to play in one player, depending o

  • Credit Card Non-Use/Bank Termination - FICO Impact?

    Have recently received notification from issuing bank that as a result of non-use my MasterCard account is to be terminated.  No prior notification was received that this account was jeopardized.  Current FICO is in range of 780+.  How does this affe

  • In Piano Roll: no  "Show Selected Regions Only" View menu item !!

    I need to use this function, and it's not there! The Manual says it should be! Any one else have this problem, or know the answer? Thanks!