May 12, 2008

More Efficient Way To Double Buffer

Free Web Hosting, No Ads > CONTRIBUTE > Computers > Programming Languages > Java, Java Servlets, Java Script, & JSP

free web hosting

More Efficient Way To Double Buffer

beeseven
For a long time I used a BufferedImage/Graphics(2D) to double buffer my programs but someone recently pointed out something to me that is much more efficient: JFrames can automatically create buffers.

The way that I used to use was like this:
CODE
private BufferedImage image;
private Graphics buffer;
public NameOfJPanel() {
     image = new BufferedImage(WIDTH, HEIGHT, BufferedImage.TYPE_INT_RGB);
     buffer = image.getGraphics();

     ...
}
public void paintComponent(Graphics g) {
     g.drawImage(image, 0, 0, null);
}
private class Time implements ActionListener {
     public void actionPerformed(ActionEvent e) {
          ...

          repaint();
     }
}
It uses the methods paintComponent and repaint and two objects to double buffer the panel. The other way is just about as easy and much faster:
CODE
private static BufferStrategy bs = null;
public static void main(String[] args) {
     JFrame f = new JFrame("Title");
     ...
     while(bs == null) {
          f.createBufferStrategy(2); //number of buffers, 2 is almost always enough
          bs = f.getBufferStrategy();
     }
}
//don't need to do anything in the JPanel constructor
private class Time implements ActionListener {
     public void actionPerformed(ActionEvent e) {
          if(bs == null) //I put this in because you make the panel before the buffer
               return;
          Graphics g = bs.getDrawGraphics();

          ...

          bs.show();
          g.dispose();
     }
}
I made a test program for each type of buffering that had a square bouncing around the screen. After one minute the BufferedImage version was at 379 fps and the BufferStrategy version was at 476 fps. The BufferStrategy also eliminated a weird thing where, when using the BufferedImage, you have to account for the title bar and edges of the frame when you set its size. I've attached both versions of the test (they're in text files because of upload restrictions). At the bottom left the numbers are (top to bottom) number of frames since the program was run, the number of seconds since the program was run, the number of frames per second.

