JFrame and Double Buffering

Is double buffering incorporated into Jframes? If so how can I implement it?

I don't know the answer to your question. But, looking at your recent threads, I think you need to be told that there is a Swing forum here:
http://forum.java.sun.com/forum.jspa?forumID=57
Most of your questions are related to Swing, and you will get better answers in that forum--where more Swing experts hang out.
Good luck!

Similar Messages

  • Panel refreshing and double buffering

    Hi all swing experts
    Could any one solve the problem.I have an application,which is having a JSplit pane.
    On the left of the JSplit pane , there is a tree. When u click a node from the tree
    that will be selected and you can place that node into the right side panel.
    And the same way you can click an another node (redirection or sink) and drop into the
    panel.you can draw a line by clicking the source and the sink / or redirection.
    The line is getting drawn dynamically by getting the x,y coordinates of the node.
    once the line is drawn am storing the line into vector, since this is getting drawn
    dynamically once if i minimize and maxmize it will disappear.
    For avoiding this am trying to redraw the old line from the vector when the window
    is getting activated, here the problem starts it draws the line but the line
    is getting disappeared immly.
    HOW DO I SOLVE THIS?
    is it possible to solve this problem with double buffering tech? if so how?
    PL HELP.
    Software - Visual Tool
    Last Modified -7/23/01
    sami
    import java.awt.*;
    import java.awt.event.*;
    import java.io.*;
    import java.util.*;
    import javax.swing.*;
    import javax.swing.border.TitledBorder;
    import javax.swing.event.TreeSelectionEvent;
    import javax.swing.event.TreeSelectionListener;
    import javax.swing.plaf.FontUIResource;
    import javax.swing.tree.*;
    import java.lang.System;
    import java.net.*;
    import java.awt.image.*;
    import javax.swing.event.*;
    public class CompTree extends JFrame implements TreeSelectionListener,WindowListener{      
    // Swing components declarations     
         public JSplitPane jSplitPane1,jSplitPaneTop;
         public JScrollPane treeScrollPane,splitScrollPane;     
    public JTree mainTree,jtree ;
    public static DefaultMutableTreeNode topchildnode1, topchildnode2, topchildnode3,toptreenode;
    DrawPanel dp = new DrawPanel();
         public int i=0;
         public int j=0;
         public int flag = 1 ;
         public String var,S,R,D;
    Frame fr = new Frame("GUI TOOL");
    public CompTree()
         File nFile = null ;     
         mainTree = DrawTree(nFile,"N") ;
         mainTree.updateUI();
         mainTree.setBackground(new Color(105,205,159));     
              // Tree is getting added into scroll pane
         treeScrollPane = new JScrollPane(mainTree);
              treeScrollPane.setVerticalScrollBarPolicy(javax.swing.JScrollPane.VERTICAL_SCROLLBAR_ALWAYS);
    treeScrollPane.setHorizontalScrollBarPolicy(javax.swing.JScrollPane.HORIZONTAL_SCROLLBAR_ALWAYS);
              splitScrollPane = new JScrollPane();
              splitScrollPane.setViewportView(dp.panel1);          
              splitScrollPane.setVerticalScrollBarPolicy(javax.swing.JScrollPane.VERTICAL_SCROLLBAR_ALWAYS);
    splitScrollPane.setHorizontalScrollBarPolicy(javax.swing.JScrollPane.HORIZONTAL_SCROLLBAR_ALWAYS);
    jSplitPane1 = new JSplitPane(JSplitPane.HORIZONTAL_SPLIT,treeScrollPane,splitScrollPane);          
         jSplitPane1.setOneTouchExpandable(true);
         jSplitPane1.setContinuousLayout(true);
    jSplitPane1.addComponentListener(new ComponentAdapter(){
              public void componentResized(ComponentEvent e) {      
                   System.out.println("Componenet resized");
              flag = 1;
              paint(dp.panel1.getGraphics());          
    //Provide minimum sizes for the two components in the split pane
    Dimension minimumSize = new Dimension(150,75);
              splitScrollPane.setMinimumSize(minimumSize);
    //Provide a preferred size for the split pane
    jSplitPane1.setPreferredSize(new Dimension(700, 500));
              //setContentPane(jSplitPane1);
              fr.add(jSplitPane1);
              fr.setSize(700,500);
              fr.setVisible(true);          
              fr.addWindowListener(this);     
    public void windowActivated(WindowEvent we){
         System.out.println("activated");
         dp.draw();
    public void windowClosed(WindowEvent we){System.out.println("closed");}
    public void windowIconified(WindowEvent we){System.out.println("iconified");}
    public void windowDeiconified(WindowEvent we){
         dp.draw();
         System.out.println("deiconified");
    public void windowDeactivated(WindowEvent we){System.out.println("deactivated");}
    public void windowOpened(WindowEvent we){
         dp.repaint();
         System.out.println("opened");
    public void windowClosing(WindowEvent we){
         System.exit(0);
         System.out.println("closing");
         public void valueChanged(TreeSelectionEvent e) {
              DefaultMutableTreeNode node = (DefaultMutableTreeNode)
              mainTree.getLastSelectedPathComponent();     
              String strRootNode = "" ;
              try{
                   Object rootNode = node.getRoot();          
                   strRootNode = rootNode.toString() ;
              catch(Exception eRoot)
                   System.out.println("Error in geting Root Node");
              if (node == null) return;
              Object nodeInfo = node.getUserObject();          
              TreeNode ParentNode = node.getParent();               
              final String strParentName = node.toString() ;
                   if (strParentName.equals("Source"))
              System.out.println("Before source");     
              var = "S";
              System.out.println("This is source");
              else if (strParentName.equals("Redirection"))
    var ="R";
              else if (strParentName.equals("Sink") )
                   var ="D";
              else
                   if ( strRootNode != strParentName){
         public JTree DrawTree( File file, String strIsValid)
                   jtree = new JTree();
                   toptreenode = new DefaultMutableTreeNode("Start");
                   topchildnode1 = new DefaultMutableTreeNode("Source");
                   topchildnode2 = new DefaultMutableTreeNode("Sink");
                   topchildnode3 = new DefaultMutableTreeNode("Redirection");
                   toptreenode.add(topchildnode1);
                   toptreenode.add(topchildnode2);
                   toptreenode.add(topchildnode3);
                   jtree.putClientProperty("JTree.lineStyle", "Angled");
                   DefaultTreeModel defaulttreemodel = new DefaultTreeModel(toptreenode);
                   jtree.setModel(defaulttreemodel);
                   DefaultTreeSelectionModel defaulttreeselectionmodel = new DefaultTreeSelectionModel();
                   defaulttreeselectionmodel.setSelectionMode(1);
                   jtree.setSelectionModel(defaulttreeselectionmodel);
                   jtree.addTreeSelectionListener(this);
                   jtree.setEditable(true);
                   return jtree;      
    public static void main(String args[]){
         CompTree ct = new CompTree();
         * This class contains all the component related to panel 1
         * this can be used for .....
    public class DrawPanel extends JPanel implements ActionListener,
         ComponentListener,MouseListener,KeyListener{
         public JRadioButton uniRadio,multiRadio,show;
         public JButton sBut,rBut,dBut;
         public int flag = 1 ;
         public int Radio = 1;
         public boolean sIndicator = true;
         public boolean rIndicator = true;
         public boolean isDestSelected = false;
         public boolean isDestFirstTime = true;
    public int x1 = 0 ;
         public int y1 = 0 ;
         public int x2 = 0 ;
         public int y2 = 0;
         public int x3 = 0;
         public int y3 = 0;
         public int k=0;
         public int l = 40;
    public int b = 40;     
         public String connection1,connection2,connection3,destination1,destination2;
         public int locX;
         public int locY;
    public JPanel panel1 = new JPanel ();      
    public JPanel panel2 = new JPanel ();     
         Vector lines = new Vector();
         Vector colors = new Vector();
         Vector obj = new Vector();
    Vector source = new Vector();
         Vector loc = new Vector();
         BasicStroke stroke = new BasicStroke(2.0f);
    Icon compImage = new ImageIcon("network1.gif"); //new
    Icon workImage = new ImageIcon("tconnect02.gif");
    Icon lapImage = new ImageIcon("server02.gif");
         public DrawPanel(){
         am adding radio button for checking the mode unicast and broad cast mode -- new
    uniRadio = new JRadioButton("Unicast Mode");
    uniRadio.setMnemonic(KeyEvent.VK_B);
    uniRadio.setSelected(true);
    multiRadio = new JRadioButton("Broadcast Mode");
    multiRadio.setMnemonic(KeyEvent.VK_C);
    show = new JRadioButton("show Panel");
    show.setMnemonic(KeyEvent.VK_C);
         ButtonGroup group = new ButtonGroup();
    group.add(uniRadio);
    group.add(multiRadio);
              group.add(show);
         /*     Border border = ButtonGroup.getBorder();
              Border margin = new EmptyBorder(10,10,10,10);
              ButtonGroup.setBorder(new CompoundBorder(border,margin)); */
              uniRadio.addActionListener(this);
         multiRadio.addActionListener(this);
              show.addActionListener(this);
    panel1.add(uniRadio);
              panel1.add(multiRadio);
              panel1.add(show);
              uniRadio.setBounds(150,15,100,40);
              multiRadio.setBounds(260,15,120,40);
              show.setBounds(390,15,100,40);
              uniRadio.setBackground(new Color(105,200,205));
              multiRadio.setBackground(new Color(105,200,205));
              show.setBackground(new Color(105,200,205));
              /*****************PANEL 1*********************/
              panel1.setLayout(null);
    panel1.setBounds(new Rectangle(0,0,400,400));
              panel1.setBackground(new Color(105,100,205));
              panel1.addComponentListener(this);
              panel1.addMouseListener(this);      
         public void sourceObject(String name)
    sBut = new JButton(compImage);
         panel1.add(sBut);     
         sBut.setMnemonic(KeyEvent.VK_F);
         sBut.setBounds(new Rectangle(locX,locY,l,b));     
         sBut.addActionListener(this);
         sBut.addMouseListener(this);
         sBut.addKeyListener(this);
    System.out.println("am inside the source object") ;
         sBut.setBackground(new Color(105,100,205));
         System.out.println("key number" +sBut.getMnemonic());
         System.out.println("MY LOCATION : SBUT : "+ sBut.getLocation());
         public void redirectionObject(String name)
         rBut = new JButton(workImage);
         panel1.add(rBut);
         rBut.setBounds(new Rectangle(locX,locY,l,b));     
    rBut.addActionListener(this);
         rBut.addMouseListener(this);
         rBut.addKeyListener(this);
         rBut.setBackground(new Color(105,100,205));
    System.out.println("am inside the redirection :" + j) ;
    System.out.println("MY LOCATION : RBUT : "+ rBut.getLocation());          
    public void destinationObject(String name){     
         dBut = new JButton(lapImage);
         panel1.add(dBut);     
         dBut.setBackground(new Color(105,100,205));
    System.out.println("am inside the destination object") ;     
    dBut.setBounds(new Rectangle(locX,locY,l,b));                    
         System.out.println("am inside the destination:" + j) ;
         dBut.addActionListener(this);
         dBut.addMouseListener(this);
         dBut.addKeyListener(this);
         System.out.println("MY LOCATION : DBUT : "+ dBut.getLocation());           
    public void paintComponent(Graphics g){
    super.paintComponent(g);
         System.out.println("inside paint");
         Graphics2D g2 = (Graphics2D) g;
    g2.setStroke(stroke);
    if(flag == 1){
         /* this is for drawing current line, this will be drawn when component event happens */
              g.setColor(getForeground());
    System.out.println("inside flag");
    int np = lines.size();
                        System.out.println("Total number of lines present the buffer to draw :" + np);
                             for (int I=0; I < np; I++) {                       
         Rectangle p = (Rectangle)lines.elementAt(I);
                        g2.setColor((Color)colors.elementAt(I));
                             System.out.println("width" + p.width);
                             g2.setColor(Color.red);
                        //     g2.setPaint(p.x,p.y,p.width,p.height);
                             g2.drawLine(p.x,p.y,p.width,p.height);                         
                             System.out.println("$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$");
                             System.out.println(obj.elementAt(I));
                             System.out.println("$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$");
                             System.out.println(p.x +"," +","+ p.y + ","+ ","+ p.width+ "," + ","+ p.height);
    flag = -1;
    }else if(flag == -1){
         if(x1 != 0 && y1 != 0 && x2 != 0 && y2 != 0 ){
    connection1 = "source to redirection";
    g2.setColor(Color.red);
         g2.drawLine(x1,y1,x2,y2);          
         lines.addElement(new Rectangle(x1,y1,x2,y2));
         colors.addElement(getForeground());
         obj.addElement(connection1);
         x1 = 0 ;y1 = 0 ;
         x2 = 0 ;y2 = 0 ;
    else if (x2 != 0 && y2 != 0 && x3 != 0 && y3 != 0 )
              connection2 = "Redirection to Destination";
              g2.setColor(Color.green);
                   g2.drawLine(x2,y2,x3,y3);                    
    colors.addElement(getForeground());
                   lines.addElement(new Rectangle(x2,y2,x3,y3));               
                   obj.addElement(connection2);
                   x2 = 0; y2 = 0 ;
                   x3 = 0 ; y3 = 0 ;                    
    else if (x1 != 0 && y1 != 0 && x3 != 0 && y3 != 0)
                   connection3 = "Source to Destination";
                   g2.setColor(Color.red);
                   g2.drawLine(x1,y1,x3,y3);                    
    colors.addElement(getForeground());
                   lines.addElement(new Rectangle(x1,y1,x3,y3));                              
                   obj.addElement(connection3);
                        x1 = 0; y1 = 0 ;
                        x3 = 0 ; y3 = 0 ;                    
                        /*     Image offscreen = panel1.createImage(400,400);
              Graphics og = offscreen.getGraphics();
         og.drawLine(200,200,500,500);
              g.drawImage(offscreen,0,0,null); */
    // Component Listener's method
    public void componentHidden(ComponentEvent e) { 
    if(e.getSource().equals(panel1)){System.out.println("Componenet Hidden");}
              System.out.println("Componenet Hidden");
    public void componentMoved(ComponentEvent e) {
              System.out.println("Componenet moved");
              draw();
    public void componentResized(ComponentEvent e) {      
              System.out.println("Componenet resized");
              flag = 1;
              paintComponent(panel1.getGraphics());
    public void componentShown(ComponentEvent e) {     
              System.out.println("Componenet Shown");
    // Mouse Listerner's Method
         public void mouseClicked(MouseEvent me){
    if (me.getSource().equals(panel1))
              System.out.println("inside mouse clicked");
                        if(var == "S"){
    the boolean sIndicator will allow the usage of source object only once
         This is the case for both unicast and multi cast.It has been restricted
         to single use.
                             if (sIndicator){
                             System.out.println("inside mouse clicked");
                        System.out.println("locX" + locX);
                        locX = me.getX();
    locY = me.getY();
                   sourceObject("Source");
                             sIndicator = false;
                        }else{}
              }else if (var == "R")
    if(rIndicator){
    if(!isDestSelected){
    System.out.println("redirection" + locX);
    locX = me.getX();
    locY = me.getY();
                   redirectionObject("Redirection");
                   rIndicator = false;
                   }else{}
    } else{}
              }else if(var == "D"){
              if(Radio == 1 && isDestSelected == false){
              System.out.println("Destination -- uni cast mode" + locX);
    locX = me.getX();
    locY = me.getY();
                   destinationObject("Sink");
              isDestSelected = true;
              } else if (Radio == 2)
                                  System.out.println("Destination -- Multicast mode" + locX);
                                  locX = me.getX();
                                  locY = me.getY();
                                  destinationObject("Sink");
                                  isDestSelected = true;                    
         public void mousePressed(MouseEvent me){System.out.println("am inside mouse pressed"); }
         public void mouseReleased(MouseEvent me){
              System.out.println("am inside mouse released");
              paintComponent(panel1.getGraphics());
         public void mouseEntered(MouseEvent me){}
         public void mouseExited(MouseEvent me){}
    // key Listener
    public void keyReleased(KeyEvent e) {        
                        Component compo =(JButton)e.getSource();                               
                             if (e.getKeyChar() == e.VK_DELETE){                         
                             remove(compo);
              public void keyTyped(KeyEvent e) {}
              public void keyPressed(KeyEvent e){}
    public void remove(Component comp){          
    System.out.println("inside delete key" );                         
         panel1.remove(comp);
         panel1.repaint();     
         public void draw(){
              super.paint(panel1.getGraphics());
              System.out.println("inside draw");
              flag = 1;
              paintComponent(panel1.getGraphics());     
         public void actionPerformed(ActionEvent e)
                             if(e.getSource().equals(sBut)){
                                  System.out.println("am s button");                
                                  x1 = sBut.getX() + l;
                                  y1 = sBut.getY() + (b/2);
                             else if(e.getSource().equals(rBut)){
                                  System.out.println("am r button");               
                                  x2 = rBut.getX() ;
                                  y2 = rBut.getY()+ b/2;
                                  System.out.println("x2 : " + x2 + "y2 :" +y2 );
                             else if(e.getSource().equals(dBut)){
                                  System.out.println("am d button");                
                                  x3 = dBut.getX();
                                  y3 = dBut.getY()+ b/2;
                             else if (e.getSource().equals(uniRadio)){
                                  System.out.println("uni radio");
                                  Radio = 1 ;
                             } else if (e.getSource().equals(multiRadio)){
                                       System.out.println("multi radio");
                                       Radio = 2;
                             } else if (e.getSource().equals(show)){            
                                  System.out.println("inside show");
    *********************************************

    ok
    i don't take a long time tracing your code, but i think u have to overwrite the repaint methode so it 's call the methode which will paint the line each time.
    hope this will help!

  • Double buffering for shape animation

    Hello people,
    I'm building an applet which animates some text (a shape with various setting for stroke, fill, etc.) and translating it from x1 to x2 using AffineTransform. How can I clear the screen to create an animation effect and double buffering to avoid flickering? Double buffering can be used with ImageS, but what about ShapeS?
    Many thanks

    Double buffering is a general concept that applies to all
    graphic objects.

  • 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

  • Drawing with double buffering to a JFrame

    I want to create a simple JFrame and draw stuff to it via Graphic object using double buffering.
    If I create a loop and draw constantly using JFrame.getGraphic().xxx, am i doing double buffering. ( 'cause i read somewhere that swing components automaticly use double buffering ). And is this the righ approuch ( or whatever it's spelled ) ?

    I want to create a simple JFrame and draw stuff to it
    Don't do that.
    If you want to do custom rendering then use JPanel or JComponent, not JFrame.
    If I create a loop and draw constantly using JFrame.getGraphic().xxx, am i doing double buffering.
    No.
    You're also painting outside the standard paint cycle, which is a Bad Idea.
    So, essentially, everything your suggesting is the wrong way to go about things.
    In its most simple form, double buffering works something like this, though there are a whole load of subtleties to consider (such as component resizing for a start)
    public class Foo extends JComponent
        private BufferedImage image = null;
        protected void paintComponent(Graphics g)
            if (image != null)
                image = createImage(getWidth(), getHeight());
                paintBuffer(ig);
            g.drawImage(image, 0, 0, this);
        private void paintBuffer()
            Graphics ig = image.getGraphics();
            // do the rendering
            ig.dispose();
    }

  • Double Buffering and Components

    Hello I am wondering how do I turn off double buffering for my components. This is important for printing as double buffering makes the print job alot of MB

      /** The speed and quality of printing suffers dramatically if
       *  any of the containers have double buffering turned on.
       *  So this turns if off globally.
       *  @see enableDoubleBuffering
      public static void disableDoubleBuffering(Component c) {
        RepaintManager currentManager = RepaintManager.currentManager(c);
        currentManager.setDoubleBufferingEnabled(false);
      /** Re-enables double buffering globally. */
      public static void enableDoubleBuffering(Component c) {
        RepaintManager currentManager = RepaintManager.currentManager(c);
        currentManager.setDoubleBufferingEnabled(true);
      }

  • I am trying to write a double buffered data acquisition program using MFC and a callback function.

    i am trying to do a double buffer data acquisition using MFC application framework in Visual Studio.i want to use a callback function to notify when the buffer is half full.do you have some sample reference program that can help me?

    What DAQ board are you using? When you installed NI-DAQ you should have selected to install the support files for VC++. Then there will be several examples on how to do double buffered data acquisition.
    If you have already installed NI-DAQ 6.8 or higher and did not select to include the support files, you can run the NI-DAQ setup program and just add them. If you are using an older version, you will have to uninstall and reinstall.
    Once you have the support files, follow this path to the examples.
    >>Program Files>>National Instruments>>NI-DAQ>>Examaples>>Visual C>>
    If you are doing digital acquistion, goto the di folder, if you are doing analog acquisition goto the ai folder.
    As for the callback function, you can use the NI-DAQ function Config_DAQ_
    Event_Message with DAQEvent Type = 1, where N would equal half your buffer.
    Brian

  • Can i use double buffering with SCAN_Sequence_Setup and sample rate divisors?

    If possible I would like to use double buffering when acquiring multiple channels at different rates using SCAN_Sequence_Setup. What are the tricks to sizing the buffers, if any.
    PCI-MIO-16Xe-10 and PCI-6052E are the boards I'm writing for, using Borland C++ builder under Windows2000
    Thanks,
    Brady

    Hello;
    At this time, you can't set up a multiple Scan Rate for different channels at same DAQ board. But, you can set up your Sample Rate to the fastest required to acquire you fastest channel, and then discard the readings of the other channels and only take the values for the different channels at their theoretical rate.
    Hope this helps.
    Filipe

  • 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));
    }

  • 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 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.

  • Strange double buffering bug

    Hi all,
    I have stumbled on strange swing behavior on Windows, most probably connected to double buffering introduced in java 6.
    Once in a while Windows stops redrawing my JFrame. From the java side everything seems ok - all the components are painted (that is, all native methods called), EventQueue normally processed by EDT, but repainted GUI is not shown on the screen. Note that OS has the repainted info - if I cover part of the application window with another window (e.g. explorer), and hid it back, the part that was covered is repainted. This happens even if I have java app halted on debug, so no other java actions can cause this repaint - OS has to have this image, it just does not put it on the screen. When I minimize/maximize the app, everything goes back to normal.
    Note that I can normally operate the app "as if" it was painted - I can change tabs, click buttons (even though I can't see them), and results of these actions are painted by java to some offscreen buffer, but are only shown when I cover/uncover my app with another window, or min/max it. Min/Maxing ends this strange state and further repaints are shown normally.
    Did any of you have this kind of problem? Any idea how to approach/resolve it or what can be the cause?
    Java is 1.6.20, I have seen the behavior on Windows XP, Vista and 2008. It is not reproducible, it just happens sometimes. I haven't seen that on Java 5. Turning off double buffering resolves that, but is not feasible due to degraded user experience.
    Thanks in advance for your help!
    Jakub

    Thanks for your help so far, perhabs this is something with the driver, but I use fairly generic windows distribution.
    EDT is not hosed, it is processing events normally (I checked that on debug step-by-step). We do not override any paint methods, and this is rather something on different level - it is not "a component not being repainted" it is "everything is repainted, but not shown on screen". Including tabbedPane's tab changes, menu display, etc. I can even see cursor changing into carret when I hover over "not shown" textfield.
    Displaying and then disposing of modal dialog also fixes the state, as do resizing of the JFrame.

  • 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:
       ***

  • How to handle both single click and double click from mouse

    hey,
    I looked in past threads and didn't get a proper answer for capturing both single and double click from the mouse.
    in most applications the single click action does not interfere with the double click action, for example in a text editor, single click sets the cursor in between the text, double click marks a word, triple click marks a sentence, they do not bother each other, they all can happen first the single then the double and then the triple, but what if i have a very distinct action for each of the actions, the e.getClickCount() returns every time the number of clicks and if i use
    if(e.getClickCount()==1)
        doSingleClick();
    if(e.getClickCount()==2)
        doDoubleClick();it will always do first the single click and then the double click, which works fine with the example i gave, but not with what i want to do, so i was thinking to over come this that i will use another thread to run my tasks if dt has past since the last click and by the last click counts to perform the correct action and go to sleep until the next mouse click notify it, what do you think?
    run this to get what i mean...
    package blah;
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    public class MouseClickTest {
         static long previousTime = System.currentTimeMillis();
         public static void main(String[] args) {
              JPanel panel = new JPanel();
              JButton component = new JButton("Hit me, please");
              component.addMouseListener(new MouseAdapter(){
                   public void mouseClicked(MouseEvent me){
                        if(me.getClickCount()==1)
                             System.out.println("Now I will do single click action");
                        if(me.getClickCount()==2)
                             System.out.println("Now I will do DOUBLE click action");
    //                    System.out.println("Click count: " + me.getClickCount());
              panel.add(component);
              Launcher.launch(panel);
    package blah;
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    public class Launcher {
         public static JFrame launch (Container contents, String title, Color backgroundColor) {
              JFrame frame = new JFrame (title);
              if (backgroundColor != null) {
                   frame.setBackground (backgroundColor);
                   contents.setBackground (backgroundColor);
              } else {
                   frame.setBackground (contents.getBackground());
              frame.getContentPane().add (contents, BorderLayout.CENTER);
              frame.pack();
              frame.addWindowListener (new WindowAdapter() {
                   public void windowClosing (WindowEvent e) {
                        System.exit (0);
              frame.setVisible (true);
              return frame;
         public static JFrame launch (Container contents, String title)      {
              return launch (contents, title, null);
         public static JFrame launch (Container contents, Color backgroundColor) {
              return launch (contents, contents.getClass().getName(), backgroundColor);
         public static JFrame launch (Container contents) {
              return launch (contents, contents.getClass().getName());
    }

    Read my comments and solution in this posting; [http://forums.sun.com/thread.jspa?forumID=57&threadID=705244]
    and then choose a better design for your application.

  • 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.

Maybe you are looking for