简体   繁体   English

KeyEvent无法识别按下了Shift

[英]KeyEvent not recognizing that shift is pressed

I am having following problem, i am trying to restrict users to enter only alphabetical values. 我遇到以下问题,我试图限制用户仅输入字母值。 Any other value (key pressed) that is not alphabetical will throw error. 任何其他非字母值(按下键)都将引发错误。 There are however 3 exceptions, of which two are working fine. 但是,有3个例外,其中两个例外。
exception1 : Del Key exception1:删除键
exception2 : Back Key exception2:返回键
exception3 : Shift <- this one is not recognized and i am not sure why exception3:Shift <-无法识别这一点,我不确定为什么

SurnameSearch.addKeyListener(new KeyAdapter(){
        public void keyPressed(KeyEvent e){
            char ch = e.getKeyChar();
                if(Character.isAlphabetic(ch)|| (ch == KeyEvent.VK_BACK_SPACE) || (ch == KeyEvent.VK_DELETE) || (ch == KeyEvent.VK_SHIFT)){/*null*/}
                  else{
                    JOptionPane.showMessageDialog(null, "Only letters are allowed!");
                    SurnameSearch.setText(" ");
            }
        }
    });

Hints appreciated :) 提示表示赞赏:)


@MadProgrammer @MadProgrammer

Example would be, a user is requested to enter into form his surname, first name, middle name, and mobile telephone number && home phone number. 例如,要求用户输入其姓氏,名字,中间名和移动电话号码&&家庭电话号码。 So obviously we dont want numerical values in alphabetic field and vice verse :) 所以显然我们不希望在字母字段中输入数值,反之亦然:)

Don't compare the key char with key codes. 不要将键字符与键代码进行比较。 They are typically different things. 它们通常是不同的东西。

Key codes are a virtual concept used to allow for different keyboard types and input methods. 按键代码是一个虚拟概念,用于允许使用不同的键盘类型和输入方法。

Instead, use something like e.getKeyCode() == KeyEvent.VK_SHIFT . 而是使用e.getKeyCode() == KeyEvent.VK_SHIFT类的东西。

If you are trying to restrict the input to any type of text component, KeyListener is not the interface you want. 如果您试图将输入限制为任何类型的文本组件,则KeyListener不是您想要的接口。 You will want to use a DocumentFilter instead. 您将改为使用DocumentFilter This will allow y to filter text as it is input to the fields document. 这将使y在输入到字段文档中时过滤文本。

This is a better approach for a number of reasons. 由于多种原因,这是一种更好的方法。 The first is, you have no control over the order KeyListeners are notified, meaning the key stroke may have already been submitted to the text component before it reaches your listener. 第一个是,您无法控制KeyListeners的通知顺序,这意味着击键可能已在到达侦听器之前提交给了文本组件。 Secondly, if the user pastes text into your field, it will bypass the KeyListener altogether. 其次,如果用户将文本粘贴到您的字段中,它将完全绕开KeyListener

That's because the Shift key doesn't have a Unicode key character. 这是因为Shift键没有Unicode键字符。 It's probably returning KeyEvent.VK_UNDEFINED . 它可能返回KeyEvent.VK_UNDEFINED Rather, the Shift key modifies other keypresses (ie, it capitalizes them, usually). 而是, Shift键可修改其他按键(即通常将其大写)。

From the Javadoc , getKeyChar : Javadoc中getKeyChar

Returns the character associated with the key in this event. 返回与此事件中的键关联的字符。 For example, the KEY_TYPED event for shift + "a" returns the value for "A". 例如,shift +“ a”的KEY_TYPED事件返回“ A”的值。

Instead of using getKeyChar , try getKeyCode , which 而不是使用getKeyChar ,尝试getKeyCode ,这

Returns the integer keyCode associated with the key in this event. 返回与此事件中的键关联的整数keyCode。

You will probably also have to use getKeyChar for your isAlphabetic presses (if those matter to you). 您可能还需要对isAlphabetic印刷机使用getKeyChar (如果这些对您而言很重要)。


EDIT: Here's a working example: 编辑:这是一个工作示例:

public static void main(String[] args) {
    JFrame f = new JFrame();
    JButton button = new JButton("Press keys");
    button.addKeyListener(new KeyAdapter() {

        @Override
        public void keyPressed(KeyEvent ke) {
            if (ke.getKeyCode() == KeyEvent.VK_SHIFT) {
                System.out.println("You pressed Shift");
            } else {
                System.out.println("You pressed a non-Shift key");
                // [ more logic ]
            }
        }

    });
    f.add(button, BorderLayout.CENTER);
    f.pack();
    f.setVisible(true);
    f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM