Reputation: 21
I'm a beginning programmer using Java and I'm trying to make a game in which you toss a disc through a moving hoop. The disc has a constant downward force and can be moved upward using the up key; however, before I even added any collision detection I started getting an error saying that java compile couldn't find the variable e
of KeyEvent
. I looked everywhere online and I'm sure I've just made a dumb mistake but can somebody take a look at this please.
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.RenderingHints;
import java.awt.event.KeyListener;
import java.awt.event.KeyEvent;
import javax.swing.JPanel;
import javax.swing.JFrame;
import java.util.Random;
@SuppressWarnings("serial")
public class DiscHoopToss extends JPanel{
int x = 710;
int y = 150;
int xm = -3;
int ym = 1;
int xr = 2;
Random rng = new Random();
int r = rng.nextInt((220-20)+1)+20;
public DiscHoopToss() {
KeyListener listener = new KeyListener() {
@Override
public void keyTyped(KeyEvent e) {
}
@Override
public void keyPressed(KeyEvent e) {
if (e.getKeyCode == KeyEvent.VK_UP) ym = -2;
}
@Override
public void keyReleased(KeyEvent e) {
if (e.getKeyCode == KeyEvent.VK_UP) ym = 1;
}
};
setFocusable(true);
}
private void moveDisc() {
x = x + xm;
y = y + ym;
if (y == 0) {
y = 150;
x = 710;
}
if (y == getHeight() - 20) {
y = 150;
x = 710;
}
if (r + xr < 0) xr = 2;
if (r + xr >getHeight() - 55) xr = -2;
r = r + xr;
}
@Override
public void paint (Graphics g) {
super.paint(g);
Graphics2D g2d = (Graphics2D) g;
g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
g2d.drawOval(50,r,25,55);
g2d.fillOval(x, y, 50, 20);
}
public static void main (String[] args) throws InterruptedException {
JFrame frame = new JFrame("Toss the disc into the hoop!");
DiscHoopToss game = new DiscHoopToss();
frame.add(game);
frame.setSize(750, 350);
frame.setResizable(false);
frame.setVisible(true);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
while(true) {
game.moveDisc();
game.repaint();
Thread.sleep(10);
}
}
}
Upvotes: 0
Views: 478
Reputation: 97148
Function calls in Java require parentheses. You need to write
e.getKeyCode()
not just
e.getKeyCode
Upvotes: 6