Deleting last keystroke in JTextField if invalid

守給你的承諾、 提交于 2019-12-11 06:37:28

问题


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);
                } 
            }
        }

Thanks.


回答1:


The easiest way to do this is simply to use a JFormattedTextField instead of a JTextField.

NumberFormat format = NumberFormat.getNumberInstance();
format.setMinimumFractionDigits(2); // eventually maximum fraction digits

JFormattedTextField fld = new JFormattedTextField(format);



回答2:


You should avoid keyListeners in this case. What happens if the user pastes text into field. The keyListener will not be notified, allowing invalid characters to be inserted.

You're better of using DocumentFilter to filter out any invalid characters you don't want.

Take a look at Implementing a DocumentFilter for more information and DocumentFilter for some nice examples




回答3:


Simply set it's text to be the current text, without the character before the caret position


    @Override
    public void keyReleased(KeyEvent paramKeyEvent) {
        char keyChar = paramKeyEvent.getKeyChar();
        char[] badCharArray = "abcdefghijklmnopqrstuvwxyz-`~!@#$%^&*()[]{}<>_+=|\"':;?/ ".toCharArray();
            for (int i = 0; i < badCharArray.length; i++) {
                if (badCharArray[i] == keyChar) {
                    int caret = field.getCaretPosition()-1;
                    System.out.print(badCharArray[i] + " bad\n");
                    field.setText(field.getText().substring(0, caret) + 
                            field.getText().substring(caret+1));
                    field.setCaretPosition(caret);
                    } 
            }
    }

Took out the setting it to red, as if you're going to auto-correct it, no point in having that there (maybe set it to show red for one second?)


Actually, the only issue with that is that if they hold in an invalid key, it only deletes the last one; the following should work a lot better, and won't shift the caret :P

        boolean held = false;
        private int oldCaret = 1;
        @Override
        public void keyPressed(KeyEvent e) {
            if(! held) {
                oldCaret=field.getCaretPosition();
                System.out.println(oldCaret);
            }
            held = true;

        }
        @Override
        public void keyReleased(KeyEvent paramKeyEvent) {
            char keyChar = paramKeyEvent.getKeyChar();
            char[] badCharArray = "abcdefghijklmnopqrstuvwxyz-`~!@#$%^&*()[]{}<>_+=|\"':;?/ ".toCharArray();
            for (int i = 0; i < badCharArray.length; i++) {
                if(field.getText().contains(badCharArray[i]+"")) {
                    field.setText(field.getText().replace(badCharArray[i]+"", ""));
                    field.setCaretPosition(oldCaret);
                }
            }

            held=false;
        }



回答4:


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);

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);   
     }
}

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

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?

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



来源:https://stackoverflow.com/questions/11836699/deleting-last-keystroke-in-jtextfield-if-invalid

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!