在课堂上,我们的任务是重建游戏太空入侵者。现在我正在努力让我的宇宙飞船穿过底部。我一直在使用调试器,但是当我按下箭头时,我的keyPressed方法没有被调用。
package testprogram;
import java.awt.Color;
import java.awt.Graphics;
import javax.swing.*;
import java.awt.Point;
import java.awt.Polygon;
import java.awt.event.KeyListener;
import java.awt.event.KeyEvent;
public class TestFrame extends JFrame{
public TestFrame(){
setBackground(Color.white);
Test2 t2 = new Test2();
this.add(t2);
t2.repaint();
}
private class Test2 extends JPanel implements KeyListener {
int width;
int height;
DrawObject object;
public Test2(){
setSize(500,500);
setBackground(Color.black);
this.width = this.getWidth();
this.height = this.getHeight();
object= new DrawObject(getWidth(), getWidth());
addKeyListener(this);
}
@Override
public void paintComponent(Graphics g){
super.paintComponent(g);
object.draw(g);
}
@Override
public void keyPressed(KeyEvent k){
int key = k.getKeyCode();
if(key == k.VK_LEFT){//if left arrow is pressed
object.moveLeft();
repaint();
}
if(key == k.VK_RIGHT){//if right arrow is pressed
object.moveRight();
repaint();
}
}
@Override
public void keyReleased(KeyEvent k){
//dummy method
}
@Override
public void keyTyped(KeyEvent k){
//used for launching projectile
}
//used to call draw methods
}
private class DrawObject{
int pnlWidth;
int pnlHeight;
int moveInc =5;
public DrawObject(int pnlWidth, int pnlHeight){
this.pnlWidth=pnlWidth;
this.pnlHeight=pnlHeight;
}
public void draw(Graphics g){
Point loc = new Point();
//bottom right point
loc.x=pnlWidth;
loc.y=pnlHeight;
Polygon triangle = new Polygon();
triangle.addPoint(loc.x, loc.y);//bottom right point
triangle.addPoint(loc.x-50, loc.y);//bottom left point
triangle.addPoint(loc.x-25, loc.y-50);
g.setColor(Color.red);
g.fillPolygon(triangle);
}
//moves canon left
public void moveLeft(){
if(getLocation().getX()>0 && getLocation().getX()<pnlWidth)
getLocation().translate(-moveInc, 0);
}
//moves canon right
public void moveRight(){
if(getLocation().getX()<pnlWidth && getLocation().getX()>0)
getLocation().translate(moveInc, 0);
}
}
}
我已经分离了这个测试类的关键部分。你能告诉我我做错了什么吗?