Reputation: 15
I want the oval to slide when I hold down the key. But it wont work!
I tried the while loop which did nothing at all.
I kinda disorganized it, but it's still readable. Im using a lower version of java so some things will look different.
import java.awt.Graphics;
import java.awt.Image;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
import javax.swing.JFrame;
public class TEST extends JFrame {
int x, y;
private Image dbgImage;
private Graphics dbg;
public TEST() {
addKeyListener(new AL());
setTitle("CIRCLE THING");
setSize(1000, 1000);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setVisible(true);
setResizable(true);
x = 150;
y = 150;
}
public class AL extends KeyAdapter {
public void keyPressed(KeyEvent e) {
int keyCode = e.getKeyCode();
if(keyCode == e.VK_D) {
x++;
}
if(keyCode == e.VK_A) {
x--;
}
if(keyCode == e.VK_W) {
y--;
}
if(keyCode == e.VK_S) {
y++;
}
}
public void keyReleased(KeyEvent e) {}
}
public void paint(Graphics g) {
dbgImage = createImage (getWidth(), getHeight());
dbg = dbgImage.getGraphics();
paintComponent(dbg);
g.drawImage(dbgImage, 0, 0, this);
}
public void paintComponent(Graphics g) {
g.fillOval(x, y, 90, 100);
repaint();
}
public static void main(String[] args) {
new TEST();
}
}
Upvotes: 1
Views: 325
Reputation: 324128
You should not be overriding paint().
See Motion Using the Keyboard for some examples. The example moves a label, but many of the concepts are the same. One difference is that when you do custom painting you are responsible for invoking the repaint() method on the component when you change a property of the component. In your case when the change the location where you want to paint the image.
Upvotes: 4
Reputation: 1583
You need to call the repaint() method of the image object (the oval) after changing the coordinates values.
In the end of the keyPressed() method, add dbgImage.repaint(). This will cause the image's parent paint() method to be called, which in this case is your frame's paint() method.
Upvotes: 1