3

I have to write a simple Java app which can load pictures, show it in a GUI form, allow the user to apply some transformation, and show the transformed picture. My solution is working fine, but the UI is flickering a bit, because the repaint method called too often (for example when the user scaling the image with a JSlider)

My code looks like this:

public class ImageCanvas extends Canvas
{
    private BufferedImage image;
    // ...

    @Override
    public void paint(Graphics g) 
    {
        Graphics2D g2d = (Graphics2D) g;
        if(image != null)
        {
             // I draw out the image...
        }
    }

    public void setImage(BufferedImage image)
    {
        this.image = image;
        this.repaint();
    }

    public void setRotation(double rotation)
    {
        this.rotation = rotation;
        this.repaint();
    }

    public void setScale(double scaleX, double scaleY) 
    { 
       //set the scaling field, then repaint ....
    }    

    // and so on...
}

And, of course, I have an ImageCanvas control on my main UI, and I simply call the public methods (see for example the "setRotation" method above) which repaint the canvas area. I know it's a simple question, but I don't even find a DoubleBuffered property on the Canvas...

Any help appreciated.

asdfghjkl
  • 91
  • 2
  • 8

3 Answers3

7

Double buffering is built-in for Swing (i.e. JComponent derived) classes.

If you want built-in double-buffering, you should extend JPanel rather than Canvas, and override paintComponent, not paint.

Hovercraft Full Of Eels
  • 283,665
  • 25
  • 256
  • 373
Burleigh Bear
  • 3,274
  • 22
  • 32
1

If you can use JPanel than go for it. Please make sure you are not overriding the JPanel.paint method, override JPanel.paintComponent instead. See this link for details.

GETah
  • 20,922
  • 7
  • 61
  • 103
-1

Usually graphic lags in these applications can be caused by setting a empty variable at the top of the script, then changing its value, then waiting for the repaint to update it. You could try changing the:

    setRotation(double rotation);

so that it rotates the image in that method.

Just a general thing I happen to see while dealing with graphics.

Matt
  • 95
  • 6
  • makes no sense to me, even after reading more than once: nothing "usually lags", there is neither an "empty variable" nor a "script". What's empty, though, is the code snippet. – kleopatra Dec 07 '11 at 09:25
  • Well I'm sorry if you didn't post your whole code. Guess you won't get Full help. – Matt Dec 07 '11 at 16:09