Search code examples
javaimagegraphics

Java - Graphics to image


Well I am a junior java programmer, in the last week I've been facing the following problem: I've got an image and a panel. Both image and panel are inside a ScrollPane, and they both need to move in the same time. When I try moving them together I get a flickering effect. Moving each of them alone though, works fine. I've read about double buffering and decided to implement it. My problem is that my image is very very big, therefore drawing it each time from scratch causes my app to get stuck. So instead I've been thinking of the following solution:

In my paint function, I'd advance the scrollbar of the large image(works fine), draw a new image from my now updated graphics content and draw upon it my panel's content.

Though as much as I looked for it on the web, I couldn't find an explanation of how to do it. So making it short, how do I use my current Graphic object to draw an image from it?


Solution

  • I think you made an override from the paint method somewhere in your code.

    You have to doublebuffer the frame:

    frame.setVisible(true);
    frame.createBufferStrategy(2); // Two is the number of buffers
    // Here is the order important: first set visible, then createStrategy
    

    Then your paint-method in your frame: (Do not override a method)

    public void updateGraphics()
    {
         BufferStrategy bs = getBufferStrategy();
         Graphics g = bs.getDrawGraphics();
         paint(g);
         g.dispose();
         bs.show();
         Toolkit.getDefaultToolkit().sync();
         update(g);
    }
    

    This method you can use in a Thread:

    new Thread("PainterThread")
    {
         public void run()
         {
              while (true)
              {
                   try
                   {
                        updateGraphics();
                        Thread.sleep(10);
                   } catch (Exception e) {}
              }
         }
    }.start();