Java Swing 防止键入手Key 的实现方法

 

实现思路,启动一个线程每隔0.1秒去比较文本里字符长度变化,如果文本变长了,这个情况间隔时间超过2秒,则认为是人工键入。

对于字符串较多,且包含数字和字母的情况,比较适用。

 

class KeyCodeMonitorThread extends Thread
    {
        private long lasttxtfield1InPutTime = 0;
        private long lastheheTxtFdInPutTime = 0;
        
        private int lasttxtfield1InPutLen = 0;
        private int lastheheTxtFdInPutLen = 0;
            
        @Override
        public void run()
        {
            
            while (m_bIsAliveFlag)
            {
                
                if (txtfield1.getText().length() > lasttxtfield1InPutLen && 
                        lasttxtfield1InPutTime > 0 && System.currentTimeMillis() - lasttxtfield1InPutTime > 3000)
                {
                    txtfield1.setText("");
                    showWarningDialog("请扫描标签验证!而不是键入.");
                }
                
                if (heheTxtFd.getText().length() > lastheheTxtFdInPutLen && 
                        lastheheTxtFdInPutTime > 0 && System.currentTimeMillis() - lastheheTxtFdInPutTime > 3000)
                {
                    heheTxtFd.setText("");
                    showWarningDialog("请扫描标签验证!而不是键入.");
                }
                
                if (txtfield1.getText().length() == 0)
                {
                    lasttxtfield1InPutTime = 0;
                    lasttxtfield1InPutLen = 0;
                }
                else if (txtfield1.getText().length() > lasttxtfield1InPutLen)
                {
                    lasttxtfield1InPutLen = txtfield1.getText().length();
                }
                
                if (heheTxtFd.getText().length() == 0)
                {
                    lastheheTxtFdInPutTime = 0;
                    lastheheTxtFdInPutLen = 0;
                }
                else if (heheTxtFd.getText().length() > lastheheTxtFdInPutLen)
                {
                    lastheheTxtFdInPutLen = heheTxtFd.getText().length();
                }
                
                if (0 == lasttxtfield1InPutTime && txtfield1.getText().length() > 0)
                {
                    lasttxtfield1InPutTime = System.currentTimeMillis();
                }
                
                if (0 == lastheheTxtFdInPutTime && heheTxtFd.getText().length() > 0)
                {
                    lastheheTxtFdInPutTime = System.currentTimeMillis();
                }
                
                try {
                        Thread.sleep(100);
                    } 
                catch (InterruptedException e) 
                    {
                        e.printStackTrace();
                    }
            }
        }
        
    } 

 

posted on 2023-02-14 17:29  皖南  阅读(19)  评论(0)    收藏  举报