This discussion is archived
4 Replies Latest reply: Apr 21, 2012 8:17 PM by 851442 RSS

Java Graphics Rapid Redraws

851442 Newbie
Currently Being Moderated
I am doing a full screen JPanel update(Graphics/Graphics2D) every 10 milliseconds, and find that smaller objects
in the draw area clicker every so often.

If I am to move smaller visual items around, I have to redraw (update) the entire region each pixel move.

I have tried freezing the current thread before the call to update(graphics) is called,
and setting a perioding timer on the repeated action I have without looking at threads,
and I find I still have the same problem either way.

How can I prevent the flickering I get?
  • 1. Re: Java Graphics Rapid Redraws
    931373 Explorer
    Currently Being Moderated
    Did you tried double buffering ?

    you can simply create an instance of BufferedImage , create a Graphics2D object from it and do your drawings in it,
    When your drawing finished, repaint your panel and use drawImage to draw your buffered image on your panel.

    inform me if you need sample code,
  • 2. Re: Java Graphics Rapid Redraws
    DarrylBurke Guru Moderator
    Currently Being Moderated
    Moderator action: Moved from Java Programming.
    ---
    It looks like you're trying to tweak old AWT code. Don't override update(Graphics). Swing has a different painting mechanism, and is double buffered by default.

    If you're using getGraphics() of a component, don't.

    It also looks like you're unaware of Swing's single threaded rule.
    If I am to move smaller visual items around, I have to redraw (update) the entire region each pixel move.
    There's an overload of repaint(...) that saves you from that.

    Recommended learning resources:
    http://docs.oracle.com/javase/tutorial/uiswing/painting/index.html
    http://docs.oracle.com/javase/tutorial/uiswing/concurrency/index.html

    db
  • 3. Re: Java Graphics Rapid Redraws
    DarrylBurke Guru Moderator
    Currently Being Moderated
    Fahim wrote:
    inform me if you need sample code,
    Lets not turn the forum into a code factory.

    db
  • 4. Re: Java Graphics Rapid Redraws
    851442 Newbie
    Currently Being Moderated
    Brilliant!! People, the answer is the simple approach.

    The painting method to override is

    protected void paintComponent(Graphics g)

    not public void paint(Graphics g)

    and not to call paint(Graphics g) or update(graphics g)

    but simply repaint();

    What genius! Problems solved, flickers gone!! Thank you all!

Legend

  • Correct Answers - 10 points
  • Helpful Answers - 5 points