码迷,mamicode.com
首页 > 其他好文 > 详细

implements KeyListener了按键监听却监听不到

时间:2014-09-19 13:53:05      阅读:226      评论:0      收藏:0      [点我收藏+]

标签:style   color   io   os   java   ar   sp   on   c   

今天写游戏,按键监听却是总也添加不上去苦思冥想,

我实现了接口但是监听不到

后来才发现我只是实现了结口却没调用它仔细想来就在控件panel上面添加了一个addKeyListener(this);

写监听一定要记得让控件去触发总之来说还是基础不牢固,马虎

其次我有在其他的程序里测试发现方法都写了也不行:后来比较了一下少了个

this.setFocusable(true);

网上一查才知道还需要获取焦点,伙伴们你们知道了么?

将控件设置成可获取焦点状态,默认是无法获取焦点的,只有设置成true,才能获取控件的点击事件

import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;


import javax.swing.JFrame;
import javax.swing.JPanel;




public class mainFrame extends JFrame {
private KeyboardPanel keyboardPanel =new KeyboardPanel();
public mainFrame(){
add(keyboardPanel);
keyboardPanel.setFocusable(true);

}
public static void main(String [] args){
mainFrame frame = new mainFrame();
frame.setTitle("mainFrame");
frame.setSize(300,300);
frame.setLocationRelativeTo(null);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
}
static class KeyboardPanel extends JPanel implements KeyListener{
private int x=100;
private int y=100;
private char keyChar = ‘A‘;
public KeyboardPanel(){
setBackground(Color.cyan);
addKeyListener(this);
/*addKeyListener(new KeyAdapter(){
public void keyPressed(KeyEvent e){
switch (e.getKeyCode()){
case KeyEvent.VK_DOWN: 

y+=10;
break;
case KeyEvent.VK_UP:
y-=10;
break;
case KeyEvent.VK_LEFT:
x-=10;
break;
case KeyEvent.VK_RIGHT:
x+=10;
break;
default:
keyChar=e.getKeyChar();
}
//repaint();
}


});*/
}

   protected void paintComponent(Graphics g){
  super.paintComponent(g);
  g.setFont(new Font("TimesRoman",Font.PLAIN,40));
  g.drawString(String.valueOf(keyChar), x, y);
   }


@Override
public void keyPressed(KeyEvent e) {
// TODO Auto-generated method stub
switch (e.getKeyCode()){
case KeyEvent.VK_DOWN: 


y+=10;
break;
case KeyEvent.VK_UP:
y-=10;
break;
case KeyEvent.VK_LEFT:
x-=10;
break;
case KeyEvent.VK_RIGHT:
x+=10;
break;
default:
keyChar=e.getKeyChar();
}
repaint();
}


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

}


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

}
}
}

implements KeyListener了按键监听却监听不到

标签:style   color   io   os   java   ar   sp   on   c   

原文地址:http://blog.csdn.net/songjunyan/article/details/39396739

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!