今天写的游戏。主要听众,但它并不总是加入了育雏,
我实现了接口,但不听
后来,我发现只是没想到服用口服细致怎么称呼控制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
}
}
}
版权声明:本文博主原创文章。博客,未经同意不得转载。