Edit: I didn't realize that you don't actually need a JPanel to do to use this buffer method (though having one doesn't hurt). You can just have the main class extend JFrame and do everything in the constructor:
CODE
public class ClassName extends JFrame {
     public static void main(String[] args) {
          new ClassName();
     }
     public ClassName() {
          //set size, location, defaultcloseoperation, visible

          while(getBufferStrategy() == null)
               createBufferStrategy(2);

          //other stuff like add timer
     }
     private class Time implements ActionListener {
          public void actionPerformed(ActionEvent e) {
               Graphics g = getBufferStrategy().getDrawGraphics();

               //other stuff

               getBufferStrategy().show();
               g.dispose();
          }
     }
}

 

 

 


Reply

peterrogers
Hi, just a quick note to say thanks for your quick explanation and code for bufferStategy. I have added to my app and it is really fast without the hideous flickering that was driving me mad. Appreciate it. Pete R

Reply



Got an Opinion! Express your Views! (no registration):-
Add your Reply/ Opinion/ Views/ Comments/ Suggestion/ Questions/ Queries etc.
Posts with decent grammar & English will be accepted and please refrain from profanities.
For asking a Question, We recommend you to sign-up (for free) so that you can track the topic easily.

Nature of your Post*: Opinion/ Reply/ Comments
Question/Query
Feedback to us.
       
Name   Email
Title/Question*

(Maximum characters: 10,000)
You have characters left.
Confirm Code:

Recent Queries:-
  1. jframe double buffer - 963.35 hr back.
  2. jframe doublebuffer - 1164.45 hr back.
Similar Topics

Keywords : efficient, double, buffer

  1. How To Make A Double-voice Effect
    DVS, I call it. (1)
  2. Conserving Battery Power
    Efficient usage of your laptop battery (3)
    I know this is very much known to many people. I recently stumbled upon this on Vista documentation
    and thought it will be of some use to others... QUOTE Get the most from a single charge If you
    have time to do only one thing... Use the Power saver power plan to minimize power consumption.
    You can always return to this article later to try more power-saving tips. To choose the Power saver
    plan, open Power Options in Control Panel. Ever run out of battery power in the middle of a
    meeting? Has the urgent beep of your mobile PC's battery alarm made you th....
  3. Vista & Linux Double Boot
    (8)
    I am considering installing Ubuntu Linux to run as a double boot on my new laptop. I purchased the
    laptop with Vista Home Premium and I need to keep it for some of my games and software. Ex. Guild
    Wars, Halo, Visual C++ Express. I am just wanting to run Linux to see what it is like and I am
    wondering whether or not I could run Vista and Linux on the same hard drive. I have at least 70GB of
    space left and my C partition contaisn about 103 GB. I just bought the laptop a few days ago. I am
    just wanting to know this because I am thinking of getting Linux and possibly an exte....
  4. Photoshop -- Double Stroke
    Learn to create a neat-o text effect (2)
    Lets do this! 1. Create a new photoshop document with the dimensions 88x31. If your lost
    already... quit. 2.Alright make some random background and then put some random black-colored
    (#000000) text on it. Kind of like the picture below. 3. Select the text layer you have just
    created and click on the little f symbol near the bottom of the layer window. A sub menu should pop
    up. Click on stroke. 4. Some editing window should appear. Change all the values to what you
    see in the following image, make sure the stroke color is white (#FFFFFF). After this tu....
  5. Most Efficient Code To Get Prime Numbers
    (6)
    Can anyone write a more efficient code than this to get the prime numbers from 1 -999? //
    Assignment: sieve.cpp // Purpose: To write the most efficient program // that outputs prime
    numbers. #include #include #include // declare constant MAX_NUMBER to be the # of arrays. const
    MAX_NUMBER = 1000; // declare array primes. bool primes ; // function prototypes void
    initializeArray(); void findMultiples(); void printSubscripts(); int main() { // call to functions
    initializeArray(); findMultiples(); printSubscripts(); return 0; }
    //*****************************....
  6. Double Standard :yes For Kosovo But Not For Kurdestan
    Double Standard (0)
    US , Western countries and UN wanted declare Kosova to be dependent from Serbia. US helped Irak
    Kurdstan to have seperate identity but not the Kurdstan of Turky. Why this double standard. Also
    in past south Sudan parts was strugeling for seperation for 30 years and no body helped and said yes
    they are different culture and identity. When we become fair for all. ....
  7. Religious Double Standards
    They annoy the hell outta me (see what i did thar ;34) (14)
    OK. Religion is a very questionable topic. Because EVERYONE seems to get incredibly offended by it.
    This brings me on to my first topic. Why the hell is everyone so hooked up on religion? I mean. If
    you say something bad to someone. And its about say. Their fashion sense. It's what they think
    look good so they'll be like. I see you disagree but I'm entitled to my own opinion ^.^. You
    are all like ^.^ okay then =D everyones fine. If you say, I think your religion is ridiculous and
    implausible they'll probably report you for racism, maybe cry, possibly neve....
  8. Pump It Up
    Arcade-Style Dance Game - Five Panels (Single) - Ten Panels (Double) (0)
    With an influence from Korean culture as well as the cultures of America and Latin-based countries,
    Pump It Up gives players a new view about music as well as the physical aspect of "dancing" as some
    people will call it. In this game, the player must step on certain colored panels depending on how
    the arrows are positioned on the screen while the arrows will move according to the beat and rhythm
    of the music. The game itself is separated into certain difficulties in order to ensure that many
    people will be able to enjoy the game on different settings. Here's a run d....
  9. Stop Double Post/submit
    (10)
    Hi Whats the best way of stopping a double post from occurring? Re-directs? I was hoping that
    there was another way because I am using smarty and with the current setup of my site implementing
    redirects would be a right pain. Thanks for any help. ....
  10. Double Dropdown
    Disable the second until first is selected (2)
    Allright so heres the deal.. Im trying to make a 3 teir dropdown Sort, Order, User both will be
    populated by a database so dont worry about the content inside of them they will be the same stuff
    in both but in a diffrent order by using php (ajax i guess is what it is since its javascript with
    php lol) CODE <html> <head> <script
    src="selectuser.js"></script> </head> <body> <?php
    $c=mysql_connect ("localhost", "database", "password") or die
    ('I cannot conne....
  11. How To Double Kick Bass Drum
    a video (2)
    Here is a samble for drummer on how to use double kick in one pedal
    http://youtube.com/watch?v=0ITXS9vnX6c http://youtube.com/watch?v=4iwKznwPotQ&...ted&search=
    this is i dont know what his talking about but his got the speed! his really quick and he goes
    from slow to faster than fast i've learn alot with him...now i can kick those pedals....
  12. Double Xp, Then Dual Boot?
    (1)
    i build ther rig in my sig with 2 320gb hdds, both partitioned 30/290 each and loaded xp on my first
    drive,30gb partition, i have an upgrade version of vista homer premium, so i can not just install
    vista on my second drive right? i have to upgrade an exisiting xp os, so can i reload xp on my
    second drive then upgrade it so i keep my first drive and xp untouched and run a dual boot system?....
  13. Php Frameworks - Leaner, More Efficient Coding.
    A quick overview of what they are and where you can find some. (1)
    PHP Frameworks What do you guys think of coding websites using framworks like Zend or CakePHP? I
    used to code my applications from scratch but it does get tedious and because PHP is not as
    structured as other languages it's very easy to create redundant, unmaintainable code. I think
    a framework should be more than just a bunch of libraries. It's true that having libraries for
    functions specific to what you are trying to do might help alot but it takes more than that to
    create some maintainable code. What I' m talking about is MVC and Front Controllers. The....
  14. Double Dating
    Need serious help (6)
    Hi guys, I've been with a girl Ive known since school days, and it's been like 8 years, but
    I also came to know another girl for the past year, and we've been very close to each other, i
    love the girl i've been with for the past 8 years but I also started liking the new girl, i dont
    know what to do, they both love me and they don't know i;m double dating, how can i choose?
    Thanks in advance....
  15. Buffer Overflow In Action Tutorial
    Learn how to buffer overflow programs to change the program flow... (0)
    This tutorial will show you how to buffer overflow programs in order to change the flow of the
    application , even if this means executing your own code. A very well explained tutorial of buffer
    overflows ( not theory but practise ) + a 20 min video tutorial/demonstration + all the files needed
    for the tutorial.. Buffer Overflow In Action Tutorial LINK ....
  16. [forum] Double Posting Happening By An Error
    (3)
    Hello, I am currently working on EvilBoard 0.1.1, for those who know about this project versjon 0.1b
    can be downloaded from http://www.evilservices.com Well over to the reason why i am posting this,
    I am currently experincing a problem with my new posting code wich has been rewrited in version
    0.1.1, You see, it is double posting by an error, i thouht i could fix that myself, but no, so i
    just thought, Trap17 is perfect, they problety know how to fix this, Here is the code: CODE
    <? /* * @Name: Post Topic * @Author: Arne-Christian Blystad * @Copyright&....
  17. What Is... The Double Slit Experiment
    Electrons know when you're watching (6)
    The Double Slit experiment is a famous example of how we don't understand how reality works.
    Here's a brief explination of what the Double Slit experiment is about, based on my
    understanding, largely influenced by What the BLEEP Do We Know? , which does a much better job than
    I ever could at making this clear. ^-^ Anyway, on to the explination. Step 1: Why are there two
    slits? The two slits are used to determine whether an object is travelling as matter or as a wave.
    It's quite simple, really. If you were to fire a lot of small matter - say, paint bal....
  18. Want To Double Your Money Online
    Discussing online investments (1)
    I found a real offline and online business that has an investment opportunity for any person
    interested in making money through them. The deal is, you invest with them and you earn a certain
    percentage return per month for 5 months. Its not autosurf, MLM or HYIP. Its a real business with
    products being sold. Send me a PM for details if you are interested.....
  19. Dialup Users Double Your Connection Speed
    with simple modem command tweek (3)
    I found this instruction on the net and I'm wondering this actually "speeds up" a dial up
    connection? QUOTE Suffering from 52 kbps internet connection? Follow these simple steps and
    double your internet connection speed: Connect to the internet Click Start and select control
    panel Click Phone and Modem Select Modems tab and then click Properties Click the Advanced tab
    and in the extra initialization commands type AT&FX Click Ok and disconnect from the internet
    Connect to the internet again and enjoy your 115 kbps connection! Source http....
  20. Assist Breast Cancer Research
    Click once a day, double points for May 2006 (3)
    Help this worthy cause by going to this site and clicking once per day. Funds generated go towards
    Breast Cancer Research. A worthy cause, indeed.
    http://www.thebreastcancersite.com/cgi-bin...bjects/CTDSites ....
  21. Ftp Double-click Caution
    ...with multiple sites - be careful with the double-clicking (5)
    I just want to put out a little caution for everybody. Be very careful when using most FTP transfer
    programs. If you double-click on any file (either local, or remote) it usually transfers that file
    across to the other side. Be especially careful if you have set up the default to overwrite. I
    found this out when I was doing some admin with a PhpNuke site, and I wanted to view its config.php
    file, but I transferred that file to my local directory (which was a local nuke). At the time, I
    just thought it was strange that the file didn't view or launch.... but, it s....
  22. Double Monitor Question
    ^^ (15)
    Alright, I got 2 monitors currently and I found that my brother left his old graphics card at my
    house. I was wondering if I would be able to run dual monitors with this. I don't know like
    anything about running dual monitors. Do you just need 2 monitors and 2 graphic cards? If thats
    the case, my current graphics card is a 32mb geforce2. My brothers old one I believe is some 16mb
    card. Will these work? or will their be conflicts because I believe they are different brands and
    also have different mb capacity? Also, I'm running windows 2000 pro. Will my os....
  23. [photoshop Cs] Simple Double Layer Tech Border
    (0)
    This tutorial will show you how to make a simple, yet effective double layer tech border for a sig
    in Photoshop CS, (should be similar in earlier versions of PS). This uses some of my shortcuts,
    because I am basically a lazy person and will always look for the easiest way to do something.
    /tongue.gif" style="vertical-align:middle" emoid=":P" border="0" alt="tongue.gif" /> The main one in
    particular is the "Tech Borders" style file, attached here. Download the file now, then extract
    and save the file in to the "Presets > Styles" folder of your Photoshop folder. You wil....
  24. Gigabit Efficiency ?
    How efficient should a gigabit net be? (4)
    How efficient should a decent gigabit net be?? I am missing something, I'm afraid, as I only
    get about 64 mb/sec, or around 6-8% effiency, unless I missed a power of ten somewhere I used the
    PASSMARK network test and got these figures for 2 machines over 30 seconds. I have 2 intel
    pro/mt1000's, through a trendware gigabit switch on a network with only these on it. I have
    offloaded all calculations/checks as possible, and tried jumbo frames. It doesn't seem that
    about 7% efficiency is correct. any ideas what I'm doing wrong, or a better way o....
  25. Double Combo Box Produces Images?
    (1)
    I am trying to do a website which requires two drop down boxes that will display different images.
    Basically you select a category then you can select a sub category from the second drop down box.
    Now all the scripts I found online that do this direct you to a link by either pressing Go or some
    kind of submit button. Can some one point me in the right direction to make the selection show
    different images? In the end I want to have an image show up when you select the sub category, then
    have the user be able to drag and drop that image to a different part of the screen....
  26. What Is Double Jeopardy?
    (5)
    I had no idea what it meant when i watched the film called Double jeopardy. QUOTE DOUBLE
    JEOPARDY - Being tried twice for the same offense; prohibited by the 5th Amendmentto the U.S.
    Constitution. ' he Double Jeopardy Clause protects against three distinct abuses: a second
    prosecution for the same offense after acquittal; a second prosecution for the same offense after
    conviction; and multiple punishments for the same offense.' U.S. v. Halper, 490 U.S. 435, 440
    (1989). Separate punishments in multiple criminal prosecution are constitutionally permissi....
  27. Double Leg Takedown
    wrestling moves (7)
    Hello everyone, this is Jason Bray future MMA champ, today I will describe to you how to perform a
    double leg takedown. (The importance of this move is critical for any grappler/wrestler looking to
    take his/her opponet to the ground to work his submission/ground and pound skills). step 1 (the
    setup) Before you shoot in on your opponet it is extremely important to set your opponent up for the
    takedown. Even if you have great takedowns a nice setup will make life that much easier. Now there
    many different ways to set your opponent up. One of my personal favorite include ....
  28. Yet Another Signature Rotator
    (Easier, and more Efficient) (7)
    Hey Trap, It's Mr. Panda, and I'm introducing a signature rotator script I came across
    several months ago. Unlike most other signature rotators on trap17, this one does DOES NOT
    require the configuration process, and a new signature can be added, simply by uploading it to the
    proper directory. Seeing as this requires so much less configuration, I do hope it will be
    implemented by some of you 'Sig Masters' out there /biggrin.gif' border='0'
    style='vertical-align:middle' alt='biggrin.gif' /> , that have to add another line of code to your
    rotator file....
  29. How To Double Stroke Images
    Using Photoshop (22)
    (I am aware that there is an existing tutorial on double stroking text, but this is very different.)
    How to double stroke images using Photoshop by Strawberrie 1. Open up/copy&paste the
    image you want to double stroke onto a new layer (Shift+Ctrl+N) in Photoshop. 2. Go to Edit >
    Stroke. Set the width to 3 px and color to whatever you wish your furtherest inside border to be (in
    this case, black). You should get something like this: 3. Go to Edit > Stroke again. Set the
    width to 2 px and color to whatever you wish your middle border to be (in thi....
  30. Soldiers Of Fortune Ii-double Helix
    Ever played the game before? (2)
    Been playing the Soldiers of Fortune Double Helix for some time now but I got hooked somewhere.+ if
    you've ever played the game before, what i ann know is how i am to pass the china streets stage.
    i kinda got hooked in there and i dont even know how, where and what to do. thanks for your
    anticipated help.....

    1. Looking for efficient, double, buffer

Searching Video's for efficient, double, buffer
Similar
How To Make
A
Double-voice
Effect -
DVS, I call
it.
Conserving
Battery
Power -
Efficient
usage of
your laptop
battery
Vista &
Linux Double
Boot
Photoshop --
Double
Stroke -
Learn to
create a
neat-o text
effect
Most
Efficient
Code To Get
Prime
Numbers
Double
Standard
:yes For
Kosovo But
Not For
Kurdestan -
Double
Standard
Religious
Double
Standards -
They annoy
the hell
outta me
(see what i
did thar
;34)
Pump It Up -
Arcade-Style
Dance Game -
Five Panels
(Single) -
Ten Panels
(Double)
Stop Double
Post/submit
Double
Dropdown -
Disable the
second until
first is
selected
How To
Double Kick
Bass Drum -
a video
Double Xp,
Then Dual
Boot?
Php
Frameworks -
Leaner, More
Efficient
Coding. - A
quick
overview of
what they
are and
where you
can find
some.
Double
Dating -
Need serious
help
Buffer
Overflow In
Action
Tutorial -
Learn how to
buffer
overflow
programs to
change the
program
flow...
[forum]
Double
Posting
Happening By
An Error
What Is...
The Double
Slit
Experiment -
Electrons
know when
you're
watching
Want To
Double Your
Money Online
- Discussing
online
investments
Dialup Users
Double Your
Connection
Speed - with
simple modem
command
tweek
Assist
Breast
Cancer
Research -
Click once a
day, double
points for
May 2006
Ftp
Double-click
Caution -
...with
multiple
sites - be
careful with
the
double-click
ing
Double
Monitor
Question -
^^
[photoshop
Cs] Simple
Double Layer
Tech Border
Gigabit
Efficiency ?
- How
efficient
should a
gigabit net
be?
Double Combo
Box Produces
Images?
What Is
Double
Jeopardy?
Double Leg
Takedown -
wrestling
moves
Yet Another
Signature
Rotator -
(Easier, and
more
Efficient)
How To
Double
Stroke
Images -
Using
Photoshop
Soldiers Of
Fortune
Ii-double
Helix - Ever
played the
game before?
advertisement



More Efficient Way To Double Buffer



 

 

 

 

ADD REPLY / Got an Opinion! Remove these ADs! RAPID SEARCH! Free Web Hosting [X]
Express your Opinions, Thoughts or Contribute more info. to help others.
Ask your Doubts & Queries to get answers, So that "Together We can help others!"
Register FREE for AD-FREE forum, Create your own topics, Ask Questions, track topics, setup subscriptions & notifications and Get a Free Website w/ Email and FTP.
500MB Space *No Ads*, CPanel, FTP, PHP, MySQL, EMails - 100% FREE