[英]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. 谢谢。
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: 无论是我还是您,您甚至不必担心它在做什么,因为该代码是完全错误的,不应出于以下几个原因使用:
paintComponent()
method only. 通过仅重写paintComponent()
方法来完成自定义绘制。 You don't need to override paint(). 您不需要重写paint()。 Read the section from the Swing tutorial on Custom Painting for explanations and examples of how painting SHOULD be done. 阅读Swing教程上有关“ 自定义绘画”的部分,以获取有关绘画方法的解释和示例。
Once you understand the basics of painting properly then you can move on to getting rid of the KeyListener. 一旦了解了正确绘画的基础知识,就可以继续使用KeyListener。 Instead you should be using Key Bindings
. 相反,您应该使用Key Bindings
。 All Swing components use Actions
and Key Bindings
to handle specific keyboard input from the user. 所有的Swing组件都使用Actions
和Key Bindings
来处理来自用户的特定键盘输入。 Check out Motion Using the Keyboard for more information and working examples. 查看使用键盘运动,以了解更多信息和工作示例。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.