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?

kleopatra
  • 51,061
  • 28
  • 99
  • 211
UnableToLoad
  • 315
  • 6
  • 18
  • 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 - DocumentFilter – kleopatra Oct 05 '11 at 09:44

2 Answers2

7

maybe better would be use DocumentFilter with Pattern,

mKorbel
  • 109,525
  • 20
  • 134
  • 319
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

kleopatra
  • 51,061
  • 28
  • 99
  • 211
Xavjer
  • 8,838
  • 2
  • 22
  • 42
  • 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("********"); – Xavjer Oct 05 '11 at 08:44
  • 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? – UnableToLoad Oct 05 '11 at 09:13
  • well if you make 20 *s, you should be able to enter 1-20chars – Xavjer Oct 05 '11 at 09:29
  • 2
    no, that's not what MaskFormatter is meant for: "specifies exactly which characters are valid in _each position_ of the field's text" – kleopatra Oct 05 '11 at 09:39
  • 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. – Xavjer Oct 05 '11 at 09:41
  • -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 alternative – kleopatra Oct 05 '11 at 15:05