• java事件处理4(焦点,键盘


    FocusEvent焦点事件

    接口

    addFocusListener(FocusListener listener)

    有两个方法

    public void focusGains(FocusEvent e)
    public void focusLost(FocusEvent e)

    测试代码

    class MyWin extends JFrame{
        JTextField text1,text2;
        JButton button1,button2;
        MyWin(){
            init();
            setVisible(true);
            setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        }
        void init(){
            text1=new JTextField(8);
            add(text1);
            setLayout(new FlowLayout());
            FocusPolice focusPolice1=new FocusPolice();
            text1.addFocusListener(focusPolice1);
            add(new JButton("click"));
        }
    }
    
    class FocusPolice implements FocusListener{
        public void focusGained(FocusEvent e){
            System.out.print("11");
        }
        public void focusLost(FocusEvent e){
            System.out.print("22");
        }
    }

    键盘事件

    addKeyLIstener(KeyEvent e)

    KeyListener 有三个接口

    publice void keyPressed(KeyEvent e)//按下键盘
    publice void keyReleased(KeyEvent e)//释放键盘
    publice void keyTyped(KeyEvent e)//一套动作

    KeyEvent有两个方法

    getKeyCode()//返回一个键码值,但不知道我总是返回0
    getKeyChar()//返回键上的字符

    一个自动跳文本框的代码

    class MyWin extends JFrame{
        JTextField text[]=new JTextField[3];
        JButton button1,button2;
        MyWin(){
            init();
            setVisible(true);
            setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        }
        void init(){
            setLayout(new FlowLayout());
            KeyPolice keyPolice1=new KeyPolice();
            for(int i=0;i<3;i++){
                text[i]=new JTextField(8);
                text[i].addKeyListener(keyPolice1);
                text[i].addFocusListener(keyPolice1);
                add(text[i]);
            }
            text[1].requestFocusInWindow();
            add(button1=new JButton("click"));
        }
    }
    
    class KeyPolice implements KeyListener,FocusListener{
        public void keyPressed(KeyEvent e){}
        public void keyReleased(KeyEvent e){}
        public void keyTyped(KeyEvent e){
            JTextField text1=(JTextField)e.getSource();
            if(text1.getText().length()>=6)//有7个才会跳
                text1.transferFocus();//跳函数
        }
        public void focusGained(FocusEvent e){
    //        JTextField text=(JTextField)e.getSource();//看起来没有用
    //        text.setText(null);
        }
        public void focusLost(FocusEvent e){}
    }
  • 相关阅读:
    Webpack配置开发环境总结
    vue2.0 引入font-awesome
    vue-cli 脚手架项目简介(一)
    CSS3伪类与伪元素的区别及注意事项
    页面滚动到可视区域执行操作
    56. 合并区间
    <leetcode c++>卖股票系列
    面试题 16.01. 交换数字
    542. 01 矩阵
    <leetcode c++> 445. 两数相加 II
  • 原文地址:https://www.cnblogs.com/vhyc/p/5995103.html
Copyright © 2020-2023  润新知