Re: help with KeyListener
I don't see where the KeyListener is added to any component (also don't see how this compiles, but that's a separate issue). Call addKeyListener to do so (See How to Write a Key Listener (The Java™ Tutorials > Creating a GUI With JFC/Swing > Writing Event Listeners) )
Re: help with KeyListener
Alright so here is my modified code. It now does what I wanted but there is a white flash every time it moves, and you can only see the dot on like every tenth move. How can I make the animation smooth?
Code :
import java.awt.*;
import java.awt.event.*;
import java.applet.*;
import java.util.*;
import static java.lang.System.*;
public class forum_practice extends Applet implements KeyListener{
int x = 0;
int y = 0;
byte direction;
final byte UP = 1;
final byte RIGHT = 2;
final byte DOWN = 3;
final byte LEFT = 4;
public void init() {
x = 100;
y = 100;
addKeyListener(this);
}
public void paint(Graphics g) {
g.setColor(Color.black);
g.fillOval(x, y, 10, 10);
run();
}
public void run(){
try {
Thread.sleep(100);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
if(direction==UP){
y-=10;
}
if(direction==DOWN){
y+=10;
}
if(direction==LEFT){
x-=10;
}
if(direction==RIGHT){
x+=10;
}
repaint();
}
@Override
public void keyPressed(KeyEvent e) {
if(e.getKeyCode()==37){
direction = LEFT;
}
if(e.getKeyCode()==38){
direction = UP;
}
if(e.getKeyCode()==39){
direction = RIGHT;
}
if(e.getKeyCode()==40){
direction = DOWN;
}
repaint();
}
@Override
public void keyReleased(KeyEvent e) {
}
@Override
public void keyTyped(KeyEvent e) {
// TODO Auto-generated method stub
}
}
Re: help with KeyListener
Your running into a common issue when it comes to drawing things with swing. Swing is a single threaded model, and updates and listeners are called on this thread. When you call Thread.sleep you end up sleeping this thread, and no painting can be performed until the sleep has finished. If you wish to perform animation, use a SwingTimer or throw the work onto another thread (if you use the other thread approach, make sure you place swing calls onto the EDT using SwingUtilties).
Re: help with KeyListener
Thread moved to - AWT / Java Swing