Get the width of characters

Hello everyone,
I have a question and I hope to find anyone who can answer it :-)
I am developing a Midlet (MIDP 1.0 CDLC 1.0) for which I am implementing my own forms. That means that I do not use the ChoiceGroup class (for example ) which is provided but I implement my own one.
To do so I am extending the canvas class, print everything on screen with g.drawString(...) (where g is a Graphics object) and handle the user input on my own.
The problem is that I have to do word wraps on my own. What I know is the width of the canvas object, but I do not know how many pixel are needed for a character. (Actuelly it seems like different characters need different numbers of pixels). Is there any possibility to get this information or is there any other possibility to implement the word wraps?
Thank you,
kellergeist

Well, I found the methode
public int stringWidth(String str) but I am not sure whether I understand the description
http://j2medevices.com/documentation/midp1.0/javax/microedition/lcdui/Font.html#charWidth(char)
Dies that mean that stringWidth returns the amount of pixels which is needed by the String?

Similar Messages

  • How to get the width of a numeric field at runtime

    Hi, everyone :D
    Is there a built-in that let me get the width of a numeric field at runtime? The SRW bulit in only has the SWR.GET_PAGE_NUM built-in. Is there something like the Get_item_property of Forms IN Report?
    Thanks
    Edited by: user12422762 on 07-ene-2010 14:16
    Edited by: user12422762 on 07-ene-2010 14:30
    Edited by: user12422762 on 08-ene-2010 4:40
    Edited by: user12422762 on 08-ene-2010 4:50

    Hi. Thanks for answering. I need the width because i want to set the format of the field at runtime. The quantity of decimal digits for all the numeric fieds in the report is received as a parameter.
    I can use a function to create the respective decimal mask ('D99,'D999',etc.) and then call the SRW.SET_FORMAT_MASK in the format trigger of every single field, but i'd have to type the mask of the integral part of the number in the code of the trigger ('99G999D99, '999G999G999D'). However, If i could get the width, i'd just create a function and call it from every format trigger.
    Edited by: user12422762 on 08-ene-2010 10:05
    Edited by: user12422762 on 08-ene-2010 10:06
    Edited by: user12422762 on 08-ene-2010 10:08

  • How can I get the width of window?

    Hi. I would like to get the width of window on IE.
    If on Netscape, I can use "window.inner(outer)Width".
    However, I don't know what to do with IE.
    I am sorry that this question might be very begginer.
    Thank you,

    and this is not a question taht in belongs in this forum! it is a IE/IE.Script question. perhaps you find an answer here: http://developer.irt.org/script/window.htm

  • How many ways are there to get the Width/Height of an image ?

    I am currently using the following code to get the width and hight of an image :
    BufferedImage Buffered_Image=ImageIO.read(new File(Image_Path));
    int Image_Width=Buffered_Image.getWidth();
    int Image_Height=Buffered_Image.getHeight();I don't need to get the image (*.jpg, *.gif, *.png), just want to know it's dimensions. I wonder how many other ways are available to do the same thing in a Java application ?
    Frank

    Ni_Min wrote:
    That's what I thought. I am asking because I hit a wall and am trying to find a different approach.Yeah, if you only have one file type you can probably write the code to read the header in 20 min.
    I packed my programs into an executable Jar file which I can run and access images on my C:\ drive, everything worked fine until I tried to experiment with something new. I know that I can force JVM to pre-load all my java classes just after it starts, so I deleted the jar right after the program pre-loaded all my classes and tried to see if it would work, but now I get a null pointer error when it tried to get the width/height of an existing image, because ImageIO.read return null. ( The same image is still on my C:\ drive )Sounds like a strange thing you're doing here. What's the point of this?
    So I wonder why it makes a difference after I deleted the jar, what was the problem ( or do I need to pre-load another class related to ImageIO.read ? ), and maybe if I use something else other than the ImageIO.read to get the width/height, I can bypass the problem.I dunno why you need to do this preload stuff and/or delete anything. I'd say leave the JVM and the app alone if possible.

  • Please Help!! How to get the width of the String for print out?

    Hi there,
    I need to do some printing in my application. I just want to know how can I get the width of the string when it is printed on the paper.
    I have tried to use the following code to get the width
    Rectangle2D rec = font.getStringBounds(str, new FontRenderContext(null, true, true));
    double width = rec.getWidth();
    however, the width I got from that function is not correct (the returned width is longer than the printed one)
    Does anyone know how to solve this problem?
    Thank you and Happy New Year !

    hi,
    The getFontMetrics(Font) is also defined in the Component class and therefore you can retrieve it even if you dont override the paint method.
    try the following (provided ur code extends some class that extends Component indirectly)
    FontMetrics f = this.getFontMetrics(this.getFont());
    int width = f.stringWidth(str); //str is the String for which u need to check the width.
    hope this was useful
    happy holidayz

  • How to get the width and height of the selected rectangle

    Hi,
         I need to get the width and height of the selected rectangle in indesign cs3 and display the values in a dialog box for user verification.
    Regards,
    saran

    Hi Saran,
    InterfacePtr<IGeometry> itemGeo ( objectUIDRef, UseDefaultIID() );
    PMRect ItemCoord = itemGeo->GetStrokeBoundingBox();
    PMReal width  = ItemCoord->Width();
    PMReal height = ItemCoord->Height();

  • Getting the width of a String, or centering it within the Applet.

    Hello,
    I want to get a String within the center of my 2D Applet, so I'm wondering if it's possible to get the width (and height) of the String in numbers, or even if it's possible to center like Microsof Word does. If one of the two is possible, please tell it me :)
    Thanks
    PS: I use fonts and a size for the font, could this create problems?
    Edited by: The_Pointer on Mar 27, 2009 3:34 PM
    Edited by: The_Pointer on Mar 27, 2009 3:34 PM

    Can someone explain the
    Graphics.getFontMetrics()
    x = (Component.getWidth() - Fontmetrics.stringWidth()) / 2 a little bit more please?
    Since I get the following errors
    C:\Documents and Settings\Robert van der Pijl\Bureaublad\Clock\clockApplet.java:66: non-static method getFontMetrics() cannot be referenced from a static context
              Graphics.getFontMetrics();
                      ^
    C:\Documents and Settings\Robert van der Pijl\Bureaublad\Clock\clockApplet.java:67: x is not public in java.awt.Component; cannot be accessed from outside package
              x = (Component.getWidth() - Fontmetrics.stringWidth()) / 2;
              ^
    C:\Documents and Settings\Robert van der Pijl\Bureaublad\Clock\clockApplet.java:67: non-static method getWidth() cannot be referenced from a static context
              x = (Component.getWidth() - Fontmetrics.stringWidth()) / 2;
                            ^
    C:\Documents and Settings\Robert van der Pijl\Bureaublad\Clock\clockApplet.java:67: cannot find symbol
    symbol  : variable Fontmetrics
    location: class clockApplet
              x = (Component.getWidth() - Fontmetrics.stringWidth()) / 2;
                                          ^
    4 errors

  • How do i get the width of a JPanel

    Hey
    Im trying to get the width of my JPanel with this code, but it just prints 0, what am i doing wrong?
    public class GamePanel extends JPanel implements Runnable {
         private static final int PWIDTH = 500;   // size of panel
         private static final int PHEIGHT = 400;
         private static final int NO_DELAYS_PER_YIELD = 16;     
         private static int MAX_FRAME_SKIPS = 5;
         private MovingGame frame;
         private Thread animator;
         private volatile boolean running = false;   // used to stop the animation thread
         private long gameStartTime;   // when the game started
         private BallSprite ball;
         //      off-screen rendering
         private Graphics dbg;
         private Image dbImage = null;
         //      holds the background image
         private BufferedImage bgImage = null;
         public GamePanel(MovingGame frame){     
              this.frame = frame;
              setDoubleBuffered(true);
              setBackground(Color.blue);
              setPreferredSize( new Dimension(PWIDTH, PHEIGHT));
              setFocusable(true);
              requestFocus();
              addKeyListener( new KeyAdapter() {
                   public void keyPressed(KeyEvent e)
                       { processKey(e);  }
              ball = new BallSprite(40, 40, this);
              System.out.println("Width: " + getWidth());    <------- this prints 0
         }

    veldhanas wrote:
    Hi,
    Use
    setSize(PWIDTH, PHEIGHT); instead of
    setPreferredSize( new Dimension(PWIDTH, PHEIGHT));ThanksWrong Wrong Wrong Wrong
    .setSize() sets the size of the component at that instant in time and has no effect on anything the layout managers do with the component. .setPreferredSize() sets the size the layout manager will look at (assuming it cares about what size you want the component at).

  • How to get the first 3 characters from the previous month?

    Hi,
    I need to get in a View Column only the first 3 characters of the previous month of data from the bellow query.
    SELECT ID, Department, Capital_Project_Number, 
    Capital_Site_Number, 
    Funding_Source, Milestone, 
    Account, Year, Month, Data
    FROM  Table
    Where Month = DATENAME(Month, DATEADD(Month, - 1, GETDATE())) and (Year = YEAR(GETDATE()));
    Go

     Left(DATENAME(Month, DATEADD(Month, - 1, GETDATE())),3)
    --Or
     convert( varchar(3), DATEADD(Month, - 1, GETDATE()),100)

  • How do I get the width of message I'm composing to not get too wide?

    When writing a message, it used to automatically return when it was as wide as the message. Now it just keeps getting wider and wider. How can I fix this?

    Maybe you have switched from composing in plain text to composing in HTML? In HTML the message text only goes to a new line when you give an enter. Otherwise it wraps at the tight side of the window. It will probably display the same way on the receiver's computer, depending on the width of his screen.
    You can try to see if this causes your problem, by holding the Shift key before clicking the Compose button, to start composing in the alternate way (e.g. in plain text instead of HTML).
    If you prefer plain text, you can change the configuration under Tools -> Account Settings -> [account] -> Composition & Addressing and toggle the preference Compose messages in HTML format.
    Note that this is a setting per account, and for news accounts it defaults to plain text...

  • Getting the JScrollPane width

    Hi all,
    I have created a JScrollPane into which I have added a JTable. However, I have two issues regarding column size:
    1. When the table is created, the columns do not take up a full row. I have set setAutoResizeMode(JTable.AUTO_RESIZE_OFF]; and instead, run a method that I created that automatically sets the size of each column based on the selected tree node. However, as soon as the columns are resized to my size, they are automatically resized back to their default small size. This only happens the first time when I'm loading the program.
    2. To resize the columns, I need the width of the JScrollPane. I use the following to get the width: messageList.getViewport().getWidth(); However, the width that is returned is a little bit wider than the JScrollPane width. I've tried subtracting the Insets widths from that, but didn't have any luck.
    Can someone suggest anything? My code for creating the JTable and resizing the columns is below.
    Please note that I call resizeMessageListColumns() from the method to which the JScrollPane is returned.
    *** Code that creates the JTable ***
    * Insert the method's description here.
    * Creation date: (8/17/2002 4:22:14 PM)
    * @return javax.swing.JTable
    public JTable createMessageList( String title )
         tableNames = setMessageListHeader(title);
         tableData = setMessageListData(title);
        // Create a model of the data.
         dataModel = new MailTableModel(tableData,tableNames);
        // Create the table
        tableView = new JTable(dataModel);
         // Show colors by rendering them in their own color.
        DefaultTableCellRenderer colorRenderer = new DefaultTableCellRenderer()
              public void setValue(Object value)
                 if (value instanceof Color)
                     Color c = (Color)value;
                     setForeground(c);
                     setText(c.getRed() + ", " + c.getGreen() + ", " + c.getBlue());
        tableView.setRowHeight(12);
        tableView.setBackground(Color.white);
        tableView.setColumnSelectionAllowed(false);
        tableView.setRowSelectionAllowed(true);
        tableView.setCellSelectionEnabled(false);
        tableView.setShowVerticalLines(false);
        // turn off autoresize
         tableView.setAutoResizeMode(JTable.AUTO_RESIZE_OFF);
        return tableView;
    }*** Resize the Rows ***
    * Insert the method's description here.
    * Creation date: (8/18/2002 11:50:48 AM)
    public void resizeMessageListColumns(String currentNode)
         // The total number of columns in this folder
         int numColumns = 0;
         // Total width available
         int totalWidth = messageList.getViewport().getWidth();
         // Remaining available width
         int remainingWidth = totalWidth;
         // absolute widths
         int[] finalWidths = new int[0];
         // Define Column Widths
         final double[] INBOX_COLUMN_SIZES =          { 20, 20, 0.30, 0.50, 20, 0.10, 0.10 };
    //                                                       {"Pr","Fg","Sender","Subject","At","Date","Size"};
         final double[] SENT_COLUMN_SIZES =          { 20, 0.30, 0.50, 20, 0.10, 0.10 };
    //                                                       {"Pr","Recipient","Subject","At","Date","Size"};
         final double[] DELETE_COLUMN_SIZES =     { 20, 0.30, 0.50, 20, 0.10, 0.10 };
    //                                                       {"Pr","Sender","Subject","At","Date","Size"};
         final double[] DRAFT_COLUMN_SIZES =          { 20, 20, 0.30, 0.50, 20, 0.10, 0.10 };
    //                                                       {"Pr","Fg","Recipient","Subject","At","Date","Size"};
         final double[] DEFAULT_COLUMN_SIZES =     { 20, 20, 0.30, 0.50, 20, 0.10, 0.10 };
    //                                                       {"Pr","Fg","Sender","Subject","At","Date","Size"};
         // now calculate aboslute widths of relative widths
         for (int i=0; i<numColumns; i++)
              if (INBOX_COLUMN_SIZES[i] < 1) // if this is an absolute size
                   finalWidths[i] = (int)(INBOX_COLUMN_SIZES[i] * totalWidth);
                   remainingWidth = (int)(INBOX_COLUMN_SIZES[i] * totalWidth);
         // Calculate Column Widths
         if (currentNode.equals(INBOX_TITLE))
              numColumns = INBOX_COLUMN_SIZES.length;
              // array where final widths are stored
              finalWidths = new int[numColumns];
              // now, start determining the size of the columns
              // this does not yet return the final size of each column
              // but only calculates the remaining width
              for (int i=0; i<numColumns; i++)
                   if (INBOX_COLUMN_SIZES[i] >= 1) // if this is an absolute size
                        remainingWidth -= (int)INBOX_COLUMN_SIZES;
                        finalWidths[i] = (int)INBOX_COLUMN_SIZES[i];
              totalWidth = remainingWidth;
              // now calculate aboslute widths of relative widths
              for (int i=0; i<numColumns; i++)
                   if (i == (numColumns-1))
                        finalWidths[i] = remainingWidth;
                   else if (INBOX_COLUMN_SIZES[i] < 1) // if this is an absolute size
                        finalWidths[i] = (int)(INBOX_COLUMN_SIZES[i] * totalWidth);
                        remainingWidth -= (int)(INBOX_COLUMN_SIZES[i] * totalWidth);
         else if (currentNode.equals(SENT_TITLE))
              numColumns = SENT_COLUMN_SIZES.length;
              // array where final widths are stored
              finalWidths = new int[numColumns];
              // now, start determining the size of the columns
              // this does not yet return the final size of each column
              // but only calculates the remaining width
              for (int i=0; i<numColumns; i++)
                   if (SENT_COLUMN_SIZES[i] >= 1) // if this is an absolute size
                        remainingWidth -= (int)SENT_COLUMN_SIZES[i];
                        finalWidths[i] = (int)SENT_COLUMN_SIZES[i];
              totalWidth = remainingWidth;
              // now calculate aboslute widths of relative widths
              for (int i=0; i<numColumns; i++)
                   if (i == (numColumns-1))
                        finalWidths[i] = remainingWidth;
                   else if (SENT_COLUMN_SIZES[i] < 1) // if this is an absolute size
                        finalWidths[i] = (int)(SENT_COLUMN_SIZES[i] * totalWidth);
                        remainingWidth -= (int)(SENT_COLUMN_SIZES[i] * totalWidth);
         else if (currentNode.equals(DELETE_TITLE))
              numColumns = DELETE_COLUMN_SIZES.length;
              // array where final widths are stored
              finalWidths = new int[numColumns];
              // now, start determining the size of the columns
              // this does not yet return the final size of each column
              // but only calculates the remaining width
              for (int i=0; i<numColumns; i++)
                   if (DELETE_COLUMN_SIZES[i] >= 1) // if this is an absolute size
                        remainingWidth -= (int)DELETE_COLUMN_SIZES[i];
                        finalWidths[i] = (int)DELETE_COLUMN_SIZES[i];
              totalWidth = remainingWidth;
              // now calculate aboslute widths of relative widths
              for (int i=0; i<numColumns; i++)
                   if (i == (numColumns-1))
                        finalWidths[i] = remainingWidth;
                   else if (DELETE_COLUMN_SIZES[i] < 1) // if this is an absolute size
                        finalWidths[i] = (int)(DELETE_COLUMN_SIZES[i] * totalWidth);
                        remainingWidth -= (int)(DELETE_COLUMN_SIZES[i] * totalWidth);
         else if (currentNode.equals(DRAFT_TITLE))
              numColumns = DRAFT_COLUMN_SIZES.length;
              // array where final widths are stored
              finalWidths = new int[numColumns];
              // now, start determining the size of the columns
              // this does not yet return the final size of each column
              // but only calculates the remaining width
              for (int i=0; i<numColumns; i++)
                   if (DRAFT_COLUMN_SIZES[i] >= 1) // if this is an absolute size
                        remainingWidth -= (int)DRAFT_COLUMN_SIZES[i];
                        finalWidths[i] = (int)DRAFT_COLUMN_SIZES[i];
              totalWidth = remainingWidth;
              // now calculate aboslute widths of relative widths
              for (int i=0; i<numColumns; i++)
                   if (i == (numColumns-1))
                        finalWidths[i] = remainingWidth;
                   else if (DRAFT_COLUMN_SIZES[i] < 1) // if this is an absolute size
                        finalWidths[i] = (int)(DRAFT_COLUMN_SIZES[i] * totalWidth);
                        remainingWidth -= (int)(DRAFT_COLUMN_SIZES[i] * totalWidth);
         else
              numColumns = DEFAULT_COLUMN_SIZES.length;
              // array where final widths are stored
              finalWidths = new int[numColumns];
              // now, start determining the size of the columns
              // this does not yet return the final size of each column
              // but only calculates the remaining width
              for (int i=0; i<numColumns; i++)
                   if (DEFAULT_COLUMN_SIZES[i] >= 1) // if this is an absolute size
                        remainingWidth -= (int)DEFAULT_COLUMN_SIZES[i];
                        finalWidths[i] = (int)DEFAULT_COLUMN_SIZES[i];
              totalWidth = remainingWidth;
              // now calculate aboslute widths of relative widths
              for (int i=0; i<numColumns; i++)
                   if (i == (numColumns-1))
                        finalWidths[i] = remainingWidth;
                   else if (DEFAULT_COLUMN_SIZES[i] < 1) // if this is an absolute size
                        finalWidths[i] = (int)(DEFAULT_COLUMN_SIZES[i] * totalWidth);
                        remainingWidth -= (int)(DEFAULT_COLUMN_SIZES[i] * totalWidth);
         // set column widths
         for (int i=0; i<numColumns; i++)
              tableView.getColumnModel().getColumn(i).setMinWidth(finalWidths[i]);
              tableView.getColumnModel().getColumn(i).setPreferredWidth(finalWidths[i]);
              tableView.getColumnModel().getColumn(i).setMaxWidth(finalWidths[i]);
    //     tableView.repaint();

    Hi,
    I solved the second problem. All I did was change the autoresize to      setAutoResizeMode(JTable.AUTO_RESIZE_ALL_COLUMNS);.
    However, I still have the first problem.
    Thanks for your help in advance.

  • How do I find the width of an external swf file that I am loading in

    I have loaded in an external swf file and it works fine.
    However, when I get the width dimensions of the movieclip that is housing the external swf file it gives me a '0' for the width.
    Thanks for your time.

    you must wait until loading is complete before trying to access the loaded objects width.  at that point you can determine the width,height of the onstage/backstage objects in frame 1 of the loaded swf.

  • Nested canvas in GridLayout can't get its width and height

    Hello,
    I have a class entitled DisplayCanvas, which will accept some parameters from an invocation in another class including a shape and message parameters. These parameters must be centered in the instance of DisplayCanvas.
    For some reason, when I use this.getWidth() and this.getHeight() within my DisplayCanvas class, I get 0 and 0! I need the width and height in order to center the parameters the user will enter.
    Why does the width and height result at 0? What can I do to get the width and height?
    In my DisplayCanvas class notice the lines:
    canWidth = this.getWidth();
    canHeight = this.getHeight();
    For some reason the result is 0 for each!
    Here is my code for the DisplayCanvas class:
    //import the necessary clases
    import java.awt.*;
    import java.applet.*;
    import javax.swing.*;
    //begin the DisplayCanvas
    public class DisplayCanvas extends Canvas
      //declare private data members to house the width and height of the canvas
      private int canWidth;
      private int canHeight;
      //declare private data members for the shape and message
      private String message;
      private String shape;
      private Color sColor;
      private int sWidth;
      private int sHeight;
      private String font;
      private Color ftColor;
      private int ftSize;
      //declare public data members
      //constructor of DisplayCanvas
      public DisplayCanvas()
         //set the width and height
         canWidth = this.getWidth();
         canHeight = this.getHeight();
         //set all data members to defaults
         message = "";
         shape = "";
         sColor = null;
         sWidth = 0;
         sHeight = 0;
         font = "";
         ftColor = null;
         ftSize = 0;
      } //end the constructor
      //begin the setParams function
      public void setParams(String m, String s, Color c, int w, int h,
                            String f, Color ftC, int ftS)
          //set all private data members of DisplayShape to the arguments
          //this function assumes error checking was done by DemoShape
          message = m;
          shape = s;
          sColor = c;
          sWidth = w;
          sHeight = h;
          font = f;
          ftColor = ftC;
          ftSize = ftS;
      } //end the setParams function
      //begin the public paint function of ShowShape
      public void paint(Graphics g)
          //set and output the shape according to the arguments
          //determine the x and y of the shape
          int x = (canWidth - sWidth) / 2;
          int y = (canHeight - sHeight) / 2;
          //set the color for the graphic object
          g.setColor(sColor);
          //output the shape
          g.drawRect(x, y, sWidth, sHeight);
          //set and output the message according to the arguments
          //set the color and the font for the graphic object
          g.setColor(ftColor);
          g.setFont(new Font(font, Font.PLAIN, ftSize));
          //determine the centering of the message
          //output the message with the settings
          g.drawString(canWidth + " " + canHeight, 10, 10);
      } //end the paint function of ShowShape class
    } //end the DisplayCanvas classHere is my form entry class using the nested DisplayCanvas instance entitled drawCanvas:
    //import the necessary java packages
    import java.awt.*;                  //for the awt widgets
    import javax.swing.*;               //for the swing widgets
    import java.awt.event.*;            //for the event handler interfaces
    //no import is needed for the DisplayCanvas class
    //if in the same directory as the DemoShape class
    public class DemoShape extends JApplet
        //declare private data members of the DemoShape class
        //declare the entry and display panel containers
        private Container entire;           //houses entryPanel and displayCanvas
        private JPanel entryPanel;          //accepts the user entries into widgets
        private DisplayCanvas drawCanvas;   //displays the response of entries
        //required control buttons for the entryPanel
        private JTextField xShapeText, yShapeText, messageText, fontSizeText;
        private ButtonGroup shapeRadio;
        private JRadioButton rect, oval, roundRect;
        private JComboBox shapeColorDrop, fontTypeDrop, fontColorDrop;
        //declare public data members of the DemoShape class
        //init method to initialize the applet objects
        public void init()
            //arrays of string to be used later in combo boxes
            //some are used more than once
            String fonts[] = {"Dialog", "Dialog Input", "Monospaced",
                                "Serif", "Sans Serif"};
            String shapes[] = {"Rectangle", "Round Rectangle", "Oval"};   
            String colors[] = {"Black", "Blue", "Cyan", "Dark Gray",
                                "Gray", "Green", "Light Gray", "Magenta", "Orange",
                                "Pink", "Red", "White", "Yellow"};
            //declare variables to assist with the layout
            //these are the left and right justified x coordinates
            int ljX = 10; int rjX = 150;
            //this is the y coordinates for the rows
            int yRow1 = 10;     //the shape rows
            int yRow2 = 40;
            int yRow3 = 60;
            int yRow4 = 130;
            int yRow5 = 150;
            int yRow6 = 210;    //the message rows
            int yRow7 = 240;
            int yRow8 = 260;
            int yRow9 = 300;
            int yRow10 = 320;
            int yRow11 = 360;
            int yRow12 = 380;
            //these are the widths for the text boxes, drop downs
            //message entry,  big message entry and radio buttons
            int tWidth = 30; int dWidth = 100;
            int mWidth = 250; int bmWidth = 250;
            int rWidth = 125;
            //the height is universal, even for the messages!
            int height = 25;
            //set a content pane for the entire applet
            //set the size of the entire window and show the entire applet
            entire = this.getContentPane();
            entire.setLayout(new GridLayout(1, 2));
            //create the entry panel and add it to the entire pane
            entryPanel = new JPanel();
            entryPanel.setLayout(null);
            entire.add(entryPanel);
            //create the display canvas and add it to the entire pane
            //this will display the output
            drawCanvas = new DisplayCanvas();
            entire.add(drawCanvas);       
            //entry panel code
            //add the form elements in the form of rows
            //the first row (label)
            JLabel entryLabel = new JLabel("Enter Shape Parameters:");
            entryPanel.add(entryLabel);
            entryLabel.setBounds(ljX, yRow1, bmWidth, height);
            //second row (labels)
            JLabel shapeTypeLabel = new JLabel("Select Shape:");
            shapeTypeLabel.setBounds(ljX, yRow2, mWidth, height);
            entryPanel.add(shapeTypeLabel);
            JLabel shapeColorLabel = new JLabel("Select Shape Color:");
            shapeColorLabel.setBounds(rjX, yRow2, mWidth, height);
            entryPanel.add(shapeColorLabel);
            //third row (entry)        
            rect = new JRadioButton("Rectangle", true);
            oval = new JRadioButton("Oval", false);
            roundRect = new JRadioButton("Round Rectangle", false);
            rect.setBounds(ljX, yRow3, rWidth, height);
            oval.setBounds(ljX, yRow3 + 20, rWidth, height);
            roundRect.setBounds(ljX, yRow3 + 40, rWidth, height);
            shapeRadio = new ButtonGroup();
            shapeRadio.add(rect);
            shapeRadio.add(oval);
            shapeRadio.add(roundRect);
            entryPanel.add(rect);
            entryPanel.add(oval);
            entryPanel.add(roundRect);       
            shapeColorDrop = new JComboBox(colors);
            shapeColorDrop.setBounds(rjX, yRow3, dWidth, height);
            shapeColorDrop.addFocusListener(new focusListen());
            entryPanel.add(shapeColorDrop);
            //the fourth row (labels)
            JLabel xShapeLabel = new JLabel("Enter Width:");
            xShapeLabel.setBounds(ljX, yRow4, mWidth, height);
            entryPanel.add(xShapeLabel);
            JLabel yShapeLabel = new JLabel("Enter Height:");
            yShapeLabel.setBounds(rjX, yRow4, mWidth, height);
            entryPanel.add(yShapeLabel);
            //the fifth row (entry)
            xShapeText = new JTextField("200", 3);
            xShapeText.setBounds(ljX, yRow5, tWidth, height);
            xShapeText.addFocusListener(new focusListen());
            entryPanel.add(xShapeText);        
            yShapeText = new JTextField("200", 3);
            yShapeText.setBounds(rjX, yRow5, tWidth, height);
            yShapeText.addFocusListener(new focusListen());
            entryPanel.add(yShapeText);
            //the sixth row (label)
            JLabel messageLabel = new JLabel("Enter Message Parameters:");
            messageLabel.setBounds(ljX, yRow6, bmWidth, height);
            entryPanel.add(messageLabel);
            //the seventh row (labels)   
            JLabel messageEntryLabel= new JLabel("Enter Message:");
            messageEntryLabel.setBounds(ljX, yRow7, mWidth, height);
            entryPanel.add(messageEntryLabel);
            //the eighth row (entry)
            messageText = new JTextField("Enter your message here.");
            messageText.setBounds(ljX, yRow8, mWidth, height);
            messageText.addFocusListener(new focusListen());
            entryPanel.add(messageText);
            //the ninth row (label)
            JLabel fontTypeLabel = new JLabel("Select Font:");
            fontTypeLabel.setBounds(ljX, yRow9, mWidth, height);
            entryPanel.add(fontTypeLabel);
            JLabel fontColorLabel = new JLabel("Select Font Color:");
            fontColorLabel.setBounds(rjX, yRow9, mWidth, height);
            entryPanel.add(fontColorLabel);
            //the tenth row (entry)
            fontTypeDrop = new JComboBox(fonts);
            fontTypeDrop.setBounds(ljX, yRow10, dWidth, height);
            fontTypeDrop.addFocusListener(new focusListen());
            entryPanel.add(fontTypeDrop);       
            fontColorDrop = new JComboBox(colors);
            fontColorDrop.setBounds(rjX, yRow10, dWidth, height);
            fontColorDrop.addFocusListener(new focusListen());
            entryPanel.add(fontColorDrop);
            //the eleventh row (label)
            JLabel fontSizeLabel = new JLabel("Select Font Size:");
            fontSizeLabel.setBounds(ljX, yRow11, mWidth, height);
            entryPanel.add(fontSizeLabel);
            //the final row (entry)
            fontSizeText = new JTextField("12", 2);
            fontSizeText.setBounds(ljX, yRow12, tWidth, height);
            fontSizeText.addFocusListener(new focusListen());
            entryPanel.add(fontSizeText);
            //display panel code
            //use test parameters
            //these will later be retrieved from the entries
            drawCanvas.setParams("Hello", "roundRect", Color.red,
                                100, 100, "Serif", Color.black, 12);
            //set the applet to visible
            //set to visible and display
            entire.setSize(800, 600);
            entire.setVisible(true);
        }   //end the init method
        //declare an inner class to handle events
        private class focusListen implements FocusListener
            //supply the implementation of the actionPerformed method
            //pass an event variable as the argument
            public void focusLost(FocusEvent e)
            { JOptionPane.showMessageDialog(null, "Focus lost."); } 
            //declare an empty focus gained function
            public void focusGained(FocusEvent e) {}      
        }   //end testListen class
    }   //end DemoShape class

    Sorry for glossing over your code sample, particularly as it looks like one of the best I've seen so far on the forums, but I'm pretty sure the answer you are looking for is as follows:
    Java doesn't render a component until paint() is called so until then you are not going to have any size settings because the jvm simply doesn't know how big the visual component is. This makes sense when you think about what the jvm is doing. The layout manager controls the display of the components depending on the settings it is supplied. So until it knows how many components you want, where, what kind of spacing, etc, etc, etc, how can the size be determined.
    The true cycle of events is therefore:
    create an instance of DisplayCanvas,
    add it to your container,
    make the container visible (which renders the component),
    get the size of the DisplayCanvas instance.
    You are being hampered because your desired chain of events is:
    create an instance of DisplayCanvas,
    get the size of the DisplayCanvas instance,
    add it to your container,
    make the container visible.
    This state of affairs is highly annoying and then leads to the next question "what do we do about that?". There is a cunning trick which is to get the jvm to render the component to an off-screen image, thus calculating the dimensions of the component so that you can do precisely the kind of enquiry on the object that you have been looking for. It should be noted that this may not be the visual size for all the reasons given above, but it is the "preferred size" for the component. Check the Swing tutorials and have a look at the section on Layout Managers for a run down on what that means.
    Anyway, we can use this handy code sample to determine the preferred size for your component. Notice the call to "paint()" (normally you would never make a direct call to paint() in swing) and the "g.dispose()" to free resources:
    package com.coda.swing.desktool.gui;
    import java.awt.Component;
    import java.awt.Dimension;
    import java.awt.Graphics2D;
    import java.awt.image.BufferedImage;
    public class PaintUtil
         public PaintUtil()
              super();
         public static Component paintBuffer(Component comp)
              Dimension size = comp.getPreferredSize();
              comp.setSize(size);
              BufferedImage img = new BufferedImage(size.width, size.height, BufferedImage.TYPE_INT_ARGB);
              Graphics2D g2 = img.createGraphics();
              comp.paint(g2);
              g2.dispose();
              return comp;
    }Before you make a call to getWidth() or getHeight() put in a call to "PaintUtil.paintBuffer(this);" and see what happens.
    By the way, I can't claim credit for this code ... and I really wish I could remember where I got it from myself so I can thank them :)

  • Finding the width of a JPEG loaded into a movie clip

    I will be loading a page of bio information. Next to the
    person's photo (photos will vary in width) I want to put a column
    of buttons about 20 pixels to the right of the photo. So after I
    load the photo into an empty movie clip, I'm trying to get the
    width of the photo in order to figure out the x position of the
    buttons next to it. Here is what I have:
    myImage = "images/" + _level0.images[link];
    loadMovie(myImage,image_mc);
    // JPEG loads okay into image_mc //
    trace("image_mc._x = " + image_mc._x);
    // I get "Image_mc._x = 393" as expected //
    trace("myImage._width = " + myImage._width);
    // I get "image_mc._width = undefined" //
    trace("image_mc._width = " + image_mc._width);
    // I get "image_mc._width = 0" //
    How do I find the width of the loaded JPEG?

    you are probably trying to get the width before the image has
    loaded completely.. use the MovieClipLoader class to load the image
    into the empty movie clip, then use the onLoadInit event to get the
    movie clips's width(which is the images width);
    var mcLoader:MovieClipLoader = new MovieClipLoader();
    var myListener:Object = new Object();
    myListener.onLoadInit = function(target:MovieClip):Void{
    trace(image_mc._width);
    mcLoader.addListener(myListener);
    mcLoader.loadClip(myImage, image_mc);

  • How do i get the last 4 chars

    String FileE = myFile.getName();
    This gives me a file name but how do I a reverse trim and get the last 4 chars??

    Hi
    What are you trying to achieve here, why are you pulling a file into a String Buffer ?
    fileName.getName() will output a string, you can use the following statement to get the last four characters of the filename
    Here is an example
    String fileName = "testfile";
    String lastFourChars = fileName.substring(fileName.length()-4);
    This will give you the last four characters of the filename.
    But if you are trying to get the extension of the file
    Do this
    String extension = fileName.substring(fileName.lastIndexOf("."));
    Thanks
    Swaraj
    Thanks
    Swaraj

Maybe you are looking for

  • Getting char values from a string problem

    Hi, Here's an example of what I'm trying to do: boolean loopSwitch = true; while (loopSwitch)      String orderDecider = JOptionPane.showInputDialog (null, "Would you like your numbers to be ordered in   ascending or descending order(A/D)",      "Ord

  • Is there any way to contact support via email as I cannot receive phone call at the moment . Thanks

    I have forgotten my security questions and cannot purchase apps. My rescue email was entered with an error .me instead of .mw so I can't reset my account. Is there a way to contact support via email ? as I can't receive a call. Thanks

  • Need help adding schedule to xcode 4

    I need help adding a tour schedule for an iphone app building an app for 13 djs and they want thier tour schedules added these need to be updated monthly is there a way to add this????

  • Is the iTunes 10 download disabled?

    Here's the link for downloading iTunes 10: http://www.apple.com/itunes/download/ I can't find anything clickable on the page (other than the option to switch to Spanish). (And, yes, I actually tried it from that language, too. -- Same effect.) Ideas?

  • ODI - Hyperion Planning  - Plan Type Option Missing

    Hi All, Iam not able to see the Plan Type option in the Hyperion Planning Application. For the application we have in planning has 5 plan types. A custom dimension is enabled for 3 plan types. When I reverse engineer the application under that dimens