从外部Jar添加KeyEventListeners到JFrame?

时间:2015-03-04 05:41:54

标签: java swing keylistener

我在这里有一个班级项目,我必须在那里制作一个有效的小行星游戏。现在,我一直坚持让关键事件得到认可。我已经阅读并观看了教程并使其工作,但在此环境中实现相同的功能并没有帮助。我希望也许有人可以指导我朝着正确的方向前进。

这是使用关键操作方法实现KeyListener的主类,它使我的Ship对象成为一个“沙箱”。 “Sandbox”是显示对象的Jframe。 “Sandbox”是从我在课堂上收到的外部jar以及“blobfx.jar”中的其他东西导入的。

package Asteroid;

import java.util.Random;

import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;

import blobfx.SandBox;
import blobfx.SandBoxMode;



public class AsteroidMain implements KeyListener{
//           ^^^^^^^^^^^^ currently has error: "The type AsteroidMain must implement the inherited abstract method KeyListener.keyPressed(KeyEvent)"

private static Random random = new Random();

public static void main(String[] args) {


    SandBox sb = new SandBox();
    sb.setFrameRate(66);
    // makes window for objects at frame rate of 15


    Ship shipThing = new Ship();
    sb.addBlob( shipThing );
    // makes ship object then adds it to the window

    SandBox.simulate(sb);
    // draws the objects on screen

}

@Override
public void keyPressed(KeyEvent e, Ship shipThing) {
//          ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ currently has error: "The method keyPressed(KeyEvent, Ship) of type AsteroidMain must override or implement a supertype method"
    if(e.getKeyCode() == 38){
        shipThing.moveForward(); 
        System.out.println("KEY PRESSED");
    }

}

@Override
public void keyReleased(KeyEvent e) {

}


@Override
public void keyTyped(KeyEvent e) {
    // TODO Auto-generated method stub

}
}

这是我的Ship类,我想在按下UP键时向前移动。

package Asteroid;

import java.lang.Math;

import blobfx.PolyBlob;


public class Ship extends PolyBlob{

private double angle = 0.0;
private final double delta = 0.15;
private final double speed = 5.0;


public Ship( ){

    super(0,0,0);

    int x[] = {10, -10, -5, -10};
    int y[] = { 0,  -7,  0,   7};
    setPolygon( x, y );
    // sets vertices that draws the ship polygon

    setLoc( 200, 200 );

}

public void moveForward(){

    System.out.println( "MOVING FORWARD");

    setLoc( getLoc().x + (int) Math.round(speed * Math.cos(angle)), 
            getLoc().y + (int) Math.round(speed * Math.sin(angle))
            );
}

public void turnLeft(){

}

public void turnRight(){

}


}

1 个答案:

答案 0 :(得分:1)

首先看一下KeyListener

的JavaDocs

您未实施keyPressed(KeyEvent)

,违反了界面的合同要求

此...

@Override
public void keyPressed(KeyEvent e, Ship shipThing) {

本来应该给你一个编译器错误,告诉你你没有覆盖一个方法,它应该是

@Override
public void keyPressed(KeyEvent e) {

您不能只是“发明”参数,界面描述了任何实现必须满足的预期要求

话虽如此,我强烈建议不要使用KeyListener支持Key Bindings API,有关详细信息,请参阅How to Use Key Bindings