开发者

JTextField limit input to certains chars only

开发者 https://www.devze.com 2023-04-11 09:07 出处:网络
i\'d like to create JTextField with input characters limited to someting like \"abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVXYWZZ0123456789+&@#/%?=~_-|!:,.;\"

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' && goodcha开发者_如何学Crs.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?


maybe better would be use DocumentFilter with Pattern,


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

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号