JTextField limit input to certains chars only
Asked Answered
D

2

5

i'd like to create JTextField with input characters limited to someting like "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVXYWZZ0123456789+&@#/%?=~_-|!:,.;" so i tried overriding

public class CustomJTextField extends JTextField {  
String goodchars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVXYWZZ0123456789+&@#/%?=~_-|!:,.;";

//... my class body ...//

@Override
public void processKeyEvent(KeyEvent ev) {
    if(c != '\b' && goodchars.indexOf(c) == -1 ) {
        ev.consume();
        return;
    }
    else 
        super.processKeyEvent(ev);}}

but it isn't what i want because user cannot ctrl-c ctrl-v ctrl-x any more... so i addeded

&& ev.getKeyCode() != 17 && ev.getKeyCode() !=67 && ev.getKeyCode() != 86 && ev.getKeyCode() !=0 &&

to the if condition, but now the user can paste inappropriate input, ie '(' or '<', without any problem... what can i do?

Devalue answered 5/10, 2011 at 8:0 Comment(1)
actually, there is rarely a need to twiddle with key events. If it appears like it's needed, chances are high that something if wrong :-) @mKorbel has the answer - DocumentFilterDisadvantage
E
7

maybe better would be use DocumentFilter with Pattern,

Echidna answered 5/10, 2011 at 8:22 Comment(0)
B
3

Try a JFormattedTextField and use

MaskFormatter mf = new MaskFormatter();
mf.setValidCharacters("abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVXYWZZ0123456789+&@#/%?=~_-|!:,.;");
JFormattedTextField textField = new JFormattedTextField(mf);

Edit: Sorry, that was the wrong code, here's the working one

Buckden answered 5/10, 2011 at 8:8 Comment(6)
while creating a MaskFormatter, you must give him the length of the string you want. For a String with a length of 8 for example: mf = new MaskFormatter("********");Buckden
that's good, but i need to limit only which chars are inserted, not how many (ie 1 char is ok, but also 20chars), how can i achieve this?Devalue
well if you make 20 *s, you should be able to enter 1-20charsBuckden
no, that's not what MaskFormatter is meant for: "specifies exactly which characters are valid in each position of the field's text"Disadvantage
I know that the main use of the maskformatter is not the one unabletoload wants, but: it can be used to do exactly what he wants. if you use textField.getText() you will get the text entered. And you can only put in the values specified, exactly what he actually wants.Buckden
-1 obviously not without that unnaturally long fake-mask ;-) Dont tweak classes into usage they are not intented for, especially not if there a clean alternativeDisadvantage

© 2022 - 2024 — McMap. All rights reserved.