JTextField limit input to certains chars only

血红的双手。 提交于 2019-12-19 19:52:38

问题


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?


回答1:


maybe better would be use DocumentFilter with Pattern,




回答2:


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



来源:https://stackoverflow.com/questions/7658324/jtextfield-limit-input-to-certains-chars-only

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