これは私のコードですが、キーリスナーを持っていますが、キーが押されたときの動作は同じです。シェイプは、ActionListenerのように動きますが、キーの1つを押すと何もしません。キーリストが実行されていない
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;
import java.awt.geom.Ellipse2D;
import javax.swing.*;
public class Snake extends JPanel implements ActionListener {
Timer t = new Timer(5, this);
double x = 0 , y = 0, xVel = 2, yVel = 2;
public void paintComponent(Graphics g)
{
super.paintComponent(g);
Graphics2D g2 = (Graphics2D) g;
Ellipse2D circle = new Ellipse2D.Double(x, y, 40, 40);
g2.fill(circle);
t.start();
}
public void actionPerformed(ActionEvent e){
if(x < 0 || x >460)
{
xVel = -xVel;
}
if(y < 0 || y > 459)
{
yVel = -yVel;
}
x += xVel;
y += yVel;
repaint();
}
public void keyPressed(KeyEvent e) //This part of the Code Doesnt seem to be running
{
int key = e.getKeyCode();
if(key == KeyEvent.VK_DOWN)
{
yVel = yVel; //There may be something wrong with the way i wrote this
xVel = 0;
}
if(key == KeyEvent.VK_UP)
{
yVel = -yVel;
xVel = 0;
}
if(key == KeyEvent.VK_RIGHT)
{
xVel = xVel;
yVel = 0;
}
if(key == KeyEvent.VK_LEFT)
{
xVel = -xVel;
yVel =0;
}
x+= xVel;
y+= yVel;
repaint();
}
}