Swing中如何忽略按键事件?

发布于 2024-12-18 15:25:22 字数 391 浏览 4 评论 0原文

我想让文本字段只接受用户的数字和退格按钮。

我添加了用于检查用户的键码的功能,但我不知道如果键码不是数字,如何停止按键事件。

我需要在函数中添加什么代码来停止事件?

 private void jTextField2KeyPressed(java.awt.event.KeyEvent evt)   
 {                                       

   if(!((evt.getKeyCode()==8) || (evt.getKeyCode()>48 && evt.getKeyCode()<57)))
   {
      //how to stop the key pressed event
   }
 }

I want to make the text field only accept numeric and backspace button from the user.

I have added the function that use to check the keycode from the user, but I don't know how to stop the key press event if the keycode is not numeric.

What code do I need to add into the function to stop the event??

 private void jTextField2KeyPressed(java.awt.event.KeyEvent evt)   
 {                                       

   if(!((evt.getKeyCode()==8) || (evt.getKeyCode()>48 && evt.getKeyCode()<57)))
   {
      //how to stop the key pressed event
   }
 }

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(6

素食主义者 2024-12-25 15:25:22

您无需搞乱 Swing 事件处理即可实现此目的。

最好的方法是使用 JFormattedTextField 代替。

有关详细信息,请参阅 Java 教程:

http://docs.oracle.com/ javase/tutorial/uiswing/components/formattedtextfield.html

You don't need to mess with the Swing event handling to achieve this.

The best way is to use a JFormattedTextField instead.

See the Java tutorial for details:

http://docs.oracle.com/javase/tutorial/uiswing/components/formattedtextfield.html

朱染 2024-12-25 15:25:22

尝试覆盖keyTyped

@Override
public void keyTyped(KeyEvent evt) {
    if (!Character.isDigit(evt.getKeyChar()) && !(evt.getKeyCode() == KeyEvent.VK_BACK_SPACE)) {
        evt.consume();
    }
}

更新:

如果您希望粘贴不起作用并强制键入输入,您可以使用以下内容。

@Override
public void keyPressed(KeyEvent evt) {
    if(evt.isControlDown() && evt.getKeyCode() == KeyEvent.VK_V) {
        evt.consume();
    }
}

Try overriding keyTyped:

@Override
public void keyTyped(KeyEvent evt) {
    if (!Character.isDigit(evt.getKeyChar()) && !(evt.getKeyCode() == KeyEvent.VK_BACK_SPACE)) {
        evt.consume();
    }
}

Update:

In case you want pasting to not work and enforce the input to be typed, you can use the following.

@Override
public void keyPressed(KeyEvent evt) {
    if(evt.isControlDown() && evt.getKeyCode() == KeyEvent.VK_V) {
        evt.consume();
    }
}
私藏温柔 2024-12-25 15:25:22

设置文本字段的 PlainDocumentDocumentFilter
样本:

    PlainDocument document = new PlainDocument();
    document.setDocumentFilter(new DocumentFilter() {

        @Override
        public void insertString(FilterBypass fb, int offset, String text, AttributeSet attrs) throws BadLocationException {
            fb.insertString(offset, filter(text), attrs);
        }

        @Override
        public void replace(FilterBypass fb, int offset, int length, String text, AttributeSet attrs) throws BadLocationException {
            fb.replace(offset, length, filter(text), attrs);
        }

        private String filter(String text) {
            StringBuilder builder = new StringBuilder(text);
            for (int i = 0; i < builder.length();) {
                if (Character.isDigit(builder.charAt(i))) {
                    i += 1;
                } else {
                    builder.deleteCharAt(i);
                }
            }
            return builder.toString();
        }
    });

    JTextField field = new JTextField(document, null, 0);

set the DocumentFilter of the PlainDocument of the text field.
Sample:

    PlainDocument document = new PlainDocument();
    document.setDocumentFilter(new DocumentFilter() {

        @Override
        public void insertString(FilterBypass fb, int offset, String text, AttributeSet attrs) throws BadLocationException {
            fb.insertString(offset, filter(text), attrs);
        }

        @Override
        public void replace(FilterBypass fb, int offset, int length, String text, AttributeSet attrs) throws BadLocationException {
            fb.replace(offset, length, filter(text), attrs);
        }

        private String filter(String text) {
            StringBuilder builder = new StringBuilder(text);
            for (int i = 0; i < builder.length();) {
                if (Character.isDigit(builder.charAt(i))) {
                    i += 1;
                } else {
                    builder.deleteCharAt(i);
                }
            }
            return builder.toString();
        }
    });

    JTextField field = new JTextField(document, null, 0);
万劫不复 2024-12-25 15:25:22

我建议您查看是否可以使用 keyPressed、KeyReleased 和 KeyTyped 事件,并查看它们是否会阻止按键到达您的程序。

您的程序可能只查找一种类型的关键事件,但您需要找出它是哪一种并使用这些事件。

I would suggest that you see if you can consume keyPressed,KeyReleased, and KeyTyped events, and see if they prevent the key reaching your program.

Your program is probably only looking out for 1 type of key event but you need to find out which one it is and consume those events.

贪恋 2024-12-25 15:25:22

你可以试试这个:

    private void txtDisplayKeyTyped(java.awt.event.KeyEvent evt) {                                          


    boolean valid = false; //some condition here
    if(!valid) evt.consume();
}

You could try this:

    private void txtDisplayKeyTyped(java.awt.event.KeyEvent evt) {                                          


    boolean valid = false; //some condition here
    if(!valid) evt.consume();
}
白色秋天 2024-12-25 15:25:22

请参阅 Limit TextField input to numeric value - 我认为这正是您所寻找的为了。

我认为您的代码不起作用的原因是 if 语句不正确并且实际上没有捕获非数字键代码。不过,我不确定,因为我自己没有看到或测试过你的代码,所以如果你真的愿意,你可以进行一些调试,但说实话,这里发布的解决方案将是最简单的。

See Limit TextField input to numeric value - I think it is exactly what you are looking for.

I think the reason your code does not work is because the if statement is incorrect and isn't actually catch non numeric key codes. Though, I'm not sure because I haven't seen or tested your code myself so you could do some debuging if you really wanted to, but to be honest the solutions posted here will be simplest.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文