Am I painting to an offscreen buffer correctly?

Hi all,
I am creating a simulation, and I want to paint the view for the simulation smoothly. Currently I have a thread that is looping around and calling repaint() every 50 ms. However, the animation is a little jerky and occasionally some parts of the view are visibly painted before others, so it looks odd (as a note, painting usually takes 30-40 ms, but occasionally spikes as high as 100 ms).
I am trying out painting to an offscreen buffer first, but I'm not sure if I'm doing it the right way. I am using a short tutorial I found.
I used to have a paint() method in my JComponent-extending view which used to look like:
paint(Graphics g){
    // do a whole bunch of painting, including cycling through hundreds of
   // images and painting them to g
}From what I could tell, I could keep this method intact, but instead of painting to the Graphics g that is passed in when repaint() is called, I could paint it to a BufferedImage, and then just paint that BufferedImage. I've posted the code below.
However, when I try this, the painting is much, much jerkier then before. Basically it paints one half of the screen, then the other half, alternating at about a 10 hertz rate, so it's not good at all.
Am I implementing the offscreen buffer pattern correctly? Would it not work in my case? Any suggestions? Thanks!
The new code I used:
     private BufferedImage offImg;
      public void paint(Graphics g){
           if (getSize().width <= 0 || getSize().height <= 0)
                return;
              Graphics2D g2 = createGraphics2D(g);
              draw(g2);
              g2.dispose();
              if (offImg != null && isShowing()) {
                g.drawImage(offImg, 0, 0, this);
      public Graphics2D createGraphics2D(Graphics g){
          Graphics2D g2 = null;
          if (offImg == null || offImg.getWidth() != getSize().width
                  || offImg.getHeight() != getSize().height) {
               offImg = (BufferedImage) createImage(getSize().width,
                       getSize().height);
          if (offImg != null) {
               g2 = offImg.createGraphics();
               g2.setBackground(getBackground());
          // .. set attributes ..
          g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
                  RenderingHints.VALUE_ANTIALIAS_ON);
          // .. clear canvas ..
          g2.clearRect(0, 0, getSize().width, getSize().height);
          return g2;
     public void draw(Graphics g)
           // the exact same long complex code I originally had in the paint() method
       }

except that he is using paintComponent instead of paintThat's actually a key difference. The double buffering magic that swing does starts in the JComponent's paint() method. If you override the paint() method to do your own thing, then there's a chance that you've effectively nullified double buffering for that component. That's why custom painting code goes into the the paintComponent method.
Now, your combination of drawing to a BufferedImage and then drawing to the graphics context within the paintComponent method will+ be slower. The graphics context passed to
public void paintComponent(Graphics g) {
}will be to a VolatileImage 99.9% of the time. Which means you might as well directly use "g", since it's equivalent to drawing on a back image which happens to faster than BufferedImage. Drawing on an intermediate image within the paintComponent will only slow things down.
In the event that you're painting too much and the animation is too slow, then the suggestion is to do all your drawings in a seperate thread on a back image, and then have your paintComponent(Graphics g) method paint only that image.
public void paintComponent(Graphics g) {
    g.drawImage(theImage,0,0,null);
}You would also decrease the sleep time in the seperate thread to try to get all the drawing done on time. You can use a BufferedImage for the back image, or with slightly more code managing - use a VolatileImage.
Component#createVolatileImage(int width, int height);

Similar Messages

  • Views using the same offscreen buffer, interfering with each other

    Hi all,
    I am creating an application where I display simulations. In order to keep the view of the simulation ticking along nicely, I paint the view to an offscreen buffer, and then paint the offscreen buffer to the screen.
    This has worked fine for me, so long as I was only viewing one single simulation on the screen at a time. I have now started displaying multiple simulations, and the views have started to interact with eachother -- one will paint over the other, particularly when I click or drag the simulation.
    I'm not using any static variables, so my guess is that the fault is the offscreen buffer that I'm using. I think my various views are using the same buffer. Is it possible that this is the problem?
    Here's how I paint my view:
    private BufferedImage offImg;
    private Graphics2D offG;
    public Graphics2D createGraphics2D(){
              if (offImg != null) {
                   offImg.flush();
                   offImg = null;
              RepaintManager repaintManager = RepaintManager.currentManager(this);
              try {
              offImg = (BufferedImage) repaintManager.getOffscreenBuffer(
                        this, this.getWidth(), this.getHeight());
              } catch (java.lang.NullPointerException e){
                   return null;
              offG = offImg.createGraphics();
              // .. clear canvas ..
              offG.clearRect(0, 0, getSize().width, getSize().height);
              return offG;
    private void draw() {
          if (offG == null)
                   createGraphics2D();
         offG.drawImage(...) //etc
    public void paintComponent(Graphics g){
               g.drawImage(offImg, 0, 0, this);
          }My first thought was to create a list of all the offImg's created and compare them. The different views are indeed getting the same image from repaintManager.getOffscreenBuffer, even though the component passed in as 'this' is different. The offG's created by each view are different, but since they belong to the same image, I assume it's the image that's important.
    Is this likely to be the source of my woes, and, assuming that I want to keep using the offscreen buffer (I do) is there a way around this problem?
    Thanks so much for any advice.

    Hello,
    I am creating an application where I display simulations. In order to keep the view of the simulation ticking along nicely, I paint the view to an offscreen buffer, and then paint the offscreen buffer to the screen.You may know that Swing uses double-buffering by default. So you usually don't really need to tweak Swing's own offscreen buffers.
    Painting conservatively on an applicative offscreen buffer is sounds (if painting is slow), but then your application has to create a dedicated offscreen buffer, not use Swing's ones.
    This has worked fine for me, so long as I was only viewing one single simulation on the screen at a time. I have now started displaying multiple simulations, and the views have started to interact with eachother -- one will paint over the other, particularly when I click or drag the simulation.
    I'm not using any static variables, so my guess is that the fault is the offscreen buffer that I'm using. I think my various views are using the same buffer. Is it possible that this is the problem?I can't tell for sure, but I'm not surprised if that's the case: all Swing ("lightweight") widgets within a same JFrame (or any other "heavyweight" top-level container) share the same native graphical resources, so presumably share the same offscreen buffer. It is Swing's machinery that arranges so that each widget paints onto a part of this buffer that corresponds to the widget's bounds.
              offImg = (BufferedImage) repaintManager.getOffscreenBuffer(
                        this, this.getWidth(), this.getHeight());You don't have to, and probably should not, ask Swing's RepaintManager for a buffer. You vould create a BufferedImage yourself, then draw onto it.
    offImg = new BufferedImage(...);Then your paintComponent method itself is fine:
    public void paintComponent(Graphics g){
               g.drawImage(offImg, 0, 0, this);
    Is this likely to be the source of my woes, and, assuming that I want to keep using the offscreen buffer (I do) is there a way around this problem?See above. And look for "offscreen graphics" on this forums, you'll probably find a lot of examples that do this way (and give example code, my sample above is sketchy and untested).
    Regards,
    J.
    Edited by: jduprez on Jun 2, 2011 12:10 AM
    Read this article if you need to kick the best out of your fast painting code (in particular, it mentions more informed ways than mine to create Image instances suitable for offscreen drawing):
    http://java.sun.com/products/java-media/2D/perf_graphics.html

  • Paint( ) - is passing of object correct?

    Thanks (in advance) for looking at this, as always,
    your input is valued & appreciated.
    I did get my program to work. But i dont know if i understood the question correctly... specifically the part about "squareOfStars...this method should be called from the applet's paint method & shold be passed the Graphics object from paint". Have i performed this correctly? It seems kinda redundant to me to be passing around a "Graphics g" parameter.
    //Ex6_18 Write a method squareOfStars that displays a solid square
    //of stars whose side is specified in integer parameter side. 
    //Eg:  if side = 4, display 4 rows containing 4 stars each. 
    //Incorporate this method into an applet that reads an integer value
    //for side from the user.  Note that squareOfStars should be called
    //from the applet�s paint method and should be passed the Graphics
    //object from paint
    import java.awt.Graphics;   // import class Graphics
    import javax.swing.*;       // import package javax.swing
    public class Ex6_18b extends JApplet {
       double number1;       // number of stars to print, row & col
       public void init()
          String firstNumber;   // first string entered by user
          // read in first number from user
          firstNumber = JOptionPane.showInputDialog(
                       "Enter size of rectangle" );
          // convert numbers from type String to type double
          number1 = Double.parseDouble( firstNumber );
       }//end of init
       public void paint( Graphics g ){ 
          squareOfStars( g );
       }//end of paint
       public void squareOfStars( Graphics g ){
          int x = 25, y = 25;
          for (int row = 1; row <= number1; row++){    //for each row
                                                       //print out one line
             for( int col = 1; col <= number1; col++){
                g.drawString( "* ", x = x + 7, y );
             y = y + 7;               // move down to next line for display
             x = 25;                  //reset x, so that next line starts at col 25+7
          }//end of outter for
       }//end of squareOfStars
    }//end of applet

    That's because it ISN'T double buffering.Yes you're right, it isn't double buffering. But it could be, I didn't show what was inside paint.
    I didn't
    know about the update method - is that as effective at
    killing flicker as my method? I'll try it.Well that's the standard(?) way of doing it. When you call repaint(), it actually calls update. So instead of overriding repaint, I suggest overriding update(Graphics g).
    While we're on the subject, I usually use
    BufferedImage for double buffering in apps, but I
    couldn't make that work in applets, probably because
    of VM versions. What is a good way to achieve
    double buffering in applets?Use a normal Image.
    Image dblBuf = createImage(width, height);
    Graphics dblGfx = dblBuf.getGraphics();Then just do all the drawing to dblGfx (anywhere in the code) and in paint just draw dblBuf on screen. Eliminates flicker nicely.

  • Offscreen buffer in AWT/Java1.1

    Hello, there!
    I am programming on a browser-application that uses an AWT Scrollpane containing lots of elements, leading to heavy slow-downs and/or flickering (depends on the browser) when scrolling. My idea was to render the whole tree into an image and just paint this (as a normail Panel) instead of all the many single components. Of course this image needs to be updated when the tree changes.
    Is it possible to do that in a way so that the single components inside the Panel still would react on mouse events?
    I haven�t been able to try this out by myself, because I already had a problem with creating an offscreen-image. When I try to generate an Image from within a component with the createImage method, I receive a "null", not a new Image. I remeber that I had this problem already one year ago in another project and that it took some ugly work-arounds to get it work...
    I guess I�m doing something wrong...
    Can anyone help me? Thank you very much!
    Znerole

    I�ve been looking at some old sources of mine and I realized why the Image-creation didn�t work. I may not call the createImage-method from the components constructor!!!
    Now I still don�t know if I may render a whole container into an Image with still having the single components reacting on mouseEntered and mouseExited... I think I have to try out on my own... :o

  • My new blank file is suddenly gray and paint bucket no longer works correctly.

    Photoshop Elements 10.  I started a new blank file, which opened white, as usual.  I enclosed the file with the rectangular marquee tool, and used the paint bucket to fill the background with a brownish color I choose, except it filled with gray.  I looked to be sure the color mode was RBG color, and it is.  After a frustrating couple of attempts to change the color, I thought of a work around and just created a new layer and colored it, but, when I tried to change the color again, the paint bucket would not respond, so I created another layer and the paint bucket then changed the color for me again.  However, I really would prefer it work the way it did before, instead of creating unnecessary layers to do the job.  I insert a screen shot, if it helps.  Any help resolving this would be appreciated.

    I clicked on the arrow and reset the tool.  I also reset the transparency setting in preferences, which was the only color related setting I saw there, to no avail.  I opened another new file, same result, dumping the paint bucket produced only a grayscale color.  Thanks for the suggestion, however. 

  • How to double-buffer a JWindow?

    Hi,
    I made a resizable JWindow, but whenever I resize, J-components within the window flicker. (First setSize(), then validate() to redraw for correct sizes). I know JWindow is not double buffered, I want to override the paint() method to implement double buffering -- anyone knows how to do that? (...besides copying from JComponent.java)

    I think double buffering available in Swing with out you doing anything. Just add the following line to your window initialization.
    ((JPanel)window.getContentPane()).setDoubleBuffered(true);If this doesn't work, and I think it should. Then use the code below.
    This is code copied from http://java.sun.com/j2se/1.3/docs/guide/awt/designspec/lightweights.html
    The following is a Panel, but you can apply the same logic to JWindow.
    public class DoubleBufferPanel extends Panel {   
      Image offscreen;
       * null out the offscreen buffer as part of invalidation
      public void invalidate() {
          super.invalidate();
          offscreen = null;
       * override update to *not* erase the background before painting
      public void update(Graphics g) {
          paint(g);
       * paint children into an offscreen buffer, then blast entire image
       * at once.
      public void paint(Graphics g) {
          if(offscreen == null) {
             offscreen = createImage(getSize().width, getSize().height);
          Graphics og = offscreen.getGraphics();
          og.setClip(0,0,getSize().width, getSize().height);
          super.paint(og);
          g.drawImage(offscreen, 0, 0, null);
          og.dispose();

  • How to draw a JPanel in an offscreen image

    I am still working on painting a JPanel on an offline image
    I found the following rules :
    - JPanel.setBounds shall be called
    - the JPanel does not redraw an offline image, on should explicitly override paint()
    to paint the children components
    - the Children components do not pain, except if setBounds is called for each of them
    Still with these rules I do not master component placement on the screen. Something important is missing. Does somebody know what is the reason for using setBounds ?
    sample code :
    private static final int width=512;
    private static final int height=512;
    offScreenJPanel p;
    FlowLayout l=new FlowLayout();
    JButton b=new JButton("Click");
    JLabel t=new JLabel("Hello");
    p=new offScreenJPanel();
    p.setLayout(l);
    p.setPreferredSize(new Dimension(width,height));
    p.setMinimumSize(new Dimension(width,height));
    p.setMaximumSize(new Dimension(width,height));
    p.setBounds(0,0,width,height);
    b.setPreferredSize(new Dimension(40,20));
    t.setPreferredSize(new Dimension(60,20));
    p.add(t);
    p.add(b);
    image = new java.awt.image.BufferedImage(width, height,
    java.awt.image.BufferedImage.
    TYPE_INT_RGB);
    Graphics2D g= image.createGraphics();
    // later on
    p.paint(g);
    paint method of offScreenPanel :
    public class offScreenJPanel extends JPanel {
    public void paint(Graphics g) {
    super.paint(g);
    Component[] components = getComponents();
    for (int i = 0; i < components.length; i++) {
    JComponent comp=(JComponent) components;
    comp.setBounds(0,0,512,512);
    components[i].paint(g);

    Unfortunately using pack doesn't work, or I didn't use it the right way.
    I made a test case, eliminated anything not related to the problem (Java3D, applet ...). In the
    test case if you go to the line marked "// CHANGE HERE" and uncomment the jf.show(), you have
    an image generated in c:\tmp under the name image1.png with the window contents okay.
    If you replace show by pack you get a black image. It seems there still something.
    simplified sample code :[b]
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    import com.sun.j3d.utils.applet.*;
    import com.sun.j3d.utils.image.*;
    import com.sun.j3d.utils.universe.*;
    import java.io.*;
    import java.awt.image.*;
    import javax.imageio.*;
    public class test {
    private static final int width=512;
    private static final int height=512;
    public test() {
    JPanel p;
    BorderLayout lay=new BorderLayout();
    java.awt.image.BufferedImage image;
    // add a JPanel with a label and a button
    p=new JPanel(lay);
    p.setPreferredSize(new Dimension(width,height));
    JLabel t=new JLabel("Hello");
    t.setPreferredSize(new Dimension(60,20));
    p.add(t,BorderLayout.NORTH);
    p.setDebugGraphicsOptions(DebugGraphics.LOG_OPTION );
    // show the panel for debug
    JFrame jf=new JFrame();
    jf.setSize(new Dimension(width,height));
    jf.getContentPane().add(p);
    [b]
    // CHANGE HERE->
    jf.pack();
    //jf.show();
    // create an off screen image
    image = new java.awt.image.BufferedImage(width, height,
    java.awt.image.BufferedImage.TYPE_INT_RGB);
    // paint JPanel on off screen image
    Graphics2D g= image.createGraphics();
    g.setClip(jf.getBounds());
    System.err.println("BEFORE PAINT");
    jf.paint(g);
    System.err.println("AFTER PAINT");
    // write the offscreen image on disk for debug purposes
    File outputFile = new File("c:\\tmp\\image1.png");
    try {
    ImageIO.write(image, "PNG", outputFile);
    } catch (Exception e) {
    System.err.println(e.getMessage());
    g.dispose();
    jf.dispose();
    public static void main(String[] args) {
    test t=new test();
    }

  • I want to display a 2d image in a buffer then onto screen

    Hi!
    I was wondering does anyone know how to draw an image first into a buffer
    and then when desirable onto the screen.
    so for example in class A there is a method:
    void setContrast(float contrast)
    contrast = contrast;
    repaint;
    }and then in class B i want to paint first into a buffer for a given contrast and then onto the screen when i want.
    any ideas?

    the problem is, my paint method has to be as follows:
    and it is in a class called class A.
    //in class A
    public void paint(Graphics g)
    super.paint(g);
    Graphics2D g2D = (Graphics2D) g;
    for(j=0; j<size; j=j+2)
      for(k = 0; k<size; k=k+2)
       g2D.setPaint(new Color(contrast, contrast, contrast));
       Rectangle2D r2 = new Rectangle2D.Float(j, k, 2, 2)
       g2D.fill(r2)
    }the contrast is set through class B calling setContrast(float contrast) which is a method in A
    public void setContrast(double c)
    contrast =c ;
    repaint();
    }in this case, how would i do it? and then to display the image in class B?
    thanks!!

  • Read PNG and draw to buffer

    Some one help me , how to read PNG file by binary, and then draw it to buffer , next draw to screen.
    Thanks

    public void paint( Graphics g )
        //double buffer
        Image img = Image.createImage( g.getClipWidth(), g.getClipHeight() );
        Graphics gr = img.getGraphics();
        try
        gr.drawImage( Image.createImage( "/image.png" ), 0, 0, Graphics.TOP | Graphics.LEFT )
        catch( Exception e )
        g.drawImage( img, 0, 0, Graphics.TOP | Graphics.LEFT );
    }Of course, this is just an example.

  • Dates not refreshed correctly

    Hi,
    We are using service contracts BT112H_SC from Web UI. From this component we are calling SAP GUI actions (using transaction launcher) to make changes to the contract u2013 like cancellations, date changes and so on.
    We now have a problem with refreshing the Dates assignment block from service contract. The Dates assignment block is handled within a separate component called BTDATES and is called from BT112H_SC using component usage.
    When running an action that should change the dates (due to for example an Annulation of contract), the status is set to Cancelled but the dates Contract end date is not changed. I am calling function module CRM_ORDER_READ_OW after the action is executed in some places and see that the dates are updated correctly in the buffer, but they are not showing up in the Web UI.
    It seems as the dates are set correctly if I donu2019t expand the assignment block Dates before running the action. So if I expand the assignment block after running the action the dates are set correctly. If expanding the Dates assignment block before running the action, the dates are not updated.
    The dates are also set correctly after saving the contract so it is just a matter of visibility.
    Also if I (after running the action), go to one of the items and expanding the Dates assignment block on item level and then go back to header level the dates are displayed correctly.
    I have enhanced component BTDATES/Dates u2013 Method DO_PREPARE_OUTPUT where I use the following commands that should refresh the values.
    me->typed_context->btdate->collection_wrapper->publish_current( ).
        lr_ent ?= me->typed_context->btdate->collection_wrapper->get_current( ).
        lr_ent->reread( ).
    I have also used the command modify without success.
    Somehow the BTDATES component must be refreshed to read the dates from the buffer correctly after the action is executed.
    Do anyone have any suggestions on how to handle this?
    Regards Andreas

    Hi,
    Thanks a lot for your answers. I need all input I can get.
    Kathirvel: I can see that event 0002_expand_link is triggered (from class  ZL_BT112H_S_MAINWINDOW_IMPL I believe) when expanding the Dates assigment block. But I cannot figure out what is happening next.
    But after expanding the assignment block once, the event is not triggered if I expand/collapse the assigment block again.
    I see that in CL_BSP_WD_VIEW_MANAGER ~ DO_FINISH_INPUT when expanding Date assignment block, a BOL_CORE->MODIFY statement is made. This code is triggered when expanding the Date assignment block (but only first time).
    Do you know which event I could call to trigger the update again?
    asen2222 : I entered the code lr_core->modify( ) in ZL_BT112H_S_OVVIEWSET_IMPL ~ DO_PREPARE_OUTPUT which is called after my action is executed and the dates are modified in the buffer. But it doesn't work. When debugging the modify( ) method it seems as it have no delta-information to save.
    I have also tried setting the statement in component BTDATES - ZL_BTDATES_DATES0_IMPL ~ DO_PREPARE_OUTPUT without success.
    In the same place -  component BTDATES - ZL_BTDATES_DATES0_IMPL ~ DO_PREPARE_OUTPUT  -  I also put the following code:
    lr_ent ?= me->typed_context->btdate->collection_wrapper->get_current( ).lr_ent->reread( ).
    This do not work either. But if I debug the reread method and go into
    method REREAD_ENTITY of CL_CRM_BOL_CORE I see following code:
    lv_relation_cacheable = me->object_model->relation_is_cacheable(
    lv_parent_relation_name ).
    If I then set lv_relation_cacheable = ' ', it seems to bypass the buffer and read the data from underlying layers. And then the values is showingcorrectly updated!.
    I believe it is reading the relation from table CRMC_ORLSTA_BTIL but this
    table do not include field DO_NOT_BUFFER so I assume this field should
    never be set for business transactions. But in this case it wouldhave worked for us.
    Regards Andreas

  • Background Painting of "Out of focus" tabbed Panel (JTabbedPane) ?

    Hi
    I would like to add a on going Bar Graph to a JTabbedPane, this works fine if the specific Tab is in Focus, but when the tab is switched, Painting stops!
    How can i ensure the painting continues in the background!
    Here is an example which demo's the problem! Also, watch the standard out...
    Any idea's how to solve this ?
    import java.awt.*;
    import java.awt.geom.*;
    import javax.swing.*;
    import javax.swing.JPanel;
    import java.util.*;
    public class TestPanel extends JPanel {
        // Define the height and width of the bars. Given by calling process.
        private int height [];
        private int width;
        // Define the starting point of the bar chart and base line.
        private int top = 5;
        private int base = 100 + top;
        private int middle = (base/2)+(top/2);
        private int baseOffset = 3;
        private int indent = 45;
        private int step = (base - top)/10;
        private int baseLen = 0;
        private int tpsArray[];
        private int maxValue;
        private int counter = 0;
        private int value;
        public TestPanel(String server, String file ) {
            tpsArray = new int[32768];
            JFrame f =  new JFrame();
            JTabbedPane t = new JTabbedPane();
            // Set the Content and Window layout
            f.setLayout( new BorderLayout() );
            t.add( panel(), "Tab A");
            t.add( new JLabel("I AM TAB B"), "Tab B");
            f.add( t, BorderLayout.CENTER);
            //f.setExtendedState( Frame.MAXIMIZED_BOTH );
            f.setSize(400,400);
            f.setVisible(true);
        public JPanel panel() {
            // Define the JPanel to hold the graphic
            JPanel panel = new JPanel( new BorderLayout());
            panel.setBackground( Color.white );
            AnnimationModel annimationModel = new AnnimationModel();
            AnimationView animationView = new AnimationView(annimationModel);
            panel.add(animationView, BorderLayout.CENTER);
            return panel;
        private class AnimationView extends JPanel {
            private Dimension d = new Dimension();
            AnimationView(AnnimationModel annimationModel) {
                // Save a reference to the model for use
                // when the view is updated
                annimationModel_ = annimationModel;
                // Listen for the events indicating that the model has changed
                annimationModel_.addObserver(new Observer() {
                    public void update(Observable o, Object arg) {
                        // All we need to do is to get the view to repaint
                        AnimationView.this.repaint();
            public void paintComponent(Graphics g) {
                super.paintComponent(g);
                Graphics2D g2d = ( Graphics2D ) g;
                baseLen = getPanelWidth() - indent * 2 ;
                System.out.println("Painting Again.... Counter = " + counter  );
                int pos = ( indent + 6 );
                addOutLine(g2d);
                // Update the view based on the information in the model.
                g.setColor(Color.green);
                for ( int i=counter;i>0;i--) {
                    if ( pos > ( baseLen + indent )  ) break;
                    g.fill3DRect( pos, (base-tpsArray), 2, tpsArray[i], true );
    pos = pos + 2;
    tpsArray[counter] = value;
    public int getPanelWidth() {
    d.width = getWidth();
    return d.width;
    public void addOutLine(Graphics2D g2d) {
    // Setup the percentage markings on left vertical bar
    g2d.setColor( Color.GRAY );
    g2d.setFont( new Font("Sanserif", Font.PLAIN, 10));
    g2d.drawString( "0", (indent - 14), base + baseOffset );
    // Display the last TPS rate
    g2d.drawString( "" + maxValue, (indent - 20 ) , top+baseOffset );
    // Display the last TPS rate
    g2d.drawString( "(" + value + ")", 3, base + baseOffset );
    // Draw vertical line from top of bar chart to base line
    g2d.drawLine( indent, top, indent, base + baseOffset );
    // Draw horizontal base line
    g2d.drawLine( indent, base, indent+baseLen, base);
    // Draw horizontal top tick mark
    g2d.drawLine( (indent)-5, top, (indent)+5, top);
    // Draw horizontal tick line at 50% or middle point
    g2d.drawLine( (indent)-5, middle, (indent)+5, middle);
    // Draw horizontal tick at bottom base line
    g2d.drawLine( (indent)-5, base, (indent)+5, base);
    // Draw the dotted lines across the bar chart.
    g2d.setColor( new Color( 160,223,233));
    float dashes[] = { 1 };
    g2d.setStroke( new BasicStroke( 1, BasicStroke.JOIN_MITER, BasicStroke.JOIN_ROUND, 0, dashes, 0));
    for (int i=base; i>=top ;i=i-step) {
    g2d.drawLine( indent + 6, i, (indent+baseLen), i );
    // The saved reference to the model
    private AnnimationModel annimationModel_;
    private class AnnimationModel extends Observable {
    // private Shared sharedRef = new Shared();
    AnnimationModel() {
    Thread annimationThread = new Thread() {
    public void run() {
    while(true) {
    try {
    Thread.sleep(1000);
    } catch ( Exception e ) {
    value = 1 + (int) (Math.random() * 100 );
    counter++;
    // Notify the observers
    setChanged();
    notifyObservers();
    annimationThread.start();
    // Simple test main
    static public void main(String[] args) {
    TestPanel app = new TestPanel(null,null);
    Thanks,
    Rob

    How can i ensure the painting continues in the background! Well, I don't think you force painting since Swing appears to be smart enough to not paint a component that isn't visible.
    However, you should be able to do your painting on an offscreen image. So your offscreen image will be continually update. Then your paintComponent(...) method simply paints this offscreen image.
    This posting should get your started using this approach:
    http://forum.java.sun.com/thread.jspa?forumID=57&threadID=607073

  • Buffer for Adobe Media Server?

    Hi
    I am want to stream via a 4G USB modem. The internet connection has an upload from 1 to 5 Mbit, normally around 2-3. The Flash Media Live Encoder is streaming at 1.5 Mbit.
    Is it possible to add some buffer so when the intenret connection goes under 1.5 Mbit in it's upload it will not have an impact for the WebTV viewers because of a large buffer?
    Where to I add this buffer?
    The Adobe Encoder does not seems to have a buffer - correct? (If not where do I control this?)
    The Adobe Streaming Server version 3.5 (not the Interactive one) has a buffer which I can control in a config file - but which parameter do I change and to what value do I change it to?
    My flash web player (JW Player) certainly also has a buffer which I control very well already.
    Which buffer is best in this case? Or is it a combination of the different buffers?
    Thank you very much :-)

    Dear sir or madam,
    Here is Letswin Technology, which specializes in global servers, web hosting, VPS, VPNj. If anything I can do for you, pls contact us!
    Have a nice day!

  • Why dont we call method paint?? and declare it instead

    usually i have seen from previous examplies in my bok that we declare methods somewhere and then we call them sending arguments but in case of paint i saw only declaration as follows
    public void paint(Graphics g){
    after declaring why is there no code like this:paint(g1);
    why no call and still paint does the work .its confusing

    Two answers to that:
    1) JVM calls paint on its own whenever it detects a need to redraw the screen. This can occur when something is added to it, when a frame is partially covered, moved, resized, etc...
    2) paint can sometimes be called programmatically using the repaint() method. This is preferable to calling paint because it finds the correct Graphics object and makes sure that everything that needs a repaint gets its paint method called...
    Steve

  • Updating paint methods

    Hi all,
    I was wondering if you can help,
    I am programming a java game applet and have got a large picture placed directly onto the applet, which is updated with an animation thread.
    This doesn't look right and I want to put the picture in a JPanel so that I can arrange my GUI better.
    The usual way seems to be to extend a JPanel in a inner class and use its paintComponent method, but I'm not sure how to convert the code I have at the moment to do this. Especially using the drawImage method I use currently (see below).
    public void paint(Graphics g){
         offScreen.drawImage(bgimage, 0, 0, this);
            offScreen.drawImage(fgimage, 0, 0, this);       
            colony.paint(offScreen);                                    
            g.drawImage(image, 0, 0, imageViewWidth, imageViewHeight,imageViewX_tc, imageViewY_tc, imageViewX_bc, imageViewY_bc, this);
    } Any help would be appreciated,
    John

    I don't suggest you use a JPanel for animation, because it is swing, and swing is not thread-safe. Which means you have to use the much slower javax.swing.Timer rather than java.lang.Thread. However, I'll still convert your code in case you still want to do it:
    public void paintComponent(Graphics g) {
         super.paintComponent(g);
         offScreen.drawImage(bgimage,0,0,this);
         offScreen.drawImage(fgimage,0,0,this);
         colony.paint(offScreen);
         g.drawImage(image, 0, 0, imageViewWidth, imageViewHeight,imageViewX_tc, imageViewY_tc, imageViewX_bc, imageViewY_bc, this);
    }You should really decide to use an AWT component for your animation, like Panel (or event better- Canvas), because you can use the much faster Thread. So try using Canvas, you can still add it to your GUI because it's a child class of Component.

  • Method paint and DVBTextLayoutMAnager

    Its good idea use method paint when i'm using DVBTextLayoutMAnager??
    Thanks a lot

    Two answers to that:
    1) JVM calls paint on its own whenever it detects a need to redraw the screen. This can occur when something is added to it, when a frame is partially covered, moved, resized, etc...
    2) paint can sometimes be called programmatically using the repaint() method. This is preferable to calling paint because it finds the correct Graphics object and makes sure that everything that needs a repaint gets its paint method called...
    Steve

Maybe you are looking for