今天写游戏,按键监听却是总也添加不上去苦思冥想,
我实现了接口但是监听不到
后来才发现我只是实现了结口却没调用它仔细想来就在控件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
}
}
}