Search code examples
javaswingpaintcomponentdouble-buffering

java double buffering moving an object with keys


I want to understand this code

import java.awt.Graphics;
import java.awt.Image;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
import javax.swing.JFrame;

public class pinpon extends JFrame  {



private Image image;
    private Graphics graph;
    int x , y ;

    public class klavye extends KeyAdapter{
        public void keyPressed(KeyEvent e){
            int key = e.getKeyCode();
        if (key == e.VK_LEFT)
            x=x-5;      
        if (key == e.VK_RIGHT)  
            x=x+5;  
        if (key == e.VK_UP) 
            y=y-5;
        if (key == e.VK_DOWN)
            y=y+5;
        }
        public void keyReleased(KeyEvent e){    
        }

    }

    public pinpon(){
        addKeyListener(new klavye());

        setSize(640, 480);
        setResizable(false);
        setVisible(true);
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        x=150;
        y=150;
    }

    public void paint(Graphics g){
        image = createImage(getWidth(), getHeight());
        paintComponent(image.getGraphics());
        g.drawImage(image,0,0,this);

    }

    public void paintComponent(Graphics g){
        g.fillOval(x, y, 15, 15);
        repaint();
    }

    public static void main(String[] args) {
        new pinpon();
    }

}

but in here i thing this code is for double buffering

public void paint(Graphics g){
    image = createImage(getWidth(), getHeight());
    paintComponent(image.getGraphics());
    g.drawImage(image,0,0,this);
}

This code is used for moving ball without any trace of ball. But i did not understand how is it works. Can anybody help me. Or tell me where can i find any explanation. Thanks.


Solution

  • But i did not understand how is it works

    Me either and you should not even worry about what it is doing because that code is completely wrong and should NOT be used for several reasons:

    1. you would never invoke paintComponent() directly
    2. you would never invoke repaint() in a painting method. This will cause an infinite loop
    3. custom painting is done by overriding the paintComponent() method only. You don't need to override paint().

    Read the section from the Swing tutorial on Custom Painting for explanations and examples of how painting SHOULD be done.

    Once you understand the basics of painting properly then you can move on to getting rid of the KeyListener. Instead you should be using Key Bindings. All Swing components use Actions and Key Bindings to handle specific keyboard input from the user. Check out Motion Using the Keyboard for more information and working examples.