如何让关键事件发挥作用

时间:2016-03-11 05:23:43

标签: java input keylistener

我一直在搞乱一些java代码,试图更好地了解语言是如何工作的,我想出了这个。我已经能够让球和框架起作用了,但我无法让它移动,甚至不再运行。它说最后一个大括号后面需要一个分号,但是当我添加它时,很多东西都会变成错误。当我尝试使用Key Listener时,首先出现运行问题,如果有帮助的话。

package com.edu4java.samplegame;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.RenderingHints;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import javax.swing.JFrame;
import javax.swing.JPanel;
@SuppressWarnings("serial")
public class Main extends JPanel {

private static final int ScreenW = 1000;
private static final int ScreenH = 800;
private static final int S_Radius = 25;
private static final int S_X = 100;
private static final int S_Y = 100;
private static final int Step = 100;

private static int x = S_X;             // x at center of the ball
private static int y = S_Y;             // y at center of the ball
private static int radius = S_Radius;   // radius of the ball

private void moveBall() {
   /* x = x + 1;
    y = y + 1;*/
}

KeyListener keyListener = new KeyListener() {
    int keyCode = e.getKeyCode();{
    switch( keyCode ) { 
        case KeyEvent.VK_UP:
            x = x - Step;
            break;
        case KeyEvent.VK_DOWN:
             x = x + Step;
            break;
        case KeyEvent.VK_LEFT:
            y = y - Step;
            break;
        case KeyEvent.VK_RIGHT :
            y = y + Step;
            break;
     }
  };

@Override 
public void paint(Graphics g) {
    super.paint(g);
    Graphics2D g2d = (Graphics2D) g;
    g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
        RenderingHints.VALUE_ANTIALIAS_ON);
    g2d.fillOval(x, y, 30, 30);
}

public static void main(String[] args) throws InterruptedException{
    JFrame frame = new JFrame("Forgotten");
    Main game = new Main();
    frame.add(game);
    frame.setSize(ScreenW, ScreenH);
    frame.setVisible(true);
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

    while (true) {
        game.moveBall();
        game.repaint();
        Thread.sleep(10);
    }
}

}

2 个答案:

答案 0 :(得分:0)

您需要注册KeyListener 在Main类中,添加一个方法来创建并返回一个KeyListener(包装你为KeyListener提供的内容)。然后在main中,注册监听器,如下所示:

frame.addKeyListener(main.getKeyListener());

或者,您可以将Main本身设为KeyListener(Main实现KeyListener),实现方法,然后您只需使用main:

frame.addKeyListener(main);

答案 1 :(得分:0)

JPanel无法使用' KeyListener',id建议您为此类侦听器创建一个新类

public class keyListen implements KeyListener {

private Main g;

public keyListen(Main g) {
    this.g = g;
}

@Override
public void keyTyped(KeyEvent e) {
    //code

}

@Override
public void keyPressed(KeyEvent e) {
    // code

}

@Override
public void keyReleased(KeyEvent e) {
    // code
}

}

完成后,您需要在主方法中将其注册为

frame.addKeyListener(new keyListen(g));

我仍然对自己为什么JPanel不允许使用KeyListener感到困惑,但要注意的是使用Key事件监听器可能不是最好的主意!