Volatile Images vs Normal Image

I am working a tile-based game, so reducing the time required to draw a tile would be a big help. I know that if you use volatile images (Java's term for images stored in video memory) you get better performance. However, I read that Java does this in the background where possible and that in most cases manually coding the use of volatile images (including checking that they have not been dumped from video memory) is a waste of time because the standard Image class handles this for you. Is this correct?
Currently my game uses standard images. During the first few redraws of the screen (it is turn-based, not real-time) the delay is very noticable, but after that silky smooth. I'm wondering if that is the JRE reaching some threshold and switching to volatile image use. Any ideas? (I realize it could be a hot spot compiler kicking in, but it seems unlikely that 2-3 calls of the paint function are sufficient to result in a hot spot compilation.)

yep,
this is the Thread you are after :-
http://www.javagaming.org/cgi-bin/JGNetForums/YaBB.cgi?board=2D;action=display;num=1048663269;start=0#0
More specifically this bit :-
>
3. Changing acceleration threshold
Acceleration threshold controls how many copies from managed images
will occur before we create a vram version of the image.
If the number is '0', the accelerated surface is created during
image initialization.
The default threshold is 1.
A new threshold can be set via flag:
-Dsun.java2d.accthreshold=N (where N>=0)
If the threshold is set to 0, all the vram surfaces
for all managed images will be created at the image
creation time, and updated during the first copy from image.
This flag can be used to eliminate the initial delay in rendering
when the images are being copied to the vram after the first few
copies. Instead, the delay is effectively shifted to the image
creation time.
This could be useful behavior when you know that your application
will be able to take advantage of image management; just get the
overhead of the copy over with at the start instead of incurring some
number of slower copies to begin with and then having the copy overhead
at some later time.
System.setProperty("sun.java2d.accthreshold", "0");

Similar Messages

  • Page flipping with Volatile Image.  Need help :)

    Hello all,
    Could someone point me to a nice tutorial which specifically addresses setting up page flipping with Volatile Images as the buffer? I haven't had any trouble with the generic BufferStrategy way of doing things, but it looks like the absolute fastest way to go is page flipping. Any info on this subject would be appreciated. I am a student who is making his first attempt at setting up a fullscreen video game...well if you want to call it that! :) I am shooting for Pong as a first project!
    Please feel free to send me the info at [email protected], and thanks much.
    Kmyers

    If you're using Windows, then your picture is already most likely
    being stored as volatile. You should look for an article on the
    web discussing Java rendering internals as of 1.4 do a search for
    "java automatic images" you'll probably find some useful info.
    But if you insist you can just fire up a debugger and
    play with it until you finally figure out what it's doing..
    You just need to do a createVolatileImage as opposed to createImage
    when creating your buffers.. make sure to use
    createBufferStrategy(2) (or if you want to be totally sure print out
    the capabilities of the buffers available and select one that you
    know for sure supports back and front buffers that are "truly"
    volatile..
    it turns out in my experience on win2k that using normal "automatic"
    images via Component.createImage() are faster than volatiles perhaps
    because I tend to do alot of scaling ops which are not as of yet
    accelerated..
    here's some stuff that might help you:
    good luck!
    static public void printBufferCapabilities(BufferCapabilities bc) {
    System.out.println("Printing Buffer Capabilities: ");
    if (bc.isFullScreenRequired())
    System.out.println("Full screen is required");
    else
    System.out.println("Full screen is required");
    if (bc.isMultiBufferAvailable())
    System.out.println("MultiBuffering is available");
    else
    System.out.println("MultiBuffering is not available");
    if (bc.isPageFlipping())
    System.out.println("PageFlipping is available");
    else
    System.out.println("PageFlipping is not available");
    ImageCapabilities ic = bc.getBackBufferCapabilities();
    if (ic.isAccelerated())
    System.out.println("BackBuffer is accelerated");
    else
    System.out.println("BackBuffer is not accelerated");
    if (ic.isTrueVolatile())
    System.out.println("BackBuffer is truly volatile");
    else
    System.out.println("BackBuffer is not truly volatile");
    ic = bc.getFrontBufferCapabilities();
    if (ic.isAccelerated())
    System.out.println("FrontBuffer is accelerated");
    else
    System.out.println("FrontBuffer is not accelerated");
    if (ic.isTrueVolatile())
    System.out.println("FrontBuffer is truly volatile");
    else
    System.out.println("FrontBuffer is not truly volatile");
    static public void printImageCapabilities(ImageCapabilities ic) {
    System.out.println("Printing Image Capabilities: ");
    if (ic.isAccelerated())
    System.out.println("Image is accelerated");
    else
    System.out.println("Image is not accelerated");
    if (ic.isTrueVolatile())
    System.out.println("Image is truly volatile");
    else
    System.out.println("Image is not truly volatile");
    static public void printFlipContents(BufferCapabilities.FlipContents flip) {
    if (flip == null) { System.out.println("Dude your flip is flipping NULL!"); return; }
    if (flip.equals(BufferCapabilities.FlipContents.BACKGROUND))
    System.out.println("Flip Contents are BACKGROUND");
    else if (flip.equals(BufferCapabilities.FlipContents.COPIED))
    System.out.println("Flip Contents are COPIED");
    else if (flip.equals(BufferCapabilities.FlipContents.PRIOR))
    System.out.println("Flip Contents are PRIOR");
    else if (flip.equals(BufferCapabilities.FlipContents.UNDEFINED))
    System.out.println("Flip Contents are UNDEFINED");
    else System.out.println("Where the hell did you find this flipping Flip Contents, now flip off!");
    static public void printElapsedTime(String desc, long start, long stop ) {
    long s = stop - start;
    double elapsed = (double) s/1000;
    System.out.println("The elapsed time for "+desc+" :"+elapsed);
    public static void chooseBestDisplayMode(GraphicsDevice device) {
    DisplayMode best = getBestDisplayMode(device);
    if (best != null) {
    device.setDisplayMode(best);

  • Volatile Image Full screen display

    Hi,
    Pls tell me where to find the getpaintGraphics();
    function for active rendereing.I searched whole 1.4.1 API and it is not compiling.The code is sample from Java website.
    public void myRenderingLoop() {
    while (!done) {
    Graphics myGraphics = getPaintGraphics();
    // Draw as appropriate using myGraphics
    myGraphics.dispose();
    Thanks in advance.
    Esh

    Hi - I had the same confusion, having read the same tutorial.
    You want to get a Graphics object to draw with... The method is:
    Graphics g = aComponent.getGraphics();
    and comes from the class java.awt.Component library.
    Hope this helps
    James

  • Why are backgrounds to created images black?

    Dear all,
    In creating a bufferred image (or a volatile image - perhaps this problem exists with all image classes), the background is completely black. Only the painted components (typically small coloured rectangles) appear as they should do, colour wise. I am creating the graphics using a Graphics2D object in the standard way. However, a call to
    g2.setBackground(Color.white) etc still results in a background color black, as does
    g2.setColor(Color.white), before the call that adds the rectangles
    So I thought, I'd first draa one huge white rectangle using something like
    g2.setColor(new Color(255,255,255)), then
    g2.fill3DRect(0,0,600,900,false) // whatever
    and then draw over the rectangles that I need to add. However the resultant background colour is gray rather than white. Whats going on?
    Any suggestions?
    Cheers
    Ben

    Here's a demo of using setColor.Works for me.
    import java.awt.*;
    import java.awt.image.*;
    import javax.swing.*;
    public class ImageBackground {
        public static void main(String[] args) {
            final int W = 200, H = 100;
            BufferedImage bi = new BufferedImage(W, H, BufferedImage.TYPE_INT_RGB);
            Graphics2D g = bi.createGraphics();
            g.setColor(Color.WHITE); //!
            g.fillRect(0,0,W,H);    //!
            g.setColor(Color.BLUE);
            g.setFont(new Font("Lucida Bright", Font.PLAIN, 16));
            g.drawString("Hello, World!", 10, 50);
            g.dispose();
            JLabel label = new JLabel(new ImageIcon(bi));
            final JFrame f = new JFrame("ImageBackground");
            f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            f.getContentPane().add(label);
            f.pack();
            SwingUtilities.invokeLater(new Runnable(){
                public void run() {
                    f.setLocationRelativeTo(null);
                    f.setVisible(true);
    }

  • Anyone have a example for useing volitile image in exclusive mode with

    i need a example of how to use a volitile image in exclusive mode with active rendering .
    anyone know of one or even partial code of how to do it ive been racking my brain trying to figure out how to do it.
    or even a example of fullscreen that i can use to draw to the screen in exclusive fullscreen mode.
    and im not talking about the sun tutorial no one can even answer my question about it when i asked in the java forum

    by the way, here's a commented version of the example I gave earlier in case the puzzle pieces are upside down for you...
    import java.awt.*;
    import java.awt.event.*;
    import java.awt.image.*;
    /* Goes into FullScreen with 640x480 16 bit
    * Not all proper checks are made (like getting available DisplayModes),
    * But you can always look at the doc for the rest of the checks. Besides,
    * What computer doesn't have 640x480...?
    public class Example extends Frame implements Runnable, KeyListener {
         VolatileImage v;
         int w,h,x,size; // x and size are for the moving ball
         boolean done; // when this is true, the program exits
         public Example() {
              /* Sets up the frame to be used for fullscreen */
              super(GraphicsEnvironment.getLocalGraphicsEnvironment().getDefaultScreenDevice().getDefaultConfiguration());
              GraphicsDevice device = GraphicsEnvironment.getLocalGraphicsEnvironment().getDefaultScreenDevice();
              /* the below 2 methods aren't required
              * but using them results in best performance.*/
              setUndecorated(true);
              setIgnoreRepaint(true);
              /* A few mandatorial checks */
              if (device.isFullScreenSupported()) {
                   device.setFullScreenWindow(this);
              if (device.isDisplayChangeSupported()) {
                   device.setDisplayMode(new DisplayMode(640,480,16,0));
              /* our frame must be showing before we
              * we create our BufferStrategy or image,
              * in this case a VolatileImage.
              * Showing our frame also switches to
              * fullscreen mode.
              show();
              w = getSize().width;
              h = getSize().height;
              x = 0;
              size = 30;
              v = createVolatileImage(w,h); // creates volatile image (duh)
              done = false; // program exits when true
              addKeyListener(this); // used for exiting
              new Thread(this).start(); // starts the thread
         public void run() {
              while (!done) {
                   x += 2; // increase ball location
                   if (x >= w-size) x = 0; // back to left if all the way right
                   /* You could also use repaint() here,
                   * but you won't get a screen update
                   * until the system decides it's time.
                   * calling paint(getGraphics()) is much faster
                   paint(getGraphics());
                   /* Pausing of the thread... */
                   try {
                        Thread.sleep(1);
                   catch (InterruptedException e) {
                        done = true; // exit if there was some error
              System.exit(0); // this won't be called until done is true
         public void paint(Graphics g) {
              /* this attempts to get the graphics
              * from VolatileImage */
              Graphics gfx = v.getGraphics();
              /* If VolatileImage has no image memory,
              * we restore it and get the graphics for it */
              while (v.contentsLost()) {
                   if (v.validate(getGraphicsConfiguration()) == VolatileImage.IMAGE_INCOMPATIBLE) {
                        v = createVolatileImage(w,h);
                   gfx = v.createGraphics();
              /* this paints the ball etc */
              gfx.setColor(Color.black);
              gfx.fillRect(0,0,w,h);
              gfx.setColor(Color.cyan);
              gfx.fillOval(x,h/2-(size/2),size,size);
              g.drawImage(v,0,0,null); // draw the VolatileImage
         public void update(Graphics g) { // used for no blinking
              paint(g);
         public void keyPressed(KeyEvent e) {
              if (!done) done = true; // program exits on any key press
         public void keyReleased(KeyEvent e) {}
         public void keyTyped(KeyEvent e) {}
         public static void main(String[] args) {
              new Example();
    }

  • Please, help a newbie:  Question about animating expanding containers

    Hi All,
    Short Version of my Question:
    I'm making a media player that needs to have an animation for panels sliding up and down and left and right, and the method I've been using to do this performs far slower than the speed I believe is possible, and required. What is a fast way to make a high performance animation for such an application?
    Details:
    So far, to do the animation, I've been using JSplitPanes and changing the position of the divider in a loop and calling paintImmediately or paintDirtyRegion like so:
    public void animateDividerLocation( JSplitPane j, int to, int direction) {
    for(int i=j.getDividerLocation(); i>=to; i-=JUMP_SIZE) {
    j.setDividerLocation(i);
    j.validate();
    j.paintImmediately(0, 0, j.getWidth(), j.getHeight());
    The validate and paintImmediately calls have been necessary to see any changes while the loop is going. I.e., if those calls are left out, the components appear to just skip right to where they were supposed to animate to, without having been animated at all.
    The animation requirement is pretty simple. Basically, the application looks like it has 3 panels. One on the right, one on the left, and a toolbar at the bottom. The animation just needs to make the panels expand and contract.
    Currenly, the animation only gets about, say, 4 frames a second on the 800 MHz Transmeta Crusoe processor, 114 MB Ram, Windows 2000 machine I must use (to approximate the performance of the processor I'll be using, which will run embedded Linux), even though I've taken most of the visible components out of the JPanels during the animation. I don't think this has to do with RAM reaching capacity, as the harddrive light does not light up often. Even if this were the case, the animation goes also goes slow (about 13 frames a second) on my 3 GHz P4 Windows XP if I keeps some JButtons, images etc., inside the JPanels. I get about 50 frames/sec on my 3 GHz P4, if I take most of the JButtons out, as I do for the 800 MHz processor. This is sufficient to animate the panels 400 pixels across the screen at 20 pixels per jump, but it isn't fast or smooth enough to animate across 400 pixels moving at 4 pixel jumps. I know 50 frames/sec is generally considered fast, but in this case, there is hardly anything changing on the screen (hardly any dirty pixels per new frame) and so I'd expect there to be some way to make the animation go much faster and smoother, since I've seen games and other application do much more much faster and much smoother.
    I'm hoping someone can suggest a different, faster way to do the animation I require. Perhaps using the JSplitPane trick is not a good idea in terms of performance. Perhaps there are some tricks I can apply to my JSplitPane trick?
    I haven't been using any fancy tricks - no double buffering, volatile images, canvas or other animation speed techniques. I haven't ever used any of those things as I'm fairly new to Swing and the 2D API. Actually I've read somewhere that Swing does double buffering without being told to, if I understood what I read. Is doing double buffering explicitly still required? And, if I do need to use double buffering or canvas or volatile images or anything else, I'm not sure how I would apply those techiniques to my problem, since I'm not animating a static image around the screen, but rather a set of containers (JSplitPanes and JPanels, mostly) and components (mostly JButtons) that often get re-adjusted or expanded as they are being animated. Do I need to get the Graphics object of the top container (would that contain the graphics objects for all the contained components?) and then double buffer, volatile image it, do the animation on a canvas, or something like that? Or what?
    Thanks you SO much for any help!
    Cortar
    Related Issues(?) (Secondary concerns):
    Although there are only three main panels, the actual number of GUI components I'm using, during the time of animation, is about 20 JPanels/JSplitPanes and 10 JButtons. Among the JPanels and the JSplitPanes, only a few JPanels are set to visible. I, for one, don't think this higher number of components is what is slowing me down, as I've tried taking out some components on my 3GHz machine and it didn't seem to affect performance much, if any. Am I wrong? Will minimizing components be among the necessary steps towards better performance?
    Anyhow, the total number of JContainers that the application creates (mostly JPanels) is perhaps less than 100, and the total number of JComponents created (mostly JButtons and ImageIcons) is less than 200. The application somehow manages to use up 50 MBs RAM. Why? Without looking at the code, can anyone offer a FAQ type of answer to this?

    You can comment out the lines that add buttons to the panels to see the behavior with empty panels.
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    import javax.swing.Timer;
    public class DancingPanels
        static GridBagLayout gridbag = new GridBagLayout();
        static Timer timer;
        static int delay = 40;
        static int weightInc = 50;
        static boolean goLeft = false;
        public static void main(String[] args)
            final GridBagConstraints gbc = new GridBagConstraints();
            gbc.weightx = 1.0;
            gbc.weighty = 1.0;
            gbc.fill = gbc.HORIZONTAL;
            final JPanel leftPanel = new JPanel(gridbag);
            leftPanel.setBackground(Color.blue);
            gbc.insets = new Insets(0,30,0,30);
            leftPanel.add(new JButton("1"), gbc);
            leftPanel.add(new JButton("2"), gbc);
            final JPanel rightPanel = new JPanel(gridbag);
            rightPanel.setBackground(Color.yellow);
            gbc.insets = new Insets(30,50,30,50);
            gbc.gridwidth = gbc.REMAINDER;
            rightPanel.add(new JButton("3"), gbc);
            rightPanel.add(new JButton("4"), gbc);
            final JPanel panel = new JPanel(gridbag);
            gbc.fill = gbc.BOTH;
            gbc.insets = new Insets(0,0,0,0);
            gbc.gridwidth = gbc.RELATIVE;
            panel.add(leftPanel, gbc);
            gbc.gridwidth = gbc.REMAINDER;
            panel.add(rightPanel, gbc);
            timer = new Timer(delay, new ActionListener()
                    gbc.fill = gbc.BOTH;
                    gbc.gridwidth = 1;
                public void actionPerformed(ActionEvent e)
                    double[] w = cycleWeights();
                    gbc.weightx = w[0];
                    gridbag.setConstraints(leftPanel, gbc);
                    gbc.weightx = w[1];
                    gridbag.setConstraints(rightPanel, gbc);
                    panel.revalidate();
                    panel.repaint();
            JFrame f = new JFrame("Dancing Panels");
            f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            f.getContentPane().add(panel);
            f.setSize(400,300);
            f.setLocation(200,200);
            f.setVisible(true);
            timer.start();
        private static double[] cycleWeights()
            if(goLeft)
                weightInc--;
            else
                weightInc++;
            if(weightInc > 100)
                weightInc = 100;
                goLeft = true;
            if(weightInc < 0)
                weightInc = 0;
                goLeft = false;
            double wLeft = weightInc/ 100.0;
            double wRight = (100 - weightInc)/100.0;
            return new double[]{wLeft, wRight};
    }

  • Random slowdown of BufferedImage painting.

    Relying on another thread that dealed with painting background image in GUI using Borders, I wrote a custom Border that display an image in the background. This is quite smart and stylish, it works and looks beautifull, except that.....
    I get sometimes a slowdown (on specific images) in painting. I mean : if I resize the window that contain the JPanel with my "ImageBorder", or if I hide then re-make visible this window, with a lot of images it is cool but with some specific images (always the same files) is take 100% CPU for 3 to 10s.
    It is not size-dependant as I suspected, cause somme huge images repaint quick as some small ones repaint slow qith 100% CPU.
    It is not type-dependant (TYPE_INT_XXX or TYPE_BYTE_YYY or other) as I thought... I believed first that images with Alpha-channel where slower but is it false : huges TYPE_CUSTOM png images with alpha channel repaint faster than a specific TYPE_3BYTE_BGR small jpeg image...
    So is there a bug in J2SE 1.4 (I'm using Hotspot 1.4.1-b21, mixed mode) ?
    Or is my code wrong ? Is it possible to predict wich images will slow down painting process ?
    package jro.gui.border;
    import java.awt.BorderLayout;
    import java.awt.Component;
    import java.awt.Graphics;
    import java.awt.Graphics2D;
    import java.awt.Insets;
    import java.awt.geom.AffineTransform;
    import java.awt.image.AffineTransformOp;
    import java.awt.image.BufferedImage;
    import java.awt.image.BufferedImageOp;
    import javax.imageio.ImageIO;
    import javax.swing.border.Border;
    * A border with a background image for GUI enhancement...
    * @author Kilwch
    public class ImageBorder implements Border {
         private BufferedImage aImage;
         private ImageBorder(){
         public ImageBorder(BufferedImage backgroundImage){
              aImage=backgroundImage;
         /* (non-Javadoc)
          * @see javax.swing.border.Border#isBorderOpaque()
         public boolean isBorderOpaque() {
              //TODO : utiliser la transparence de l'image pour d�terminer si opaque ou non
              return true;
         /* (non-Javadoc)
          * @see javax.swing.border.Border#paintBorder(java.awt.Component, java.awt.Graphics, int, int, int, int)
         public void paintBorder(Component c, Graphics g, int x, int y, int width, int height) {
              if(g instanceof Graphics2D){
                   Graphics2D g2d=(Graphics2D)g;
                   int w=aImage.getWidth(), h=aImage.getHeight();
                   if(w!=width || h!=height){
                        BufferedImageOp op=new AffineTransformOp(AffineTransform.getScaleInstance(width/(double)aImage.getWidth(),height/(double)aImage.getHeight()),AffineTransformOp.TYPE_BILINEAR);
                        //TODO PROBLEM Draw with scale op is high-CPU consuming  ! Due to Alpha channel ? Problem occured with QNS only
                        g2d.drawImage(aImage, op, x, y);
                   }else
                        g2d.drawImage(aImage, null, x, y);
         /* (non-Javadoc)
          * @see javax.swing.border.Border#getBorderInsets(java.awt.Component)
         public Insets getBorderInsets(Component c) {
              return new Insets(0,0,0,0);//Copie d�fensive, car Insets a des attributs publics ! grr...
         public static void main(String[] args) {
              if(args.length<1){
                   System.err.println("Missing argument : image URL/path");
                   System.exit(0x80010000);
              java.net.URL imageURL=ImageBorder.class.getClassLoader().getResource(args[0]);
              if(imageURL==null){
                   System.err.println("Invalid image URL/path : "+args[0]);
                   System.exit(0x80020000);
              BufferedImage img;
              try{
                   img=ImageIO.read(imageURL);
                   StringBuffer imgMsg=new StringBuffer(256);
                   imgMsg.append("Image loaded: ").append(imageURL).append("\n * type = ");
                   switch(img.getType()){
                        case BufferedImage.TYPE_3BYTE_BGR: imgMsg.append("TYPE_3BYTE_BGR"); break;
                        case BufferedImage.TYPE_4BYTE_ABGR: imgMsg.append("TYPE_4BYTE_ABGR"); break;
                        case BufferedImage.TYPE_4BYTE_ABGR_PRE: imgMsg.append("TYPE_4BYTE_ABGR_PRE"); break;
                        case BufferedImage.TYPE_BYTE_BINARY: imgMsg.append("TYPE_BYTE_BINARY"); break;
                        case BufferedImage.TYPE_BYTE_GRAY: imgMsg.append("TYPE_BYTE_GRAY"); break;
                        case BufferedImage.TYPE_BYTE_INDEXED: imgMsg.append("TYPE_BYTE_INDEXED"); break;
                        case BufferedImage.TYPE_CUSTOM: imgMsg.append("TYPE_CUSTOM"); break;
                        case BufferedImage.TYPE_INT_ARGB: imgMsg.append("TYPE_INT_ARGB"); break;
                        case BufferedImage.TYPE_INT_ARGB_PRE: imgMsg.append("TYPE_INT_ARGB_PRE"); break;
                        case BufferedImage.TYPE_INT_BGR: imgMsg.append("TYPE_INT_BGR"); break;
                        case BufferedImage.TYPE_INT_RGB: imgMsg.append("TYPE_INT_RGB"); break;
                        case BufferedImage.TYPE_USHORT_555_RGB: imgMsg.append("TYPE_USHORT_555_RGB"); break;
                        case BufferedImage.TYPE_USHORT_565_RGB: imgMsg.append("TYPE_USHORT_565_RGB"); break;
                        case BufferedImage.TYPE_USHORT_GRAY: imgMsg.append("TYPE_USHORT_GRAY"); break;
                        default: imgMsg.append("unknown");
                   imgMsg.append(" (type ").append(img.getType()).append(")");
                   imgMsg.append("\n * Dim = ").append(img.getWidth()).append("x").append(img.getHeight());
                   System.out.println(imgMsg);
              }catch(java.io.IOException pIOEx){
                   System.err.println(pIOEx);
                   System.exit(0x80030000);
                   img=null;//Yes, thats dead code !
              javax.swing.JFrame testFrame=new javax.swing.JFrame();
              testFrame.setDefaultCloseOperation(javax.swing.JFrame.EXIT_ON_CLOSE);
              testFrame.setTitle("Test frame for "+ImageBorder.class.getName());
              testFrame.setSize(img.getWidth(), img.getHeight());
              ((javax.swing.JPanel)testFrame.getContentPane()).setBorder(new ImageBorder(img));
              testFrame.getContentPane().setLayout(new BorderLayout());
              javax.swing.JLabel [] l={new javax.swing.JLabel(args[0]),new javax.swing.JLabel()};
              l[0].setForeground(new java.awt.Color(0x00,0x00,0x66,0xC0));
              l[0].setBackground(new java.awt.Color(0xFF,0xFF,0x99,0x30));
              l[0].setOpaque(true);
              testFrame.getContentPane().add(l[0], BorderLayout.NORTH);
              testFrame.getContentPane().add(l[1], BorderLayout.CENTER);
              testFrame.setVisible(true);
    }

    I've just tried out the VolatileImage. It is a partial workaround for my problem :
    1) the very first paint of my VolatileImage (and next "first paint after contentLost") takes bloody ages, because I need to create a BufferedImage first (from an URL).
    2)Then, each time I need to resize my VolatileImage (because I want it to fit the JFrame's content pane), I have to recreate it, so I re-use the BufferedImage that is the source data, and it re-takes bloody ages.
    3) it is OK since the content of VolatileImage is not lost. So minimize/restore the parent JFrame does not slow down repaint anymore, hiding the parent JFrame with another window then putting it back to front does not slow repaint anymore.
    4)Big Alpha problem : The volatile image is used to paint the borders of the content pane. Imagine now your content pane contains a yellow JLabel with 75% transparency : when another window passes over the JLabel, it look ugly (the window lets dirty marks). It seems that transparent components does not refresh with the underlying image like expected.
    (Note that I know where the slowdown occurs in the paint method : it occurs during image resize (scaling with BufferedImageOp). But I repeat, only on specific images, regardless of their size&colordepth. As I always need a BufferedImage to "remember" the picture to paint on VolatileImage, the slowdown occurs less often, but still occurs)
    Test it for the 4th problem (1st and 2nd come along with specifig images only), passing an image path as 1st arg (note the path is relative to current dir or any classpath dir as I'm using getRessource method):
    package jro.gui.border;
    import java.awt.BorderLayout;
    import java.awt.Component;
    import java.awt.Graphics;
    import java.awt.Graphics2D;
    import java.awt.Insets;
    import java.awt.geom.AffineTransform;
    import java.awt.image.AffineTransformOp;
    import java.awt.image.BufferedImage;
    import java.awt.image.BufferedImageOp;
    import java.awt.image.VolatileImage;
    import javax.imageio.ImageIO;
    import javax.swing.border.Border;
    * A border with a background image for GUI enhancement...
    * @author rousseau_j
    public class VolatileImageBorder implements Border {
         private VolatileImage aVImage;
         private BufferedImage aStaticImage;
         private VolatileImageBorder(){
         public VolatileImageBorder(BufferedImage backgroundImage){
              aStaticImage=backgroundImage;
         /* (non-Javadoc)
          * @see javax.swing.border.Border#isBorderOpaque()
         public boolean isBorderOpaque() {
              //TODO : utiliser la transparence de l'image pour d�terminer si opaque ou non
              return true;
         /* (non-Javadoc)
          * @see javax.swing.border.Border#paintBorder(java.awt.Component, java.awt.Graphics, int, int, int, int)
         public void paintBorder(Component c, Graphics g, int x, int y, int width, int height) {
              if((g instanceof Graphics2D)&& c!=null){
                   Graphics2D g2d=(Graphics2D)g;
                   if(aVImage==null){
                        aVImage=c.createVolatileImage(width, height);
                   int w=aVImage.getWidth(), h=aVImage.getHeight();
                   if(w!=width || h!=height){
                        aVImage=c.createVolatileImage(width, height);
                   do{
                        int returnCode = aVImage.validate(c.getGraphicsConfiguration());
                        if (returnCode == VolatileImage.IMAGE_RESTORED) {
                             renderOffscreen(c, x, y, width, height);
                        } else if (returnCode == VolatileImage.IMAGE_INCOMPATIBLE) {
                             aVImage = c.createVolatileImage(width, height);
                             renderOffscreen(c, x, y, width, height);
                        g2d.drawImage(aVImage, 0, 0, c);
                   }while(aVImage.contentsLost());
         private void renderOffscreen(Component c, int x, int y,int width,  int height){
              System.out.print("renderOffscreen{");//TEST
              do{
                   System.out.print("do{...");//TEST
                   if(aVImage.validate(c.getGraphicsConfiguration())==VolatileImage.IMAGE_INCOMPATIBLE){
                        aVImage=c.createVolatileImage(width, height);
                   Graphics2D vImgG2d=aVImage.createGraphics();
                   int w=aStaticImage.getWidth(), h=aStaticImage.getHeight();
                   if(w!=width || h!=height){
                        //TODO : option pour une redim d�finitive si image trop grande
                        BufferedImageOp op=new AffineTransformOp(AffineTransform.getScaleInstance(width/(double)aStaticImage.getWidth(),height/(double)aStaticImage.getHeight()),AffineTransformOp.TYPE_BILINEAR);
                        //TODO PROBLEM Draw with scale op is high-CPU consuming  ! Due to Alpha channel ? Problem occured with QNS only
                        vImgG2d.drawImage(aStaticImage, op, x, y);
                   }else
                   vImgG2d.drawImage(aStaticImage, null, x, y);
                   vImgG2d.dispose();
                   System.out.print("...}while; ");//TEST
              }while(aVImage.contentsLost());
              System.out.println("}\n");//TEST
         /* (non-Javadoc)
          * @see javax.swing.border.Border#getBorderInsets(java.awt.Component)
         public Insets getBorderInsets(Component c) {
              return new Insets(0,0,0,0);//Copie d�fensive, car Insets a des attributs publics ! grr...
         public static void main(String[] args) {
              if(args.length<1){
                   System.err.println("Missing argument : image URL/path");
                   System.exit(0x80010000);
              java.net.URL imageURL=VolatileImageBorder.class.getClassLoader().getResource(args[0]);
              if(imageURL==null){
                   System.err.println("Invalid image URL/path : "+args[0]);
                   System.exit(0x80020000);
              BufferedImage img;
              try{
                   img=ImageIO.read(imageURL);
                   StringBuffer imgMsg=new StringBuffer(256);
                   imgMsg.append("Image loaded: ").append(imageURL).append("\n * type = ");
                   switch(img.getType()){
                        case BufferedImage.TYPE_3BYTE_BGR: imgMsg.append("TYPE_3BYTE_BGR"); break;
                        case BufferedImage.TYPE_4BYTE_ABGR: imgMsg.append("TYPE_4BYTE_ABGR"); break;
                        case BufferedImage.TYPE_4BYTE_ABGR_PRE: imgMsg.append("TYPE_4BYTE_ABGR_PRE"); break;
                        case BufferedImage.TYPE_BYTE_BINARY: imgMsg.append("TYPE_BYTE_BINARY"); break;
                        case BufferedImage.TYPE_BYTE_GRAY: imgMsg.append("TYPE_BYTE_GRAY"); break;
                        case BufferedImage.TYPE_BYTE_INDEXED: imgMsg.append("TYPE_BYTE_INDEXED"); break;
                        case BufferedImage.TYPE_CUSTOM: imgMsg.append("TYPE_CUSTOM"); break;
                        case BufferedImage.TYPE_INT_ARGB: imgMsg.append("TYPE_INT_ARGB"); break;
                        case BufferedImage.TYPE_INT_ARGB_PRE: imgMsg.append("TYPE_INT_ARGB_PRE"); break;
                        case BufferedImage.TYPE_INT_BGR: imgMsg.append("TYPE_INT_BGR"); break;
                        case BufferedImage.TYPE_INT_RGB: imgMsg.append("TYPE_INT_RGB"); break;
                        case BufferedImage.TYPE_USHORT_555_RGB: imgMsg.append("TYPE_USHORT_555_RGB"); break;
                        case BufferedImage.TYPE_USHORT_565_RGB: imgMsg.append("TYPE_USHORT_565_RGB"); break;
                        case BufferedImage.TYPE_USHORT_GRAY: imgMsg.append("TYPE_USHORT_GRAY"); break;
                        default: imgMsg.append("unknown");
                   imgMsg.append(" (type ").append(img.getType()).append(")");
                   imgMsg.append("\n * Dim = ").append(img.getWidth()).append("x").append(img.getHeight());
                   System.out.println(imgMsg);
              }catch(java.io.IOException pIOEx){
                   System.err.println(pIOEx);
                   System.exit(0x80030000);
                   img=null;//Yes, thats dead code !
              javax.swing.JFrame testFrame=new javax.swing.JFrame();
              testFrame.setDefaultCloseOperation(javax.swing.JFrame.EXIT_ON_CLOSE);
              testFrame.setTitle("Test frame for "+VolatileImageBorder.class.getName());
              testFrame.setSize(img.getWidth(), img.getHeight());
              ((javax.swing.JPanel)testFrame.getContentPane()).setBorder(new VolatileImageBorder(img));
              testFrame.getContentPane().setLayout(new BorderLayout());
              javax.swing.JLabel [] l={new javax.swing.JLabel(args[0]),new javax.swing.JLabel()};
              l[0].setForeground(new java.awt.Color(0x00,0x00,0x66,0xC0));
              l[0].setBackground(new java.awt.Color(0xFF,0xFF,0x99,0x30));
              l[0].setOpaque(true);
              testFrame.getContentPane().add(l[0], BorderLayout.NORTH);
              testFrame.getContentPane().add(l[1], BorderLayout.CENTER);
              testFrame.setVisible(true);
    }

  • Full screen flickering

    Hello, I'm having some full screen issues like so m any people. I just finished converting my game to full screen mode, but now there are some problems with flickering which seems to be coming from when new images are loaded. Has any one else ever experienced a problem like this? I believe I'm going to use media tracker to finish loading the images and hope that helps. But, the computer also seems to stop updating the screen sometimes in which never happened when it was windows.
    These are the lines I used for buffering stratagie---
    (in main method)
    GraphicsConfiguration gc = device.getDefaultConfiguration();
    setUndecorated(true);
    setIgnoreRepaint(true);
    device.setFullScreenWindow(this);
    this.createBufferStrategy(2);
    bufferStrategy = this.getBufferStrategy();
    Thread th = new Thread (this);//other calculations
    th.start ();
    graphicsThread.start();//paints graphics
    --------------------------------------(this is for drawing graphics)
    class graphicsThread implements Runnable {
    private Thread thread = null;
    public void start() {
    if (thread == null) {
    thread = new Thread(this);
    thread.start();
    public void run() {
    thread.setPriority(9);
    while(true) {        
    Graphics g;
    g = bufferStrategy.getDrawGraphics();
    render(g);
    g.dispose();
    bufferStrategy.show();
    I am unsure if I want to try Volatile images or not. The frame rate is a bit low, but not unexceptable as I'm working on an RPG it isn't that important. So if anyone could help me with BufferStrategies I would be greatly obliged!

    yes, u have to ensure your images are fully loaded before you start rendering them.
    MediaTracker will do this for you.
    Alternatively you can load your images synchronously using ImageIO.read(..)
    (Note however, images returned from ImageIO are not ManagedImages - they must be copied to a ManagedImage before they will be elligable for hardware acceleration)
    As for the app. failing specifically when in fullscreen mode.
    What Java version are you using?
    There are alot of bugs related to fullscreen, most have been fixed in Java1.4.2 so i'd try upgrading to that and see if it fixes your problem.
    And with regard to the frame rate, if you are doing it right, you should be able to render several 1000 images at 60fps without to much hassel.
    Just make sure all your images are either ManagedImages or VolatileImages (depending on the circumstances, each have their uses.)

  • Output Device Redirector

    I have defined a class that calls my native methods that show up on my proprietray graphics device that implements these methods:
    void clearScreen(); // Writes the background color (black) from 0,0-Width,Height
    void setPoint(Point2D xy, Color c); //Sets the pixel at x/y to Color c
    int getWidth(); //Returns the 0-Width Visible Area
    int getHeight(); //Returns the 0-Height Visible Area
    Color getPoint(Point2D xy); // Returns the color of this point
    I would like Swing to write on my class instead of my monitor.
    Is this possible?
    What would I need to do?
    Thank you in advance~!
    PS:
    My tech level in java is pretty high.. but my problem in figuring this out myself.. lead me to these Questions:
    Do i subclass VolatileImage.. How do I make it use my volatile image instead of its own..
    Ok, if i subclass GraphicsConfiguration, don't i need to write my own Graphics class..
    Ok if i subclass Graphics, do i need to implement rectangle and circle fills?..
    Why Cant i just get away with being the target bitmap space for the existing Graphics object.. ..
    Possible i am sure.. ok am i a Cavas,Window,VolatileImage,BufferedImage,PrinterDevice,Raster? grr!

    On the oriinal class:
    MyMouse getMouse(); // Returns a device that exports these methods
    Point2D getXY();
    boolean buttonStateDown(int buttonnumber);
    int get numberButtons();
    I don't mind making this mouse device more statefull what interface should i implement for it?

  • Simple slideshow help

    Hi, I want to create a simple slideshow but my app fails with a NPE when it attempts to read in the first image.
    import javax.swing.JFrame;
    import javax.swing.JFileChooser;
    import java.io.*;
    import java.awt.*;
    import java.awt.image.*;
    import javax.swing.*;
    import java.awt.image.BufferedImage;
    import java.util.Vector;
    import java.awt.Graphics;
    public class Main extends JPanel implements Runnable
        private static Vector imagesArray;
        private static volatile Image currentImage;
        private static volatile boolean isInterrupted=false;
        private String strCurrentDir=System.getProperty("user.dir");
        //gets the current working directory
        private JFrame frame;
        private JPanel panel;
        public static void main(String[] args)
            new Main();
        public Main()
            frame = new JFrame();
            panel = new JPanel();
            frame.getContentPane().add(panel);
            getImages();    //prompt the user to select images
            Thread animationThread = new Thread(this);
            animationThread.start();
        public void getImages()
            String strTextFieldContents="";
            //open file chooser so the user can find the file
            JFileChooser fileChooser = new JFileChooser();
            fileChooser.setCurrentDirectory(new File(strCurrentDir));
            //sets file choose to use the current working directory
            fileChooser.addChoosableFileFilter((new ImagesFilter()));
            fileChooser.setDialogTitle("Please select image files");
            int returnVal = fileChooser.showOpenDialog(new JFrame());
            if (returnVal == JFileChooser.APPROVE_OPTION)
                    File temp=fileChooser.getSelectedFile();
                    strTextFieldContents=temp.getAbsolutePath();
                    imagesArray.add((String)strTextFieldContents);
            else{}
            imagesArray.trimToSize();
        public void run()
            while(isInterrupted==false)
                for(int i=0; i<imagesArray.size(); i++)
                    try
                        Thread.sleep(200);   //display the image for 200ms at a time
                    catch(InterruptedException e)
                        System.out.println("Interrupted");
                    // If the Toolkit cannot find the file or load the data it
                    // gives no warning. You must check on the loading status
                    // for yourself.
                    MediaTracker mt = new MediaTracker(this);
                    mt.addImage(currentImage, 0);
                    try
                        mt.waitForID(0);
                    catch(InterruptedException e)
                        System.out.println("media tracker interrupted");
                            int status = mt.statusAll(false);
                    if((status & MediaTracker.COMPLETE) != MediaTracker.COMPLETE)
                        System.out.println("status = " + status);
                    // getImage is asynchronous, ie, it doesn't wait for the
                    // image data to load. So you may need to stop to load it.
                    Toolkit toolkit = Toolkit.getDefaultToolkit();
                    String strImageLoc=(String)imagesArray.elementAt(i);
                    //currentImage = toolkit.getImage("Cuboid_Obstacle.jpg");
                    currentImage = toolkit.getImage(strImageLoc);
                    currentImage=(BufferedImage)imagesArray.elementAt(i);
                    panel.repaint();
        public void paintComponent(Graphics g)
            //super.paintComponent(g);
            Toolkit.getDefaultToolkit().sync();
            if (currentImage!=null)
                g.drawImage (currentImage, 0, 0, this);
    }

    The compiler tells you which line of your code generates the NullPointerException. Analyze that line to determine which of your references may be null.
    Hint: Declaring a variable reference does not initialize it!
    Then deal with the ClassCastException the same way.
    db

  • Re: Hardware Accelleration / Playing Video

    Yes, such image indeed will not be accelerated - because you have the pointer to the raw data.
    Here is an approach which I've suggested to other people with similar issues.
    Create a VolatileImage
    Copy your BufferedImage to this volatile image
    copy the volatile image to the back-buffer
    This approach especially helps if you need to copy the image to the backbuffer more often that it's updated by the video stream, or if you need to scale the frames (in the last case you'll need to use -Dsun.java2d.ddscale=true parameter if you're running on windows, or the opengl pipeline with -Dsun.java2d.opengl=true if your hardware/drivers is supported).
    Take a look at this thread on javagaming.org which discusses almost exactly the same case as yours:
    http://www.javagaming.org/forums/index.php?topic=12453.msg100335#msg100335
    Thank you,
    Dmitri
    Java2D Team

    Thank you very much dmitri, the thread you linked showed me just how to make it work. Now I can get 30fps with two videos at once.
    Previously, I was trying to build up a BufferedImage from a 24bit RGB array of pixels, which I don't think is compatible with most hardware acceleration. Now I get a pointer to a 32bit RGBA array, using:
    BufferedImage videoImage;
    GraphicsConfiguration gc = videoCanvas.getGraphicsConfiguration();
    videoImage = gc.createCompatibleImage(vidWidth, vidHeight);     
    pixelData = ((DataBufferInt) videoImage.getRaster().getDataBuffer()).getData();With minor changes to my C code I store the pixels in this buffer instead. This works much better, as the resulting BufferedImage is hardware accelerated. I then can render this BufferedImage straight to the screen, with scaling, very quickly.
    Rendering it first to a VolitileImage was causing problems for me, as performance would slow down for some reason if I changed the window's size at all while it was running.

  • VolatileImage Transparancy

    According to http://java.sun.com/products/java-media/2D/perf_graphics.html:
    Java 2D cannot hardware accelerate images with alpha at this time. Only opaque images or images with 1-bit transparency can be hardware accelerated. Acceleration support for 1-bit transparency enables you to accelerate sprites with transparent pixels.
    My code:
    GraphicsEnvironment env = GraphicsEnvironment.getLocalGraphicsEnvironment();
    GraphicsDevice device = env.getDefaultScreenDevice();
    GraphicsConfiguration gc = device.getDefaultConfigurations();
    System.out.println(gc.getColorModel());
    // output DirectColorModel: rmask=ff0000 gmask=ff00 bmask=ff amask=1000000
    VolatileImage vImg = gc.createCompatibleVolatileImage(d.width, d.height);
    BufferedImage bimg = img.getSnapshot();
    System.out.println(bimg.getColorModel());
    // output DirectColorModel: rmask=ff0000 gmask=ff00 bmask=ff amask=0
    I'm running the program on win2K.. is there anyone actually works thing out to make a transparent volatile image ?

    Good evening. I've been working on transparency and VolatileImages for several hours now, scouring the internet, and I'm really wondering if it needs to be this difficult. Does anyone else think that the documentation is weak in this area? Surely copying transparent images is not an obscure topic.
    What it seems to boil down to is that VolatileImages just don't support transparency, at least not the transparency I'm using from a PNG, which I guess is alpha-channel as opposed to bitmask. I'm not an expert on graphics formats, and I shouldn't have to be to simply copy images about without losing their transparency. Is this a Windows limitation? Are there more advanced 2D libraries in Java that I can use? Maybe I need to jump into JOGL or similar and drop all this insane AWT mess?
    This is the code that works, to create a transparency-enabled buffer where I can paint back buffers or scaled copies of images:
    Image  image = graphicsConfig.createCompatibleImage(width, height, Transparency.TRANSLUCENT);However, in practice this creates a BufferedImage, which will be slower (though not much, at least so far) and worse will quickly exhaust the Java stack. My app needs to use images scaled to various sizes, as the user zooms for example, so I liked using VolatileImages. If I understand it right they more-or-less delete themselves automatically if VRAM runs down, automatically recycling less recently used images without needing special code from me. I just have to check for contentsLost() and rebuild when needed. With BufferedImages I'll need to track the least recently used elements and discard them myself.
    Is there a way I can have it both ways, a VRAM image with transparency? Also, can anyone recommend a good book on OpenGL for Java? Or maybe C#; I hate to support the Yeti from Redmond but in practice it's just so much easier.
    Thanks!
    Hmm, lovely, Sun's forii are not fully compatible with Opera. Or does it always insert formatting codes at the end of the post, regardless of cursor position or selected text?

  • Applet run ..err or not

    i try to run my app with visual age. my applet should take live feed images from my webcam but i get a a black screen with a text message on the left corner video started.... in the console i get this message: what is wrong?
    Using SimpleLogger
    VideoApplet version 1.113 built on 2004/07/09 at 18:51:23 UTC.
    ** LiveWave Video Streamer Initialized **
    Video initializing...
    getBackBuffer for verison: 1.2.2
    using non-volatile Image
    port = 2245
    java.lang.ClassNotFoundException: netscape.javascript.JSObject
         java.lang.Throwable(java.lang.String)
         java.lang.Exception(java.lang.String)
         java.lang.ClassNotFoundException(java.lang.String)
         java.lang.Class java.net.URLClassLoader.findClass(java.lang.String)
         java.lang.Class java.lang.ClassLoader.loadClass(java.lang.String, boolean)
         java.lang.Class sun.misc.Launcher$AppClassLoader.loadClass(java.lang.String, boolean)
         java.lang.Class java.lang.Class.forName0(java.lang.String, boolean, java.lang.ClassLoader)
         java.lang.Class java.lang.Class.forName(java.lang.String)
         com.livewave.applet.JavaScriptSupport(java.applet.Applet)
         void com.livewave.applet.VideoApplet.init()
         void sun.applet.AppletPanel.run()
         void java.lang.Thread.run()
    Video initialized...
    Video starting...
    Video connecting...
    Video connecting...
    MessageManager connect
    MessageManager connecting to localhost/127.0.0.1 2245 TIMES= 1
    java.security.AccessControlException: access denied (java.net.SocketPermission 127.0.0.1:2245 connect,resolve)
         java.lang.Throwable(java.lang.String)
         java.lang.Exception(java.lang.String)
         java.lang.RuntimeException(java.lang.String)
         java.lang.SecurityException(java.lang.String)
         java.security.AccessControlException(java.lang.String, java.security.Permission)
         void java.security.AccessControlContext.checkPermission(java.security.Permission)
         void java.security.AccessController.checkPermission(java.security.Permission)
         void java.lang.SecurityManager.checkPermission(java.security.Permission)
         void java.lang.SecurityManager.checkConnect(java.lang.String, int)
         java.net.Socket(java.net.InetAddress, int, java.net.InetAddress, int, boolean)
         java.net.Socket(java.net.InetAddress, int)
         void com.livewave.net.client.MessageManager.connect()
         boolean com.livewave.net.controller.UnitController._initMessageManager(com.livewave.net.client.MessageManager)
         boolean com.livewave.net.controller.UnitController.initialize(com.livewave.server.control.UnitID, java.lang.String, java.lang.String, java.lang.String, java.net.InetAddress, int, com.livewave.net.controller.UnitController$Notify)
         void com.livewave.applet.VideoApplet.start()
         void sun.applet.AppletPanel.run()
         void java.lang.Thread.run()
    Video started...
    setSize(374,414)
    getBackBuffer for verison: 1.2.2
    using non-volatile Image
    setSize(410,447)
    getBackBuffer for verison: 1.2.2
    using non-volatile Image

    There seems to be two problems:
    java.lang.ClassNotFoundException: netscape.javascript.JSObject
    The class netscape.javascript.JSObject can't be found, and the second error is security related:
    java.security.AccessControlException: access denied (java.net.SocketPermission 127.0.0.1:2245 connect,resolve)
    Your applet isn't allowed to open a socket to your local host. It's only allows to open a socket back to the server which it was loaded from (try using your ip-address instead of 127.0.0.1)
    /Kaj

  • Animation jitter

    The test program below animates black and green rectangles
    moving across the screen. They exhibit a vertical jitter,
    drawing artifacts, along their edges, as they move
    horizontally across the screen. Can someone explain this and
    give any suggestions on how to remove this jitter?
    thank you.
    import java.awt.BorderLayout;
    import java.awt.Color;
    import java.awt.Graphics;
    import java.awt.Graphics2D;
    import java.awt.GraphicsConfiguration;
    import java.awt.image.VolatileImage;
    import javax.swing.JFrame;
    import javax.swing.JPanel;
    public class DebugJitter extends JPanel implements Runnable {
         private static final long serialVersionUID = 1L;
         private VolatileImage buffer;
         private Graphics2D bufferGraphics;
         private int xoff;
         private int yoff;
         private int width;
         private int height;
         public DebugJitter() {
              setBackground(Color.black);
              setDoubleBuffered(true);
         public void paintComponent(Graphics g) {
              GraphicsConfiguration gc = getGraphicsConfiguration();
              int w = getWidth();
              int h = getHeight();
              do {
                   if ((buffer.validate(gc) != VolatileImage.IMAGE_OK) || (width != w)
                             || (height != h)) {
                        width = w;
                        height = h;
                        buffer = createVolatileImage(width, height);
                        bufferGraphics = buffer.createGraphics();
                   bufferGraphics.setColor(Color.black);
                   bufferGraphics.fillRect(0, 0, width, height);
                   bufferGraphics.setColor(Color.green);
                   for (int x = 0; x < width; x += width / 5) {
                        bufferGraphics.fillRect(x, 0, width / 10, height);
              } while (buffer.contentsLost());
              g.drawImage(buffer, xoff, yoff, null);
              if (xoff >= width) {
                   xoff = 0;
              } else {
                   xoff += 10;
         public void addNotify() {
              super.addNotify();
              width = getWidth();
              height = getHeight();
              buffer = createVolatileImage(width, height);
              bufferGraphics = buffer.createGraphics();
          * @param args
         public static void main(String[] args) {
              // TODO Auto-generated method stub
              JFrame jf = new JFrame();
              int w = 1000;
              int h = 1000;
              jf.setSize(w, h);
              jf.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
              DebugJitter dj = new DebugJitter();
              dj.setSize(w, h);
              jf.getContentPane().add(dj, BorderLayout.CENTER);
              jf.setVisible(true);
              new Thread(dj).start();
         public void run() {
              // TODO Auto-generated method stub
              while (true) {
                   repaint();
                   try {
                        Thread.sleep(200);
                   } catch (InterruptedException e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
    }

    I can confirm what morgalr has said. The problem statement is this...
    buffer.validate(gc) != VolatileImage.IMAGE_OKWhen debugging this is always false and so you end up creating a new volatile image every loop. Eventually the gc needs to reclaim all that memory and a jitter occurs. Whats being returned by the buffer.validate(gc) is VolatileImage.IMAGE_RESTORED (which still means the current VolatileImage is perfectly acceptable). You should change that condition of the if statement to this:
    buffer.validate(gc) == VolatileImage.IMAGE_INCOMPATIBLEThis will ensure a new volatile image is created only when necessary. The pause will then disapear as the garbage collector has much less to do. JNI is kind of overkill.

  • Hiding Mouse Cursor

    Is there a way to hide the mouse cursor temporarily then bring it back by maybe.... moving the mouse or typing a key to trigger some event to make mouse visible again.
    This applies to a full screen application where it is prefered not to have the mouse visible at all times.

    Wow, I know this is old, but oh well...
    I'm just starting the design for a game engine in java that will be full screen and have its own gui. So, starting from the ground up, I know I'll have to be able to change the cursor to a neat looking hand or sword or something so I had to see if there was a way to change the cursor. I did a search snd, voila! this was the first page in the list.
    I found the Toolkit.createCustomCursor() method in the api docs and saw that if the image is invalid then you get a blank cursor also. I don't think this will make a difference in the prior situation, but I was thinking about something and, if I can get the answer from someone more experienced before I go spending hours testing it, that would be nice.
    I have two questions, I'd like to ask anyone who does a lot of graphics or game programming...
    One:
    The api says it wont use an animated gif... If I did want an animated cursor, what would be the best way to implement it? For instance, should I start a seperate thread with a loop to change the cursor to the next frame every so many milliseconds, or should I hide the mouse cursor and let my gui display an animated gif where the cursor would be? Or is there maybe a way I can get the graphics context of the cursor and draw directly to it...
    Two:
    If I seriously want to make games like "Rise of Nations" and such which is pretty much what I'm trying for, can I accomplish this in Java? I didn't use to think so, but then I learned about the fullscreen exclusive mode with buffer strategy and volatile images so it gave me hope and I got back into programming. I love java because its so easy. I hate fooling with c++, but I think I've been lazy and I just haven't played with it enough or found the right resources. I have no money so I can't buy MS VIsual C++ or something, and it seems like I have to write my own graphics routines in Assembly, and then my own gui off of those routines and then I just have no idea how to structure programs very well, I always come to a point where I get so far and then realize I've done it all wrong and I basically have to start from scratch... so I'll do that over and over up until the point when I finally get some kind of memory problem that I can't understand which always keeps me from doing anything big. I guess I should learn more about memory, but I thought java kind of shielded me from all that, but even with java I still get things I can't understand like, why the Sun ONE Studio's runide.exe gets bigger and bigger until it basically freezes up and I have to restart it. When I compile and run the program myself with javac and java, frequent runs don't compound memory usage so I'm assuming its something to do with the IDE.
    Ok... I guess this post just turned into a session of "ramblings of the beginner-intermediate programmer."
    I don't really understand these forum things either so I don't know if this "string" is so old that no one will see what I've written and be able to help me out or what, but if there is anyone out there that would be interested in discussing programming stuff or maybe mentoring me, I think it would be worth it because I'm enthusiastic, I have a big imagination, and I know I'm going to be doing big things in the future and I don't forget people that give me a helping hand, so, here's my e-mail...
    [email protected]

Maybe you are looking for

  • Sound quick launch button doesn't work when i installed windows 8 in my hp pavilion dv3z notebook

    1. Product Name and Number hp pavilion dv3z notebook pc  2. Operating System installed (if applicable)      windows 8   3. Any changes made to your system before the issue occurred      installed windows 8 when i installed windows 8 in my hp pavilion

  • Fireworks Install Error  Exit Code 7

    When attempting to install Fireworks from the WebPremium disk image I get an install error.  Any ideas on how to resolve this? Exit Code: 7 -------------------------------------- Summary -------------------------------------- - 1 fatal error(s), 3 er

  • Rendering problems in PR?

    What can I do to correct a rendering problem I have in PR? The rendering starts normally and then the number of previsualisations and the number of images still to rendre suddenly start increasing infintely. The rendering never ends. Do you know what

  • INOTHING DISPLAY WHEN RUN THE FORM,

    WHEN I WANT TO RUN MY FORM , NOTHING DISPLAY , BUT THE BROWSER OPENS PLEASE HELP THANKS

  • Smart folders versus Rules

    What is the difference between Preferences > Rules and a Smart Mailbox? Will they both work on incoming mail and mail in my Inboxes? Will they work on folder in On My Mac? If I Edit a Smart Mailbox does the mail that originally fit that description g