Double buffering issue

I have a complex modal JDialog with many JTextFields. Before it becomes visible I call setText("") on these fields to reset their values. When the dialog appears for the second time I see for a moment the old values of these fields. There is no such behaviour if I turn off double buffering on JRootPane of this dialog. Is it a bug or by design? It looks very ugly.
JDK 1.6.0.27, Linux 2.6.31

Here is an example. Click 'open', click 'fill values', close the dialog. Repeat until you see the old values in the JTextFields for a blink of an eye. Uncomment XXX to avoid this effect.
public class Test
    private static MyDialog dialog;
    public Test()
    public static void main(String[] args) throws Exception
        SwingUtilities.invokeLater(new Runnable()
            @Override
            public void run()
                final JFrame frame = new JFrame();
                frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
                frame.setLayout(new FlowLayout());
                JButton b = new JButton(new AbstractAction("Open")
                    @Override
                    public void actionPerformed(ActionEvent e)
                        if (dialog == null)
                            dialog = new MyDialog(frame);
                            dialog.pack();
                            dialog.setLocationRelativeTo(frame);
                            dialog.setModal(true);
                        dialog.clear();
                        dialog.setVisible(true);
                frame.add(b);
                frame.pack();
                frame.setLocationRelativeTo(null);
                frame.setVisible(true);
    private static class MyDialog extends JDialog
        private JTextField[] textFields;
        public MyDialog(Frame owner)
            super(owner);
            // XXX
            //getRootPane().setDoubleBuffered(false);
            int n = 20;
            setLayout(new GridLayout(n + 1, 2));
            textFields = new JTextField[n];
            for (int i = 0; i < n; ++i)
                JTextField tf = new JTextField();
                tf.setColumns(10);
                textFields[i] = tf;
                add(new JLabel("Field " + i));
                add(tf);
            JButton b = new JButton(new AbstractAction("Fill values")
                @Override
                public void actionPerformed(ActionEvent e)
                    Random rnd = new Random();
                    for (JTextField tf : textFields)
                        tf.setText(Integer.toString(rnd.nextInt()));
            add(b);
        private void clear()
            for (JTextField tf : textFields)
                tf.setText("");
}

Similar Messages

  • JNI native drawing - Double Buffering issue

    Hi,
    I use JNI to paint from a C++ DLL onto a canvas, which works fine.
    The problem is that double buffering is not working though.
    In C++ I create an offscreen HDC, draw something on it and finally i bitblit the offscreen HDC to the parent window HDC.
    That is how double buffering is supposed to work. But each time i repaint my Canvas in Java, i see flickering:
    the background color is displayed first, then the C++ paintings are drawn.
    Since i already do double buffering in my C++ drawings, i don't know why there still is flickering.
    Should i do double buffering on my canvas also?
    How would this work, since my paint method looks like;
         private native void drawChart(Graphics g);
         public void paint(Graphics g)
              drawChart(g);
         }

    this is my lucky day :)
    the following thread on http://forum.java.sun.com/thread.jspa?threadID=562392&messageID=2767046 suggested to override the update method on the canvas, which works.
         // overridden to eliminate flicker
        public void update(Graphics g)
            paint(g);
        }

  • C# implementation issue with double buffering

    I am using the C# dll library to access the berkeley db, is there any way to pass the buffer, offset, count for the btree cursor move function. I dont want to double buffer to memory every time I conduct a cursor move.

    Sir,
    The call I am assuming you are using on the double buffered example is the DAQ_DB_TRANSFER. The output or return value on this is an integer array of i16's. I'm not very familiar with Borland C++ Builer 4, but I'm thinking the VCL label is just a control that you are trying to send a value to. I'm not sure why this would give you an violation, other than that array of integers not having an data in there, or you are pointing to the data in an element incorrectly.
    Daniel McChane
    Application Engineer
    National Instruments

  • Double Buffering a large image - is it a good idea to do so ?

    I'm developing a small maze like game. I'm using double buffering. So I double buffer the enter screen area (1024x768) and copy them all back to the on screen buffer...
    I need my code to run atleast at 18 - 24 fps.
    Is there a better/efficient way to do this...
    Note : I'm manually double buffer. I don't use any Buffer manager.
    like this
    public void update(Graphics g)
          Image i = createImage(...)      ;
          paint(i.getGraphics() );
          g.drawImage(i..)
    }

    Hi chaos,
    I am developing a game too and I achieve very high frame rate (up to 60 fps) using the hardware accelerated pipelines and the double buffering/page flipping strategy.
    here is the method I call to update my the entire screen of my game:
    private void screenUpdate()
        try
          Graphics gScr = bufferStrategy.getDrawGraphics();
          gameRender(gScr); //this is where I paint the game screen
          gScr.dispose();
          if (!bufferStrategy.contentsLost())
            bufferStrategy.show();
        } catch (Exception e)
          e.printStackTrace();
          running = false;
      }Here is how I create the buffer strategy in the main JFrame:
    try
          EventQueue.invokeAndWait(new Runnable()
            public void run()
              createBufferStrategy(NUM_BUFFERS);
        } catch (Exception e)
          System.out.println("Error while creating buffer strategy");
          System.exit(0);
        bufferStrategy = getBufferStrategy();In my gameRender method, I use only draming method that works without breaking the hardware acceleration (by default enabled with java 6.0). I just make sure to use BufferedImage without rotation or manually written filters and the game runs at 60 fps without any issue.
    The CPU is even still sleeping more than 70% of the time which gives a lot room for all other processing such as path finders, A.I., ...
    Cheers.
    Vince.

  • Still Getting Buffering Issues and Slow Web Page L...

    Since I suspect this issue hasn't gone away - and I/we have been asked to post issues individually rather than clumping into a single tread.
    I just got back from Spain and after quizzing family it seems we are still getting Stream Buffering Issues (again)  (requires a refresh restart << I suspect lost packets rather than speed decrease) and webpages sometimes don't load correctly and require a refresh to load all page elements.
    Just before I left there was an Openreach engineer working on the CAB and my noise margin doubled (but given my distance from the CAB and no speed issues I think the higher margin is a bonus not a negative << so hard to get uncontradictary posts or guidance on the web about Noise Margins - speeds still ok atm according to BTW but havent been back long enough to monitor thru the day/night.
    I can only assume there are still backhaul issues ongoing.
    I notice other ISP forums eg Plusnet noting capacity contention issues but BT remains Silent.
    It's such a shame BT aren't more forthcoming to their customers and I feel really cheated/mis-sold by the whole Infinity 2 product 'never have to buffer again' - advertising hype. This has been a problem here since mid December - so we're talking a month worth of connection issues.
    Since someone will probably ask me for HH stats - here you go - apologies to all those more than 20m from the CAB who are struggling on much slower speeds (I feel for you honest) and in terms of the available speeds etc feel this HAS TO BE a BTW backhaul issue - be it from exchange or in the core.
    I'm all open to comment/solutions
    1. Product name: BT Home Hub
    2. Serial number: +068343+NQ41735167
    3. Firmware version: Software version 4.7.5.1.83.8.173.1.6 (Type A) Last updated Unknown
    4. Board version: BT Hub 5A
    5. VDSL uptime: 6 days, 15:45:33
    6. Data rate: 19999 / 79995
    7. Maximum data rate: 29234 / 106435
    8. Noise margin: 15.2 / 13.0
    9. Line attenuation: 0.0 / 4.7
    10. Signal attenuation: 0.0 / 4.7
    11. Data sent/received: 6.2 GB / 9.9 GB
    12. Broadband username: [email protected]
    13. BT Wi-fi: Yes

    Short answer Ray - nope I only use WiFi on the phone.
    Well for the benefit of others as much as myself I am still having issues and gave up on an iPlayer (live stream) due several bursts of buffering again tonight which made me miss the bits I was really interested in.
    So...
    Eliminating anything in the home the following tests are done directly into the HH5s Gb port. I normally use a switch in this port to seperate my PC's from iThings and anything else on WiFi  (the kids)(BTFon/X) - never had any issues with my switch tho and it will push pull files to/from my NAS or transfer files around my three PCs at full speed << so no concerns there, but NOT used in these tests.
    All wired with industry Grade CAT6 << even ran a checker tool on it and no probs << yip I have such things available.
    Following Stats are after a complete shut down :
    PC Restarted without Firewall or any AntiVirus - no other network connections active and HH5 WiFi Dissabled. HH5 Power Off and Factory Reset (I've tried previously as suggested by other posters using the Openreach modem but since it didnt solve anything just went back to the HH5 to save a power socket and my HH5 can stay up for 13 or so days without issues so I don't suffer in disconnection issues dept). Ok i could buy another router but I doubt its the problem and im just **bleep** away cash for what would then be a replacement for 'not fit for purpose' supplied equipment.
    Quiet Line test = clear << tested master socket with wired phone.
    My Cabinet :
    BTWholesale Speed Test :
    Interestingly i'm getting way lower UPLOAD than the minimum even on an impaired line (I'm only about 20m from the cabinet as the cable runs - less if I want to kick it) << this does seem to fluctate a lot.
    TBB Speedtest :
    I'm open to suggestions but have just about had enuff...
    I still maintain this is a congeston issue but that BT are in total denial to customers about what traffic shaping occurs to maintain the QoS for their YouView and BTSports Customers at the expense of other data under 'abnormal conditions' like lack of capacity.
    So unless a MOD wants to jump in and resolve this quickly, I have several letters ready to go to various parts of BT - Customer Complaints/Sales(for misleading claims)/and Legal Dept. Just need the stamps + a cc copy to Ofcom. This is the last phase of having done ALL I CAN BE REASONABLY EXPECTED TO DO through the BTs compaints proceedures. so that I can send a breach of contract notification to escape this madness.
    Yours xx, a very dissatisfied customer.

  • How to draw a point without double buffering?

    Hello all,
    I am drawing points as small red circles, but they are a bit ugly without double buffering. Am I able to draw the points to be nice? I mean not to draw them as just circles, but some special circle with light border that will looks much more nicer?
    Or what radius and position of the circle must be to be a nice small circle containing only 5 pixels? (upper, lower, right, left, middle)
    ps - they are ugly in the way of having a strange dot on the left side

    I use this method:
        private static final float POINT_RADIUS = 2f;
        private static final float POINT_DIAMETER = POINT_RADIUS * 2;
    private void drawPoint(float x, float y, Color c) {
            Ellipse2D point = new Ellipse2D.Float(x - POINT_RADIUS, -y
                    - POINT_RADIUS, POINT_DIAMETER, POINT_DIAMETER);
            graphics.setStroke(new BasicStroke(0.2f));
            graphics.fill(point);
    // and points looks like this:
       ***

  • Apple TV (2nd gen) - Very Specific Buffering Issue

    I have been watching the threads regularly for a situation similar to mine but I can't see one so I am starting a new one.
    I have Four (4) Apple TVs in the house and a large library of movies, TV shows and personal movies loaded into iTunes on a Window 7 64 bit system with an Intel i7 processor, 12 GB of memory and 2TB of disk space.  Everything seemed to work OK until I got the third Apple TV but that was a year ago and several software upgrades in the past.
    My problem is that when all four (4) Apple TVs are plugged into power, even if the ones I am not using are asleep, I have horrible buffering delays when watching vidoes from iTunes on the Windows PC. I do not have any trouble streaming video from Netflix or the iTunes store directly. When the Apple TV stops to fill buffers it seems to lock up trying and never comes back (I have waited up to 30 minutes). However, if I exit out of the movie as soon as the buffering issue starts, and go back into the video where I left off - it starts playing again within 3 seconds and will carry on for another random period of time in the range of 2 minutes to 10 minutes.
    Before anyone starts responding with the basic stock suggestions, I am a retired IT guy who has put a lot of time and technical effort into trying to find the root cause of this problem. I am very familiar with networking, Windows 7, firewalls, etc.
    The work around is that when I want to watch videos from iTunes on my Windows PC I have to unplug the other three Apple TVs, restart my router and reboot my Windows PC. These three steps together work consistently but omitting any one step may or may not improve the situation. This means that I can't just decide to watch a video from iTunes without 10 minutes of advance prep work - and watching two different videos on two different Apple TVs at the same time only works about 30% of the time.
    Here is some more background information:
    I have two (2) iPhones, one (1) iPad, another Windows 7 64 bit PC, a MacBook Air, and stand alone Internet radio on my network. The problem persists even when all the other devices have been powered off.
    All devices, including the Apple TVs, are running the most current version of software and have ALL patches installed.
    I have upgraded my router (twice) and now have an ASUS RT-N56U dual band router with the Windows PCs both cable connected and the Apple TVs and all the other stuff running wireless.
    I have used netstumbler to detect other networks and have tried various different channels on the router. I am in a low density area and only see two other neighbours with wireless networks.
    I have a 20 MB Internet service connection via cable modem and have no problems watching videos on the Apple TVs from the Internet
    I have relocated the router away from any other elecrical equipment (Apple TVs all show a full strength signal)
    I have tried disabling my MacAfee Security Center virus and personal firewall software (the problem persists), then removing it entirely (the problem persists), then reinstalling only the virus protection component and enabling Windows Firewall (the problem persists).
    I have removed all software from the Windows computer that brand name commercial software - I use Microsoft Office 2010 and Google Chrome as my browser (the problem persists).
    Important - I have moved the complete iTunes library to a 2TB USB hard drive and run iTunes on my MacBook Air with the Windows PCs turned off (the problem persists).
    There is one issue that seems relevant, but might just be a bug in the router management interface. I have set up reserved DHCP addresses for the Apple TVs and the computers to make it easier to identify devices when I am troubleshooting. The DHCP log shows the correct IP addresses being assigned to the correct MAC addresses but the network map screen frequently displays two or more Apple TVs with duplicate MAC addresses. It only happens with the Apple TVs and has never happened with anything else. This is what gave me the idea to turn off all Apple TVs except the one I want to watch and reset the router to clear the other addresses - which seems to be the only consistent way to watch an iTunes video without buffering problems.
    Any ideas would be greatly appreciated. I have invested a lot of time and money in Apple technologies and setting up this home video strategy.  It's very frustrating that it doesn't work reliably.
    Thanks
    Bob T

    I too am having this issue were two of my Apple TVs are showing duplicate MAC Addresses. I have varrified this by looking at the arp -a cache on multiple machines. I believe this is a major bug in the Apple TV software. Can we please get a fix.

  • Problem with Double Buffering and Swing

    Hi
    I made a game and basically it works pretty well, my only problem is it flickers really badly right now. I read up on a whole lot of forums about double buffering and none of those methods seemed to work. Then I noticed that Swing has double buffering built in so I tried that but then I get compilation errors and I'm really not sure why. My original code was a console application and worked perfectly, then I ported it into a JApplet and it still works but it flickers and thats what I'm tryign to fix now.
    The code below is in my main class under the constructor.
    Heres the double buffering code I'm trying to use, I'm sure you all seen it before lol
    public void update(Graphics g)
              // initialize buffer
              if (dbImage == null)
                   dbImage = createImage(this.getSize().width, this.getSize().height);
                   dbg = dbImage.getGraphics();
              // clear screen in background
              dbg.setColor(getBackground());
              dbg.fillRect(0, 0, this.getSize().width, this.getSize().height);
              // draw elements in background
              dbg.setColor(getForeground());
              paint(dbg);
              // draw image on the screen
              g.drawImage(dbImage, 0, 0, this);
         }My paint is right under neath and heres how it looks
    This snipet of code works but when I change the method to
    public paintComponent(Graphics g){
    super.paintComponent(g)...
    everythign stops working and get a compilation error and says that it can't find paintComponent in javax.swing.JFrame.
    public void paint(Graphics g)
              super.paint(g);
              //if game starting display menue
              if (show_menue)
                   //to restart lives if player dies
                   lives = 3;
                   menue.draw_menue(g);
                   menue_ufo1.draw_shape(g);
                   menue_ufo2.shape_color = Color.DARK_GRAY;
                   menue_ufo2.draw_shape(g);
                   menue_ufo3.shape_color = Color.BLUE;
                   menue_ufo3.draw_shape(g);
                   menue_ufo4.shape_color = new Color(82, 157, 22);
                   menue_ufo4.draw_shape(g);
                   menue_ufo5.draw_shape(g);
                   menue_ufo6.shape_color = new Color(130, 3, 3); ;
                   menue_ufo6.draw_shape(g);
                   menue_turret.draw_ship(g);
                   menue_ammo.draw_ammo(g);
              else
                   //otherwise redraw game objects
                   gunner.draw_ship(g);
                   y_ammo.draw_ammo(g);
                   grass.draw_bar(g);
                   o_ufo.draw_shape(g);
                   b_ufo.draw_shape(g);
                   m_ufo.draw_shape(g);
                   s_ufo.draw_shape(g);
                   z_ufo.draw_shape(g);
                   xx_ufo.draw_shape(g);
                   info.draw_bar(g);
                   live_painter.draw_lives(g, lives);
                   score_painter.draw_score(g, score);
                   level_display.draw_level(g, level);
                   explosion.draw_boom(g);
         }I just want to get rid of the flickering for now so any help will be greatly appreciated. Depending which will be simpler I can either try to double buffer this program or port it all to swing but I'm not sure which elements are effected by AWT and which by Swing. Also I read some of the Java documentation but couldn't really understand how to implement it to fix my program.
    Thanks in advance
    Sebastian

    This is a simple animation example quickly thrown together. I have two classes, an animation panel which is a JPanel subclass that overrides paintComponent and draws the animation, and a JApplet subclass that simply holds the animation panel in the applet's contentpane:
    SimpleAnimationPanel.java
    import java.awt.Dimension;
    import java.awt.Graphics;
    import java.awt.Point;
    import java.awt.event.ActionEvent;
    import java.awt.event.ActionListener;
    import java.awt.image.BufferedImage;
    import java.io.IOException;
    import java.net.MalformedURLException;
    import java.net.URL;
    import javax.imageio.ImageIO;
    import javax.swing.JPanel;
    import javax.swing.Timer;
    class SimpleAnimationPanel extends JPanel
        private static final int DELAY = 20;
        public static final int X_TRANSLATION = 2;
        public static final int Y_TRANSLATION = 2;
        private Point point = new Point(5, 32);
        private BufferedImage duke = null;
        private Timer timer = new Timer(DELAY, new TimerAction());
        public SimpleAnimationPanel()
            try
                // borrow an image from sun.com
                duke = ImageIO.read(new URL(
                        "http://java.sun.com/products/plugin/images/duke.wave.med.gif"));
            catch (MalformedURLException e)
                e.printStackTrace();
            catch (IOException e)
                e.printStackTrace();
            setPreferredSize(new Dimension(600, 400));
            timer.start();
        // do our drawing here in the paintComponent override
        @Override
        protected void paintComponent(Graphics g)
            super.paintComponent(g);
            if (duke != null)
                g.drawImage(duke, point.x, point.y, this);
        private class TimerAction implements ActionListener
            @Override
            public void actionPerformed(ActionEvent e)
                int x = point.x;
                int y = point.y;
                Dimension size = SimpleAnimationPanel.this.getSize();
                if (x > size.width)
                    x = 0;
                else
                    x += X_TRANSLATION;
                if (y > size.height)
                    y = 0;
                else
                    y += Y_TRANSLATION;
                point.setLocation(new Point(x, y)); // update the point
                SimpleAnimationPanel.this.repaint();
    }AnimationApplet.java
    import java.lang.reflect.InvocationTargetException;
    import javax.swing.JApplet;
    import javax.swing.JPanel;
    import javax.swing.SwingUtilities;
    public class AnimationApplet extends JApplet
        public void init()
            try
                SwingUtilities.invokeAndWait(new Runnable()
                    public void run()
                        // construct the panel
                        JPanel simpleAnimation = new SimpleAnimationPanel();
                        // put it in the contentPane of the JApplet
                        getContentPane().add(simpleAnimation);
                        setSize(simpleAnimation.getPreferredSize());
            catch (InterruptedException e)
                e.printStackTrace();
            catch (InvocationTargetException e)
                e.printStackTrace();
    }Here's a 3rd bonus class that shows how to put the JPanel into a stand-alone program, a JFrame. It's very similar to doing it in the JApplet:
    AnimationFrame.java
    import javax.swing.JFrame;
    public class AnimationFrame
        private static void createAndShowUI()
            JFrame frame = new JFrame("SimpleAnimationPanel");
            frame.getContentPane().add(new SimpleAnimationPanel());
            frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            frame.pack();
            frame.setLocationRelativeTo(null);
            frame.setVisible(true);
        public static void main(String[] args)
            java.awt.EventQueue.invokeLater(new Runnable()
                public void run()
                    createAndShowUI();
    }Edited by: Encephalopathic on Mar 15, 2008 11:01 PM

  • Apple TV buffering issues with iPhone 4s and iPad 2

    Hi all,
    I just got me an Apple TV 2nd gen (yeah, I know, ordered 2 days before the presentation of the new one). So far so good, the device is up and running, connects just fine to my Airport Express router and all.
    However, if I try to stream a video from my iPad (2) or my iPhone (4S), the results are quite horriffic. The iPad videos would buffer for a very long time before they start and then quite fast after that the buffering problems restart. It's pretty impossible to play a video fluently of more than 20 seconds. If I'd try from my iPhone it's even worse with videos being 1080p, the thing just never plays, eventually the preloading process stops on the mirroring mode is cut.
    I have to point out, all my devices are in the same room (WiFi) so the signal is the best it can be.
    This is honestly quite surprising AND disappointing to be honest, given I bought the device mostly for that, so I can stream videos from my phone and pad.
    Tell me, am I doing something wrong, or the video streaming over those devices is just a marketing gimmick with nothing real behind it?
    Would it matter if I change my router from Airport express to Airport extreme?
    Thanks!

    I have the same issue with ATV3 and iPhone 4S. Everything works properly, no buffering issues when watching netflix, vimeo, youtube BUT when I try mirroring even a small 15sec iPhone movie it stutters and buffers and results to a choppy playback..same with larger mp4 files such as 1-1.5GB, buffers forever and never plays, I just re-encoded the same movie to 700MB and plays perfectly..
    Why Apple, why?..so close..I can accept the bigger movie files issue, but not being able to playback properly an iPhone movie is funny..I recorded a movie with lower bitrate through Filmic Pro (Economy mode, up to 16Mbps)
    and plays properly.
    Is there an upcoming software update going to solve the problem or is it hardware related and therefore not fixable.
    Please don't reply with a network related answer, by 2012 we know how to set up our networks and everything else runs flawlessly.
    I'll apreciate a fast answer, we love Apple, but if it can't play an iphone movie (or a high quality movie from iTunes) it's just not up to my standards.
    Thanks again.
    JP

  • Can anyone help with Double Command issues. This a specific keyboard question and they do not seem to know.

    Before I go into a lengthy explanation of the problem: Can anyone help with Double Command issues. This a specific keyboard question and they do not seem to know.
    Thanks much.
    Emile

    Choose Force Quit from the Apple menu and close Mail from there.
    (103661)

  • Alternative to Double-Buffered Canvas

    I am working on a program in which I use a double-buffered Canvas inside a JScrollPane. The problem is that the Canvas draws over the scrollbars. I have tried extending JComponent, JPanel, JApplet, and Component instead of Canvas, and none of them are double buffered. Here is the code I used to debug this problem:
    import java.awt.*;
    import java.awt.geom.*;
    import java.awt.image.*;
    import javax.swing.*;
    public class Test implements  Runnable
         JFrame f;
         JScrollPane scroller;
         JPanel panel;
         TestCanvas canvas;
         Thread runner;
         BufferStrategy strategy;
         public static void main (String[] args) {
              Test app = new Test();
              app.init();
         public void init() {
              f = new JFrame();
              f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
              panel = new JPanel();
              canvas = new TestCanvas();
              panel.add(canvas);
              scroller = new JScrollPane(panel);
              scroller.setWheelScrollingEnabled(true);
              f.getContentPane().add(scroller);
              f.pack();
              f.setSize(300,300);
              f.setVisible(true);
              canvas.createBufferStrategy(2);
              strategy = canvas.getBufferStrategy();
              runner = new Thread(this);
              runner.run();
         public void run() {
              int x = 0;
              while(x != 65536) {
                   Graphics2D g = (Graphics2D)strategy.getDrawGraphics().create();
                   g.setColor(new Color(x%256,0,0));
                   g.fill(new Ellipse2D.Double(0,0,600,600));
                   strategy.show();
                   x++;
    }Any suggestions?

    The main culprit is that you are mixing AWT components with Swing ones.
    In addition, your are doing so many of useless things and wrong things in your code.
    Swing components are defaulted for using double-buffering.
    See: http://java.sun.com/products/jfc/tsc/articles/painting/index.html
    Try and study this code.
    import java.awt.*;
    import java.awt.event.*;
    import java.awt.geom.*;
    import java.awt.image.*;
    import javax.swing.*;
    public class Fox1229{
      JFrame f;
      JScrollPane scroller;
      TestCanvas canvas;
      int x;
      Timer t;
      public static void main (String[] args) {
        Fox1229 app = new Fox1229();
        app.init();
      public void init() {
        x = 0;
        f = new JFrame();
        f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        canvas = new TestCanvas();
        scroller = new JScrollPane(canvas);
        scroller.setWheelScrollingEnabled(true);
        f.getContentPane().add(scroller, BorderLayout.CENTER);
        f.setSize(300, 300);
        f.setVisible(true);
        t = new Timer(50, new ActionListener(){
          public void actionPerformed(ActionEvent e){
            canvas.setOc(new Color(x % 256, 0, 0));
            canvas.repaint();
            if (++x == 1024){
              t.stop();
        t.start();
    class TestCanvas extends JPanel{
      Color oc;
      public TestCanvas (){
        oc = new Color(0, 0, 0);
      public void setOc(Color c){
        oc = c;
      public Dimension getPreferredSize(){
        return new Dimension(600, 600);
      public void paintComponent(Graphics g){
        super.paintComponent(g);
        Graphics2D g2d = (Graphics2D)g;
        g2d.setColor(Color.blue);
        g2d.fill(new Rectangle(0, 0, 600, 600));
        g2d.setColor(oc);
        g2d.fill(new Ellipse2D.Double(0, 0, 600, 600));
    }

  • Using 6533 DIO32HS, is it possible to use double buffered output with varying pauses?

    I'm using Level-Ack handshaking to transmit data. Currently, I'm hooked up to a loop-back on the DIO32HS card.
    If I don't use double-buffering, I end up with pauses in data transmission, so I need to use double buffering. Unfortunately, I can't seem to set up a delay in the middle of a double buffered scheme.
    What I need to do is this:
    Transmit 64 packets of data (16 bits each) on group 2 / Receive 64 packets of data (16 bits each) on group 1
    Delay for .2 ms
    Transmit the same packets again / receive
    The delay in the middle will need to be varied, from .2 to 20 ms.
    I'm programming in Visual C++ 6.0 under Windows 2000, with (as suggested above) group1 c
    onfigured as input (DIOA and DIOB) and group2 set up as output (DIOC and DIOD). Due to the speed of transmission (256kHz) and the small size of the data set, the program I wrote, no matter how tight I try to make it, cannot insert the proper delay and start the next send on time.
    Does anyone have any idea if such a pause is possible? Anyone know how to do it, or any suggestions on what to try?
    Thanks!

    .2 ms is a very small time delay to use in software. Windows usually isn't more accurate than about 10 or 20 ms. If you need to have small, precise delays you could either use a real time OS, like pharlap and LabVIEW RT, or use extra hardware to generate the delays correctly.
    I would recommend using a separate MIO or counter/timer board (like a 660x) to generate timing pulses for the DIO32HS. This gives you precise timing control at high speed. If the 32HS is in Level ACK Mode, it will respond to external ACK and REQ signals. This is covered in more detail on page 5-10 of the PCI-DIO32HS User Manual.

  • Double buffering

    I was searching through posts to find an answer to my problem of getting double buffering working without flickering when I came across this response:
    Upgrade your SDK, early 1.4 implementations had this problem on Windows2k (It's a bug). Pretty much the second buffer will point to an empty portion of video memory always, the solution to this without updating is to fill the entire backbuffer completely, flip it, fill it again, and then flip it again. You should then be able to use it normaly.
    -Jason Thomas.
    Since I am on dialup I can't really download the SDK, so could someone give me some code to do what Jason has suggested?
    Jonathan O'Brien

    No I am not recreating the bufferstrategy every frame. Overriding update didn't work either. Here is my code for main:
              GraphicsEnvironment env = GraphicsEnvironment.getLocalGraphicsEnvironment();
              GraphicsDevice device = env.getDefaultScreenDevice();
              GraphicsConfiguration gc = device.getDefaultConfiguration();
              Frame myFrame = new Frame(gc);
    BufferCapabilities bufferCaps = gc.getBufferCapabilities();
              boolean multiBuffer = bufferCaps.isMultiBufferAvailable();
              boolean fullScreen = device.isFullScreenSupported();
              System.out.println("Full screen supported = " + fullScreen);
              System.out.println("Multi buffer available = " + multiBuffer);
              System.out.println("Page flipping = " + bufferCaps.isPageFlipping());
              myFrame.setUndecorated(true);
              myFrame.setIgnoreRepaint(true);
              if ((fullScreen) && (multiBuffer))
                   device.setFullScreenWindow(myFrame);
                   device.setDisplayMode(new DisplayMode(800, 600, 16, 0));
                   rectBounds = myFrame.getBounds();
                   myFrame.createBufferStrategy(2);
                   bufferStrategy = myFrame.getBufferStrategy();
                   bufferReady = true;
              Game thisGame = new Game(args[0]);
              myFrame.add(thisGame);
    //          myFrame.getContentPane().add(thisGame);
              myFrame.show();
    And here is the relevant code for my run method:
              if (bufferReady)
                   Graphics g = bufferStrategy.getDrawGraphics();
                   if (!bufferStrategy.contentsLost()) {
                        g.fillRect(0,0,getWidth(),getHeight());
                        g.dispose();
                        bufferStrategy.show();

  • Double buffering still gives flickering graphics.

    I copied code from a tutorail which is supposed to illustrate double buffering.
    After I run it, it still flickers though.
    I use applet viewer, which is part of netbeans to run my applet.
    Link to tutorial: http://www.javacooperation.gmxhome.de/TutorialStartEng.html
    My questions are:
    Is the strategy used for double buffering correct?
    Why does it flicker?
    Why does the program change the priority a couple of times?
    Can you make fast games in JApplets or is there a better way to make games? (I think C++ is too hard)
    Here is the code:
    package ballspel;
    import java.awt.Color;
    import java.awt.Graphics;
    import java.awt.Image;
    import javax.swing.JApplet;
    //import java.applet.*;
    * @author Somelauw
    public class BallApplet extends /*Applet*/ JApplet implements Runnable {
    private Image dbImage;
    private Graphics dbg;
    private int radius = 20;
    private int xPos = 10;
    private int yPos = 100;
    * Initialization method that will be called after the applet is loaded
    * into the browser.
    @Override
    public void init() {
    //System.out.println(this.isDoubleBuffered()); //returns false
    // Isn't there a builtin way to force double buffering?
    // TODO start asynchronous download of heavy resources
    @Override
    public void start() {
    Thread th = new Thread(this);
    th.start();
    public void run() {
    Thread.currentThread().setPriority(Thread.MIN_PRIORITY);
    while (true) {
    xPos++;
    repaint();
    try {
    Thread.sleep(20);
    } catch (InterruptedException ex) {
    ex.printStackTrace();
    Thread.currentThread().setPriority(Thread.MAX_PRIORITY);
    @Override
    public void paint(Graphics g) {
    super.paint(g);
    //g.clear();//, yPos, WIDTH, WIDTH)
    g.setColor(Color.red);
    g.fillOval(xPos - radius, yPos - radius, 2 * radius, 2 * radius);
    @Override
    public void update(Graphics g) {
    super.update(g);
    // initialize buffer
    if (dbImage == null) {
    dbImage = createImage(this.getSize().width, this.getSize().height);
    dbg = dbImage.getGraphics();
    // clear screen in background
    dbg.setColor(getBackground());
    dbg.fillRect(0, 0, this.getSize().width, this.getSize().height);
    // draw elements in background
    dbg.setColor(getForeground());
    paint(dbg);
    // draw image on the screen
    g.drawImage(dbImage, 0, 0, this);
    // TODO overwrite start(), stop() and destroy() methods
    }

    Somelauw wrote:
    I copied code from a tutorail which is supposed to illustrate double buffering.
    After I run it, it still flickers though.
    I use applet viewer, which is part of netbeans.. AppletViewer is part of the JDK, not NetBeans.
    ..to run my applet.
    Link to tutorial: http://www.javacooperation.gmxhome.de/TutorialStartEng.html
    Did you specifically mean the code mentioned on this page?
    [http://www.javacooperation.gmxhome.de/BildschirmflackernEng.html]
    Don't expect people to go hunting around the site, looking for the code you happen to be referring to.
    As an aside, please use the code tags when posting code, code snippets, XML/HTML or input/output. The code tags help retain the formatting and indentation of the sample. To use the code tags, select the sample and click the CODE button.
    Here is the code you posted, as it appears in code tags.
    package ballspel;
    import java.awt.Color;
    import java.awt.Graphics;
    import java.awt.Image;
    import javax.swing.JApplet;
    //import java.applet.*;
    * @author Somelauw
    public class BallApplet extends /*Applet*/ JApplet implements Runnable {
        private Image dbImage;
        private Graphics dbg;
        private int radius = 20;
        private int xPos = 10;
        private int yPos = 100;
         * Initialization method that will be called after the applet is loaded
         * into the browser.
        @Override
        public void init() {
            //System.out.println(this.isDoubleBuffered()); //returns false
            // Isn't there a builtin way to force double buffering?
            // TODO start asynchronous download of heavy resources
        @Override
        public void start() {
            Thread th = new Thread(this);
            th.start();
        public void run() {
            Thread.currentThread().setPriority(Thread.MIN_PRIORITY);
            while (true) {
                xPos++;
                repaint();
                try {
                    Thread.sleep(20);
                } catch (InterruptedException ex) {
                    ex.printStackTrace();
                Thread.currentThread().setPriority(Thread.MAX_PRIORITY);
        @Override
        public void paint(Graphics g) {
            super.paint(g);
            //g.clear();//, yPos, WIDTH, WIDTH)
            g.setColor(Color.red);
            g.fillOval(xPos - radius, yPos - radius, 2 * radius, 2 * radius);
        @Override
        public void update(Graphics g) {
            super.update(g);
            // initialize buffer
            if (dbImage == null) {
                dbImage = createImage(this.getSize().width, this.getSize().height);
                dbg = dbImage.getGraphics();
            // clear screen in background
            dbg.setColor(getBackground());
            dbg.fillRect(0, 0, this.getSize().width, this.getSize().height);
            // draw elements in background
            dbg.setColor(getForeground());
            paint(dbg);
            // draw image on the screen
            g.drawImage(dbImage, 0, 0, this);
        // TODO overwrite start(), stop() and destroy() methods
    }Edit 1:
    - For animation code, it would be typical to use a javax.swing.Timer for triggering updates, rather than implementing Runnable (etc.)
    - Attempting to set the thread priority will throw a SecurityException, though oddly it occurs when attempting to set the Thread priority to maximum, whereas the earlier call to set the Thread priority to minimum passed without comment (exception).
    - The paint() method of that applet is not double buffered.
    - It is generally advisable to override paintComponent(Graphics) in a JPanel that is added to the top-level applet (or JFrame, or JWindow, or JDialog..) rather than the paint(Graphics) method of the top-level container itself.
    Edited by: AndrewThompson64 on Jan 22, 2010 12:47 PM

  • Double buffering && repaint

    Hi there,
    I have a frame F that contains two panels P1 and P2.
    P1 uses double buffering for drawing circles and lines.
    P2 has buttons and a JList.
    When i click on a JList to have popup menu
    or when i move the frame F on the screen
    the panel P2 lost some of JList drawing.
    Actually i iconify the frame in order to oblige
    JVM to do repaint.
    How can i resolve this problem please.

    Do not ever mix heavyweight and lightweight, or else
    you won't be able to set up the correct zorder.But when i iconfiy and desiconify my frame Java
    repaint correctly.
    I need a nice tip article of how to simulate
    desiconify repainting process.
    Thabk u

Maybe you are looking for

  • New DVR and FiOS remote tablet access

    I had to get a replacement DVR recently (bad hard drive). All works well except I can't access the DVR details or program the box through the fios remote app on my tablet. It worked fine for the old box. Also, on the app, the old box still shows up.

  • Line Item Display Variant MIRO-column position needs to be changed..

    Hi, What is the possible way of setting the column position in line item display variant in MIRO screen. I need to change the positions of couple of columns so need to have  one layout as per my requirement. Does this involve only confiuration or it

  • Discover is showing UMRs when using getaddrinfo/getnameinfo

    Hi, I started playing with the discover (Studio 12.4, Solaris 11.2, x86) tool to check my apps for memory errors etc. I noticed that I get UMR warnings/errors when using the getaddrinfo()/getnameinfo() socket functions. Why? me@solaris11_2_x86:/tmp $

  • Cannot find the new columns I added to a list a week ago

    Hi, I'm using VS2012. I added a couple of new columns to an existing list over a week ago.  Using C# code, I was able to connect to the site and got the list.  Able to update the columns until I got to the new column4,  and then I got exception error

  • Help! I missed the code

    Sorry to have to ask this but I am a newbie and have to "attend" a job interview on Skype this afternoon for the first time. I just received a 15 second phone call giving an automated Skype message about a code for the call I am expecting at 3 o'cloc