我是一名使用Java的初级程序员,而我正试图制作一款游戏,通过移动的环向你抛出光盘。盘具有恒定的向下力,可以使用向上键向上移动;但是,在我添加任何碰撞检测之前,我开始收到一条错误,说java编译无法找到e
的变量KeyEvent
。我在网上到处看,我确信我只是犯了一个愚蠢的错误,但有人可以看看这个。
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);
}
}
}
答案 0 :(得分:6)
Java中的函数调用需要括号。你需要写
e.getKeyCode()
不仅仅是
e.getKeyCode