• implements KeyListener但关键监听器监听少


    今天写的游戏。主要听众,但它并不总是加入了育雏,

    我实现了接口,但不听

    后来,我发现只是没想到服用口服细致怎么称呼控制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

    }
    }
    }

    版权声明:本文博主原创文章。博客,未经同意不得转载。

  • 相关阅读:
    指针变量的值和指针变量地址
    定时备份docker容器中mysql的数据
    sql server表外键查询
    Go语言strings包基本操作
    centos安装字体库处理中文乱码
    codeforces 1610D
    汽车配件生产加工企业管理软件出售生产加工刹车盘、刹车鼓、刹车蹄、刹车片等企业通用
    关于document.onmousemove报错Invalid or unexpected token问题
    SilverLight支持的DataTable可以直接绑定
    我的工作我的状态
  • 原文地址:https://www.cnblogs.com/blfshiye/p/4784911.html
Copyright © 2020-2023  润新知