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
, but never callsuper.paint
, meaning that component never prepares the Graphics context for a new paint cycle, meaning that what ever you painted before remainspaintComponent
method will never be called becauseJFrame
does not support this methodJFrame
), but should be using something likeJPanel
and override it'spaintComponent
method (making sure you callsuper.paintComponent
first).paintXxx
method you're overriding...likerepaint
The
Graphics
context is a shared resource, that means that theGraphics
context you are given was used to paint all the other components in UI before you.paintComponent
is responsible for preparing theGraphics
context for painting by clearing the area it wants to paint in.I'd recommend that you take a read through Custom Painting
I would also avoid
KeyListener
and use the Key Bindings API instead.