Canvas paint never gets called - Repaint and ServiceRepaints.

I have a problem that My Canvas never gets Drawn or the Image never gets Displayed;
I am not sure if there is a DeadLock or If there is nothing to be painted,
but when I enable the Debugger I notice that it never enters the paint method. ( I call Repaint and ServiceRepaints)
If however I make the thread that calls setImage external to my Canvas Class the images do get Displayed.
   //Create the Canvas Class, Start Thread Display Canvas
   frame = new ImageCanvas();
    frame.addCommand(exitCommand);
    frame.addCommand(backCommand);
    frame.setCommandListener(this);
    frame.start();
    display.setCurrent(frame);
//Display Image
public class ImageCanvas extends Canvas implements Runnable {
protected void paint(Graphics g) {
  g.drawImage(offscreen, Constants.XPOS, Constants.YPOS,  Graphics.LEFT | Graphics.TOP);
  private void setImage(Image img, String title) {
    this.setTitle(title);
    offscreen = img;
    repaint();
    serviceRepaints();
public void run() {
     while(true){
       if (Constants.IMGLOCK != null) {
         synchronized (Constants.IMGLOCK) {
            setImage(Constants.IMAGE, title);
            Constants.IMGLOCK.setLockBoolValue(false);
             image_created = true;
      } else {
           Constants.IMGLOCK.wait(10);
}

I found the BUG, But do not understand Why this is Needed to add,
the Canvas every Time to the Display.
Can someone please Explain ???
private void setImage(Image img, String title) {
    this.setTitle(title);
    offscreen = img;
    repaint();
    display.setCurrent(this);  //<<<<<<WHY ????
    serviceRepaints();
  }

Similar Messages

  • Setter never get called in selectManyCheckbox!!

    Hello
    I posted a topic about selectManyCheckbox / selectItems , but I didnt receive any reply , so
    I reviewed earlier threads talking about the same problem:
    * setter method NOT CALLED* for selectManyCheckbox :
    http://forum.java.sun.com/thread.jsp?forum=427&thread=398097
    " ....My page is rendered with all of the correct checkboxes I require.
    One for each object in the problemOptions list.
    Once I check the boxes I want and submit the form,
    I am losing my choices when I come back to the same page.
    I noticed that I never see my setter being called.... "
    http://forum.java.sun.com/thread.jsp?forum=427&thread=401926
    "..if one ore more items are selected, ..... ,
    after it called the getter 3 times and the setter not at all.
    there is no error message and no stack in any of the logs...."
    this is sample of my JSP/backing bean :
    JSP :
      <h:selectManyCheckbox  id="foodType" value="#{productBean.foodType}">
            <f:selectItems value="#{productBean.foodTypes}" />
      </h:selectManyCheckbox>
    Backing bean class ProductBean :
      private ArrayList foodType = new ArrayList();
      private ArrayList foodTypes = new ArrayList();
    public ProductBean()  {
        foodTypes.add(new SelectItem("Sweet","Dweet label","Sweets"));
        foodTypes.add(new SelectItem("desert","Desert label","Deserts"));     
        foodTypes.add(new SelectItem("seeFood","SeeFood label","SeeFoods"));   
      public Object[] getFoodType() {
          try {
            return foodType.toArray(); }
          catch (Exception ex) { return null;  }
      public void setFoodType(Object[] newFoodType) {
        // NEVER GET CALLED !!!
        int len=0;
        if (null == newFoodType || ( len = newFoodType.length)==0 ) {    return; }
        foodType.clear();
        foodType = new ArrayList(len);
        for ( int i=0;i<len;i++) {   foodType.add(newFoodType); }
    public ArrayList getFoodTypes() {
    return this.foodTypes;
    public void setFoodTypes(ArrayList foodTypes) {
    this.foodTypes = foodTypes;
    what am I doing wrong ? , I'm really stuck , what may be the reason for JSF not to call setter for setFoodType??
    I saw a reply for Adam.winner stating that it is not suitable to use Object[] type as setter argument ,
    and to use String[] instead, but this was in EA4 .
    is this still applicable for JSF 1.0 FR ?
    I appreciate any help
    -- Erich

    The data type of the SelectItem itemValue properties must be the same basic type (primitive or the corresponding boxed type) as the data type of the UISelectMany/UISelectOne value.
    In this example, the SelectItem itemValue properties are of type String, but the UISelectMany value is of type Object. Change it to String, and it should work.

  • Static initializers get called over and over?

    I have a java web application running on resin. I don't know why but from time to time my class files suddenly get reloaded. I can notice from my log files that static initializers get called over and over again, which is causing me problems. How can this happen? Any settings I should fix? Anyone has similar problems?

    ram, thank you very much for your reply.
    I'm sure this problem doesn't always happen.
    I have a static initializer in a different
    application on a different resin server but it never
    initializes over and over.
    There must be some settings I can change to make it
    not to initialize more than once.I concur with Ram on this one. Having static initializers in container managed apps can be very dangerous if you need to make sure that it is initialized exactly once. I've seen problems like this happen on several vendor's Containers. A safer approach could be to store these values in your container's Application-scope. This way, you not only ensure that these values are initialized exactly once, but that the value will be available to all JVM's running should this app be deployed in a clustered environment.

  • When i try to set up my icloud account the system says it is sending me an email to verify.  I never get the email and it is not in my spam filter.  How can i get set up??

    when i try to set up my icloud account the system says it is sending me an email to verify.  I never get the email and it is not in my spam filter.  How can i get set up??

    Make sure that your Apple ID is your email address and you do not have any other or old IDs associated with you. Go to www.appleid.apple.com and confirm this info. Make sure that the email address you are trying to sign up with is your primary one.

  • Servlet Filter never gets called

    I have a filter configured in web.xml to run on hitting the /welcome.jsf(forward, request).
    I want to update a statistics table with the hit count for login.  But the servlet is not getting called.
    In the debugger, it never stops there and the statistics table never gets updated.

    11.1.2.3
    <filter>
            <filter-name>IBHSLoginStatistics</filter-name>
            <filter-class>gov.samhsa.dasis.isats.view.servlets.filters.IBHSLoginStatistics</filter-class>
        </filter>
    <filter-mapping>
            <filter-name>IBHSLoginStatistics</filter-name>
            <url-pattern>/faces/welcome/*</url-pattern>
            <dispatcher>FORWARD</dispatcher>
            <dispatcher>REQUEST</dispatcher>
        </filter-mapping>
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException,
    ServletException {
    HttpSession session = (HttpSession)FacesContext.getCurrentInstance().getExternalContext().getSession(false);
    if(session.isNew()) {
    IbhsStatistics ibhsStatistics = new IbhsStatistics();
    ibhsStatistics.setEventDate(new Timestamp(new Date().getTime()));
    ibhsStatistics.setEventType("Login");
    ibhsStatistics.setUserid(SecurityShell.getUserId());
    ManageIbhsStatistics manageIbhsStatistics = new ManageIbhsStatistics();
    try {
    manageIbhsStatistics.saveIbhsStatistics(ibhsStatistics);
    } catch (NamingException e) {
    } catch (NotSupportedException e) {
    } catch (SystemException e) {
    } catch (RollbackException e) {
    } catch (HeuristicMixedException e) {
    } catch (HeuristicRollbackException e) {
    chain.doFilter(request, response);

  • HTMLHost windowClose never gets called.

    Hi.
    I have a HTMLLoader and set to htmlHost a class extending HTMLHost (ie MyHTMLHost).
    Then I have this code in the class
    public class HelpHTMLHost extends HTMLHost
      override public function windowClose():void
             trace('close');
      override public function updateStatus(status:String):void
       trace("HTML: '" + status + "'");
    Then I load a page that has a
    <center><a href="javascript:alert(window);">test1</a></center>
    <center><a href="javascript:window.close();">close</a></center>
    .. Result is that  "test1" link works (shows alert window). close however deos not.
    the updateStatus method gets called (see two EMPTY strings in trace), windowClose does not get called.
    Using Adobe AIR 2 SDK, WIN 10,1,53,64 - Desktop - Windows 7 debug
    Thanks for the help.

    Same problem here, with AIR 2 SDK.

  • ApplicationSessionExpiryFilter never gets called

    I have configured a Filter in the web.xml and I have a filter class.  It doesn't seem to be getting called.  I have a page just for the timeout.
    public class ApplicationSessionExpiryFilter implements Filter {
        private FilterConfig _filterConfig = null;
        public void init(FilterConfig filterConfig) throws ServletException {
            _filterConfig = filterConfig;
        public void destroy() {
            _filterConfig = null;
        public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException,
                                                                                                         ServletException {
            String requestedSession = ((HttpServletRequest)request).getRequestedSessionId();
            String currentWebSession = ((HttpServletRequest)request).getSession().getId();
            boolean sessionOk = currentWebSession.equalsIgnoreCase(requestedSession);
            // if the requested session is null then this is the first application
            // request and "false" is acceptable
            if (!sessionOk && requestedSession != null) {
                // the session has expired or renewed. Redirect request
                ((HttpServletResponse)response).sendRedirect(_filterConfig.getInitParameter("SessionTimeoutRedirect"));
            } else {
                chain.doFilter(request, response);
    Please help.  We are already in production

    Hi Veena,
    Please mention your Jdev version always,
    https://www.youtube.com/watch?v=qGDevlbSLcw.
    Anyhow, I think this would help you.
    Thanks.

  • Canvas never gets shown (visible) on i85s, emulator works

    Hi,
    I have a class that has two canvases: one is very lightweight and I show it immediately, the other I create in a thread and block on the completion.
    The thread run() method after creating the canvas, does
    a setCurrent(canvas) and I'm able to verify that it occurs. The flag to continue is set and I block again
    on showNotify () which I have a second flag.
    showNotify() on the i85s never gets called though and my game never updates. It does work on the emulator i85s though.
    The code stripped down is like this.
    Class Manager extends TimerTask
    Thread loaderT = null;
    Loader loader = null;
    BigCanvas bc = null;
    Manager() {
    loader = new Loader (this);
    loaderT = new Thread(loader);
    loaderT.start();
    // this method called manager is instantiated
    void start() {
    timer = new Timer(); timer.schedule(this,0,delay);
    setCurrentAndVisible(tmpCanvas);
    // managers run
    void run (){
    if (!loader.done){
    current.repaint(); return;
    // done loading,
    loaderThread = null;
    advanceStates();
    if (bc.visible){ // set when showNotify() called
    bg.repaint();
    class Loader implements Runnable{
    Manager m = null; BigCanvas c = null; done = false;
    Loader(Manager m){
    this.m = m;
    run () {
    m.bc = new BigCanvas();
    m.d.setCurrent(c);
    done = true;
    please note that the classes and methods arent exactly as they are in my code, i just copied what the process was and renamed variables to make sense in a forum-setting. the code all compiles and runs fine in the emulator (so if i misspelled things, or left out of part of method sigs above please dont worry about correcting it), I'm just trying to explain my programming method above not write exactly compiling code.
    TempCanvas and Loader are both inner-classes of Manager also.
    thanks a lot!
    ps. why isnt there a cldc-interest mailing list?
    I find mailing lists easier to keep track of then forums.

    please note,
    setCurrentAndVisible does the following
    setCurrentAndVisible(BaseCanvas c)
    current = c;
    d.setCurrent(current);
    and current is a BaseCanvas in Manager.
    Also in Loader.run() , m.d.setCurrent(c); is actually
    m.setCurrentAndVisible(c);
    thanks!

  • TableSorter class never ever calls getModelToView()

    I am using TableSorter class to sort tables. There is a piece of optimization code that never gets called: getModelToView(). For that method to be called a check is performed (modelToView != null). But modelToView is assigned inside that method! This causes a single cell update to trigger fireTableDataChanged(). Is that a known bug? Is there a fix?

    I see what you mean.. you're right, it seems like modelToView will always be null.
    I found another bug.. when mouse is clicked on the tableheader area where it doesn't have any column (when table is stretched it can have no column there) , columnModel.getColumnIndexAtX(e.getX()) returns -1, and if the check there is not added, then get a runtime out-of-bounds exception on the following line columnModel.getColumn(viewColumn).getModelIndex() because viewColumn is set to -1. See the code snippet below:
    public void mouseClicked(MouseEvent e) {
                JTableHeader h = (JTableHeader) e.getSource();
                TableColumnModel columnModel = h.getColumnModel();
                int viewColumn = columnModel.getColumnIndexAtX(e.getX());
                if(viewColumn == -1) {  // added!
                    return;
                int column = columnModel.getColumn(viewColumn).getModelIndex();

  • Validators getting called multiple times?

    I am working on a project where were we have used BackingBean validators for an input text component.
    When I first submit, the validator method getting called once, when I submit again, its getting called twice, and it goes on. After clearing the session, the validator getting called once, then twice, ...
    I don't know why this happens. Can any help me with this? What could be reasons for this weird behavior? What might went wrong in our code.

    An SSCCE please.

  • I just want to know why money was taken out mi bank account,i still have a itunes balence and used a gift card.id love someone 2 call me about this but i never get thru to you

    i just want to know why money was taken out mi bank account,i still have a itunes balence and used a gift card.id love someone 2 call me about this but i never get thru to you

    This is a User to User Forum... You are not addressing Apple Here...
    Suggest you use this link to Contact iTunes Customer Service
    Apple  Support  iTunes Store  Contact Us

  • Native Canvas Painting and Refresh

    Hi,
    I have a project where I get live video from a firewire camera, and paint it to an awt Canvas natively using JNI. I need additional items painted on the canvas (on top of the video), like a pair of crosshairs and rulers to measure certain widths, etc. The software tracks an object moving across the screen, so the crosshairs need to be moved around and refreshed often.
    I am getting a strange problem - the natively painted video is working just fine, but the painted objects are not refreshing properly. For example, instead of getting a crosshair that moves around the screen, I get a trail of crosshairs. And underneath the crosshairs, the video is refreshing just fine. What's going on? I'm using libXv, an X-windows extension to paint YUV4:2:2 camera buffers directly to the screen.
    Here are relevant class snippets:
    public class NativeCanvas extends Canvas{
        public void update(Graphics g)                 <-- overridden to eliminate flicker
            paint(g);
        public native void paint(Graphics g);         <-- here's the native video drawing function
    public class CanvasWithOverlays extends NativeCanvas
        public void paint(Graphics g)
               super.paint();
               Graphics2D g2 = (Graphics2D)g;
               //(paint crosshairs, etc)
    } Any help will be greatly appreciated. Thanks very much!
    --Ismail Degani
    High Energy Synchrotron Source
    Cornell University

    Hi,
    I'm not sure how the crosshairs can be out of sync with the video stream - the canvas paint routines paint the video frame natively, and then paint the crosshairs. It's all sequential -
    super.paint();    // goes into a native function XvPutImage that quickly blits the frame on screen
    Graphics2D g2 = (Graphics2D)g;          
    //(paint crosshairs, etc) This should work properly with the Event Queue, to the best of my knowledge. I schedule a TimerTask that continually calls the repaint() method to refresh the video:
    public class LiveVideoPainter extends TimerTask
        static Logger logger = Logger.getLogger(LiveVideoPainter.class.getName());
        NativeCanvas nc;
        VideoDataSource vs;
        public LiveVideoPainter(NativeCanvas nc, VideoDataSource vs)
            if(nc == null)  {
                logger.error("The Native Canvas is null!");
                return;
            if(vs == null)  {
                logger.error("The Video Data Source is null!");
                return;
            this.nc = nc;
            this.vs = vs;
        public void run()
            vs.getFrame(nc.buffer);
            nc.repaint();
    } I actually had this same problem when designing this application with C++ using the Qt windowing toolkit a year ago. Basically, if I called XvPutimage, and then called regular X drawing routines like XDrawLine etc in a loop, it would draw successfully, but never refresh properly:
    while(true)
    get_decompressed_frame(buf);
    xv_image=XvCreateImage(display,info[0].base_id, XV_UYVY, (char*)buf, 1024, 768);
    XvPutImage(display, info[0].base_id, window, gc, xv_image,
                       0,0,1024,768,
                       0,0, 1024,768);
    if(crossHairDisplayed)
    // Draw Horizontal CrossHair                                                                                                                                                           
                XDrawLine(display, window, gc,
                          0,   (int)(DataSource::pixPerMicron*DataSource :: crossY + DataSource::zcenY),
                          1024,(int)(DataSource::pixPerMicron*DataSource :: crossY + DataSource::zcenY));
                // Draw Vertical CrossHair                                                                                                                                                             
                XDrawLine(display, window, gc,
                          (int)(DataSource::pixPerMicron*DataSource :: crossX + DataSource::zcenX), 0,
                          (int)(DataSource::pixPerMicron*DataSource :: crossX + DataSource::zcenX) , 768);
    }In this code bit, the crosshairs should move when the DataSource object changes member variables, line CrossX. But, the old crosshairs would not go away until the window was moved or resized. I'd get two crosshairs on the screen. I had to use a hack from the xwindows utility xrefresh everytime the crosshairs changed. It essentially simulated an x-window that opened over the Qt window, and then immediately closed. This worked well, but I thought I'd be free of that hack when I moved to java and JNI. Isn't this bizarre? Why would the window hold on to the old crosshair even when the varialbes change and there isn't any code that repaints it there after the video frame gets blitted?
    hack adapted from xrefresh.c:
          if(newCrossHair)
                              Visual visual;
                      XSetWindowAttributes xswa;
                      Display *dpy;
                      unsigned long mask = 0;
                      int screen;
                      Window win;
                      if ((dpy = XOpenDisplay(NULL)) == NULL) {
                        fprintf (stderr, "unable to open display\n");
                        return;
                      screen = DefaultScreen (dpy);
                      xswa.background_pixmap = ParentRelative;
                      mask |= CWBackPixmap;
                      xswa.override_redirect = True;
                      xswa.backing_store = NotUseful;
                      xswa.save_under = False;
                      mask |= (CWOverrideRedirect | CWBackingStore | CWSaveUnder);
                      visual.visualid = CopyFromParent;
                      win = XCreateWindow(dpy, DefaultRootWindow(dpy), 400, 600, 1, 1,
                                          0, DefaultDepth(dpy, screen), InputOutput, &visual, mask, &xswa);
                      XMapWindow (dpy, win);
                      /* the following will free the color that we might have allocateded */
                      XCloseDisplay (dpy);
                      newCrossHair = false;
          } Any ideas? There's probably just some type of refresh call I need to use.
    --Ismail                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                       

  • 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 :)

  • Difference between repaint() and paint()

    also i wanna know what it does inside the paint(), repaint() and update()
    Can anyone give me some links about this?
    Thank you.

    To expand briefly on what patrix3 already said:
    The GUI thread will automatically call update() to correct painting issues (such as when areas of the screen become damaged due to objects moving on top of them, etc.). However, the programmer can specify when a region needs to be repainted by calling repaint(); this does not immmediately make a call to update(). Rather, the GUI is informed that a call to update is requested, and it executes when it can (this usually happens so fast that it seems as if repaint() immediately calls update(), but there's an important reason why it doesn't).
    update() does nothing more than clear the screen and then call paint(). The version of update patrix3 gave simply ommits the screen clearing (which can cause flickering).
    If multiple requests are made to repaint() before the GUI thread gets to them, then it will only execute the last one, the other requests are ignored. This is important because otherwise the GUI thread could 'fall behind' in trying to repaint the screen, if many calls to repaint() have been made.

  • I can not get my itunes to recognize my ipod touch, I called support and when i found out there was a charge I politely said no thanks and hung up. now I can't even get the itunes to download!!

    I have tried since Chrismas to use my Ipod touch and have not been able to!  I have uninstalled and reinstalled itunes more often then I care to admit!  I called support and when I found out there is a charge ($59.95) I declined and hung up.  I now can't even download itunes!  I guess I find that a little fishy.  I was so happy with this gift and now I am so frustrated I am about to return it and never purchase another apple product again! I have gotten nothing but the run around when trying to get assistance for a very expensive music player!   HELP PLEASE

    Start here:
    iPhone, iPad, or iPod touch: Device not recognized in iTunes for Windows

Maybe you are looking for

  • Repos - logical table source does not contain mapping

    Hi, I have a repository question? I do not have a fact table in my physical layer. Do I have to have one? I thought the fact table got created in the BM. I do have a date table in the physical layer, but it isn't joined to any other table. I added th

  • Entries in the PREQ_ACTOR table gets modified

    Hi all, I am facing a typical issue with the table PTREQ_ACTOR, the entries of the table PTREQ_ACTOR gets modified sometimes resulting in the  inconsistency in the entries between the PTREQ_ACTOR and PTREQ_HEADER table, This inconsistency leads to th

  • Production confirmation error

    Hi gurus 1. Is it possible to make the order confirmation in the previous date of the production order ?? 2. can we restrict the date range for a production order confirmation Very urgent.... Pl reply,, Thanks in advance for your reply.

  • Creating a contact sheet of illustrations using CS6

    Is there a way to create a contact sheet of my illustrations (eps files) so that they don't come out fuzzy? If i use bridge they are way too pixelated.

  • KDE 4.2: Crazy Mouse after pacman -Syu -.-'

    Hi I made yesterday a sysupgrade and now is my mouse crazy!!! Example: i click a window to move it but the window will be maximized i make a right click in taskbar but nothing works  HELP -.-'