JTextField只允许输入数字和字母

叶恩
2023-12-01
JTextField timeText = new JTextField(2);
timeText.addKeyListener(new KeyListener() {
	@Override
	public void keyTyped(KeyEvent e) {

	}

	@Override
	public void keyPressed(KeyEvent e) {

	}

	@Override
	public void keyReleased(KeyEvent e) {
		Object o = e.getSource();
		if (o instanceof JTextField) {
			char keyCh = e.getKeyChar();

			Pattern pat = Pattern.compile("[0-9]|[a-z]|[A-Z]");
			if (!pat.matcher(String.valueOf(keyCh)).matches()) {
				if (keyCh != ' ')   //回车字符
					e.setKeyChar('\0');
			}
		}
	}
});

JAVA SWING中JTextField限制只能输入数字

import java.awt.Toolkit;
import javax.swing.text.AttributeSet;
import javax.swing.text.BadLocationException;
import javax.swing.text.PlainDocument;

public class NumberDocument extends PlainDocument {
    public NumberDocument() {
    }

    public void insertString(int var1, String var2, AttributeSet var3) throws BadLocationException {
        if (this.isNumeric(var2)) {
            super.insertString(var1, var2, var3);
        } else {
            Toolkit.getDefaultToolkit().beep();
        }

    }

    private boolean isNumeric(String var1) {
        try {
            Long.valueOf(var1);
            return true;
        } catch (NumberFormatException var3) {
            return false;
        }
    }
}

使用的时候,调用JTextFile的setDocument将NumberDocument设置好就可以了。

JTextField jtextField = new JTextField();
jtextField.setDocument(new NumberDocument());

 类似资料: