所以我創建了JPanel的擴展版本,不幸的是它不響應任何鍵入。你能告訴我問題是什麼嗎?我搜查了所有其他帖子,但我找不到我的錯誤。KeyListener不改變JPanel
public class MyPanel extends JPanel implements ActionListener,KeyListener{
Timer tm=new Timer(5,this);
int x=0,y=0 ,velX=0, velY=0;
public MyPanel(){
tm.start();
addKeyListener(this);
setFocusable(true);
requestFocusInWindow();
}
public void paintComponent(Graphics g){
super.paintComponent(g);
g.fillRect(0,0,this.getWidth(),this.getHeight());
g.setColor(Color.RED);
g.fillRect(x,30,50,30);
}
public void actionPerformed(ActionEvent e){
if(x<0||x>370)
velX=-velX;
if(y<0||y>370)
velY=-velY;
y=y+velY;
x=x+velX;
repaint();
}
public void keyPressed(KeyEvent e){
int c=e.getKeyCode();
System.out.println("Cascsadas");
if(c==KeyEvent.VK_LEFT){
velX=-1;
velY=0;
}
if(c==KeyEvent.VK_UP){
velX=0;
velY=-1;
}
if(c==KeyEvent.VK_RIGHT){
velX=1;
velY=0;
}
if(c==KeyEvent.VK_DOWN){
velX=0;
velY=1;
}
}
public void keyTyped(KeyEvent e){};
public void keyReleased(KeyEvent e){};
}
我所在的地方使用此JPanel類是:
public class Tester
{
public static void main(String[] args){
MyPanel t=new MyPanel();
JFrame jf=new JFrame();
jf.setTitle("Tutorial");
jf.setVisible(true);
jf.setSize(600,400);
jf.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
jf.getContentPane().add(t,BorderLayout.CENTER);
}
}
爲了更好地幫助更快(在左,右,上,下斜也是所有方向移動),後一個[MCVE](http://stackoverflow.com/help/mcve)(最小完整和可驗證示例)。 –