如果无效,请删除JTextField中的最后一个击键 [英] Deleting last keystroke in JTextField if invalid

查看:125
本文介绍了如果无效,请删除JTextField中的最后一个击键的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

正在研究我的第一个程序.我想出了如何识别不想输入的字符.我想知道如何删除最后输入的字符,以便从用户的角度来看它会出现,因为只能输入数字.

Working on my 1st program. I figured out how to identify characters I do not want to be able to be inputted. I would like to know how do delete the last character entered so that from a user perspectvive it will appear as only numbers can be entered.

@Override
public void keyPressed(KeyEvent e) {
    char keyChar = e.getKeyChar();;
    char[] badCharArray = "abcdefghijklmnopqrstuvwxyz-`~!@#$%^&*()[]{}<>_+=|\"':;?/ ".toCharArray();
        for (int i = 0; i < badCharArray.length; i++) {
            if (badCharArray[i] == keyChar) {
                System.out.print(badCharArray[i] + " bad\n");
                hourlyWageInput.setBackground(Color.RED);
                } 
            }
        }

谢谢.

推荐答案

这是JTextField的创建:

Here is the creation of the JTextField:

hourlyWageInput = new JTextField("7.25");
DocumentFilter filter = new UppercaseDocumentFilter();
((AbstractDocument) hourlyWageInput.getDocument()).setDocumentFilter(filter);
hourlyWageInput.setHorizontalAlignment(JTextField.CENTER);
add(hourlyWageInput);

这是我的DocumentFilter:

Here is my DocumentFilter:

import javax.swing.text.BadLocationException;
import javax.swing.text.DocumentFilter;

public class UppercaseDocumentFilter extends DocumentFilter {

     public void replace(DocumentFilter.FilterBypass fb, int offset, int length,
          String text, javax.swing.text.AttributeSet attr)

          throws BadLocationException {
               fb.insertString(offset, text.replaceAll("\\D", ""), attr);   
     }
}

这有效,它会自动从JTextField中删除所有字母和字符.所以,谢谢,这是最确定的.

This works, automatically removing all letters and characters from the JTextField. So thank you, this is the best for sure.

但是,我想知道是否有人知道所有使用类似于"\ D"的命令的地方.我花了一段时间才找到正确的信息.

However, I was wondering if anyone knows of a place with all of the commands similar to "\D". It took me a while to find the right information.

此外,我现在拥有的代码也可以防止.成为双打时需要的类型.有什么想法吗?

Also, the code I have now also prevents . from being types which I need as I am working with doubles. Any ideas?

感谢所有帮助,令人惊讶的是我今天学到了多少.连续进行了13个小时的编码.

Thanks for all of the help, its amazing how much I have learned today. Been coding 13 hours straight.

这篇关于如果无效,请删除JTextField中的最后一个击键的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