Reputation:
So I am making this game. It is a ball bouncing around so far. But I want to add a purpoise of the game. So I added this Pad that I want the user to be able to move around. I searched around and couldn't find a good example how to use keyevents. Anyway, this is my code for the pad.
import java.awt.*;
import javax.swing.*;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import java.awt.EventQueue;
public class MainFrame extends JPanel implements Runnable {
int diaPad = 120;
long delay = 20;
private int xx = 120;
private int yy = 670;
private int dxx = 6;
protected void paintComponent(Graphics g){
super.paintComponent(g);
Graphics2D g2 = (Graphics2D)g;
g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
RenderingHints.VALUE_ANTIALIAS_ON);
g.setColor(Color.BLACK);
g.fillRect(xx,yy,120,15);
}
public void run() {
while(isVisible()) {
try {
Thread.sleep(delay);
} catch(InterruptedException e) {
System.out.println("interrupted");
}
repaint();
}
}
public void movePadRight() {
if(xx + dxx < 0 || xx + diaPad + dxx > getWidth()) {
dxx *= -1;
}
xx += dxx;
}
public void movePadLeft(){
if(xx + dxx < 0 || xx + diaPad + dxx > getWidth()) {
dxx *= -1;
}
xx -= dxx;
}
public void keyBoard(KeyEvent e){
if (event.getKeyCode() == KeyEvent.VK_LEFT) {
movePadLeft();
}
if (event.getKeyCode() == KeyEvent.VK_RIGHT) {
movePadRight();
}
}
}
I don't see any errors in the code but when I compile the program, I get this
MainFrame.java:79: cannot find symbol symbol : variable event location: class MainFrame if (event.getKeyCode() == KeyEvent.VK_RIGHT) { ^
Upvotes: 1
Views: 3029
Reputation: 159754
The KeyEvent
variable is defined as e
if (e.getKeyCode() == KeyEvent.VK_LEFT) {
Note: Use key bindings instead for handing key interaction in Swing. Key Listeners require component focus in order to work. They were designed for the old AWT graphical library and not really suited to Swing.
Upvotes: 2
Reputation: 302
Your KeyEvent variable is "e" not "event". You have the wrong variable name.
Upvotes: 1
Reputation: 121998
if (e.getKeyCode() == KeyEvent.VK_LEFT) {
movePadLeft();
}
You are recieving event as e
.
That variable came from method argument
public void keyBoard(KeyEvent e){ <------
change it to event
, that is more readable than simple e
public void keyBoard(KeyEvent event){
if (event.getKeyCode() == KeyEvent.VK_LEFT) {
movePadLeft();
}
Upvotes: 2