我正在编写一个类来围绕屏幕移动一个圆圈,但主要的问题是布尔变量没有变为true,尽管我尝试将它们变为true。我不知道自己做错了什么。请帮忙。感谢。
public class Restart extends Panel implements KeyListener {
static final int left = 37;
static final int right = 39;
static final int down = 40;
static final int up = 38;
static boolean leftPress = false;
static boolean rightPress = false;
static boolean upPress = false;
static boolean downPress = false;
static int x1 = 0;
static int y1 = 0;
Restart(int width, int length, int minusBy) {
super(width, length, minusBy);
}
public static void main(String args[]) throws InterruptedException {
Restart panel = new Restart(500, 500, 9);
JFrame frame = new JFrame("Fishy");
frame.add(panel);
Frame.showFrame(frame);
while (true) {
if (upPress) {
y1--;
}
if (downPress) {
y1++;
}
if (leftPress) {
x1--;
}
if (rightPress) {
x1++;
}
Thread.sleep(1);
frame.repaint();
}
}
public void paintComponent(Graphics g) {
super.paintComponent(g);
g.fillOval(x1, y1, 50, 50);
}
@Override
public void keyPressed(KeyEvent e) {
if (up == e.getKeyCode()) {
upPress = true;
}
if (down == e.getKeyCode()) {
downPress = true;
}
if (left == e.getKeyCode()) {
leftPress = true;
}
if (right == e.getKeyCode()) {
rightPress = true;
}
}
@Override
public void keyReleased(KeyEvent e) {
if (up == e.getKeyCode()) {
upPress = false;
}
if (down == e.getKeyCode()) {
downPress = false;
}
if (left == e.getKeyCode()) {
leftPress = false;
}
if (right == e.getKeyCode()) {
rightPress = false;
}
}
/* NOT USING */
@Override
public void keyTyped(KeyEvent e) {
}
}
答案 0 :(得分:0)
您永远不会将keylistener添加到任何组件。所以你不会得到任何输入。通过调用Component
,将重新启动作为keylistener添加到某些JPanel
(setFocusable(true)
,而其他一些可能需要使用someComponent.addKeyListener(this)
调整焦点)。我建议您将监听器添加到Restart
实例本身。