Java球移动 [英] Java ball moving
问题描述
我的问题是,一旦移动,球就会变成一条线.
这是代码:
My problem is that the ball turns into a line once moved.
Here is the code:
package Java;
import java.awt.*;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
import javax.swing.*;
public class javagame extends JFrame {
private Image dbImage;
private Graphics dbg;
int x, y;
public class AL extends KeyAdapter {
public void keyPressed (KeyEvent e) {
int keyCode = e.getKeyCode();
if(keyCode == e.VK_LEFT) {
x-= 5;
}
if(keyCode == e.VK_RIGHT) {
x+= 5;
}
if(keyCode == e.VK_UP) {
y-= 5;
}
if(keyCode == e.VK_DOWN) {
y+= 5;
}
}
public void keyReleased (KeyEvent e) {
}
}
public javagame() {
addKeyListener(new AL());
setTitle("Java Game");
setSize(750, 750);
setResizable(false);
setVisible(true);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
x = 250;
y = 250;
}
public void paint(Graphics g) {
dbImage = createImage(getWidth(), getHeight());
dbg = dbImage.getGraphics();
paintCompenent(dbg);
g.drawImage(dbImage, 0, 0, this);
}
public void paintComponent (Graphics g){
g.drawString("Copy Right All rights reserved to Aaron Collins 2013-2013", 275, 100);
g.drawLine(270, 105, 415, 105);
g.fillOval(x, y, 15, 15);
repaint();
}
public static void main(String[] args) {
new javagame();
}
}
当我说它变成一条线时,我的意思是球在移动,但并没有移走前一条.
请帮助我解决问题,以便我继续游戏!
When I say it turns into a line, I mean the ball moves but does not remove the previous one.
Please help me resolve the problem so I can continue with my game!
推荐答案
- 您覆盖了
paint
,但是从不调用super.paint
,这意味着该组件永远不会为新的绘制循环准备Graphics上下文,这意味着您之前绘制过的所有内容都将保留 - 您的
paintComponent
方法将永远不会被调用,因为JFrame
不支持此方法 - 您不应在顶级容器(如
JFrame
)上执行自定义绘制,而应使用JPanel
之类的东西并覆盖它的paintComponent
方法(确保首先调用super.paintComponent
). /li> - 您还应该避免在您要覆盖的任何
paintXxx
方法中调用任何可能触发重绘的方法,例如repaint
- You override
paint
, but never callsuper.paint
, meaning that component never prepares the Graphics context for a new paint cycle, meaning that what ever you painted before remains - Your
paintComponent
method will never be called becauseJFrame
does not support this method - You should not be performing custom painting on a top level container (like
JFrame
), but should be using something likeJPanel
and override it'spaintComponent
method (making sure you callsuper.paintComponent
first). - You should also avoid calling any method that may trigger a repaint in any
paintXxx
method you're overriding...likerepaint
Graphics
上下文是共享资源,这意味着给您提供的Graphics
上下文用于在您之前绘制UI中的所有其他组件. paintComponent
负责通过清除要绘制的区域来准备Graphics
绘画环境.
The Graphics
context is a shared resource, that means that the Graphics
context you are given was used to paint all the other components in UI before you. paintComponent
is responsible for preparing the Graphics
context for painting by clearing the area it wants to paint in.
我建议您通读自定义绘画
我也将避免使用KeyListener
并使用键绑定API .
I would also avoid KeyListener
and use the Key Bindings API instead.
这篇关于Java球移动的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!