栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 面试经验 > 面试问答

jTextField仅接受字母和空格

面试问答 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

jTextField仅接受字母和空格

使用一个

documentFilter
,这是我制作的一个示例,它将仅接受字母字符和空格:

import javax.swing.Jframe;import javax.swing.JTextField;import javax.swing.SwingUtilities;import javax.swing.text.Abstractdocument;import javax.swing.text.AttributeSet;import javax.swing.text.BadLocationException;import javax.swing.text.documentFilter;import javax.swing.text.documentFilter.FilterBypass;public class Test {    public Test() {        initComponents();    }    public static void main(String[] args) {        SwingUtilities.invokeLater(new Runnable() { @Override public void run() {     new Test(); }        });    }    private void initComponents() {        Jframe frame = new Jframe();        frame.setDefaultCloseOperation(Jframe.EXIT_ON_CLOSE);        JTextField jtf = new JTextField();        //add filter to document        ((Abstractdocument) jtf.getdocument()).setdocumentFilter(new MydocumentFilter());        frame.add(jtf);        frame.pack();        frame.setVisible(true);    }}class MydocumentFilter extends documentFilter {    @Override    public void replace(FilterBypass fb, int i, int i1, String string, AttributeSet as) throws BadLocationException {        for (int n = string.length(); n > 0; n--) {//an inserted string may be more than a single character i.e a copy and paste of 'aaa123d', also we iterate from the back as super.XX implementation will put last insterted string first and so on thus 'aa123d' would be 'daa', but because we iterate from the back its 'aad' like we want char c = string.charAt(n - 1);//get a single character of the string System.out.println(c); if (Character.isAlphabetic(c) || c == ' ') {//if its an alphabetic character or white space     super.replace(fb, i, i1, String.valueOf(c), as);//allow update to take place for the given character } else {//it was not an alphabetic character or white space     System.out.println("Not allowed"); }        }    }    @Override    public void remove(FilterBypass fb, int i, int i1) throws BadLocationException {        super.remove(fb, i, i1);    }    @Override    public void insertString(FilterBypass fb, int i, String string, AttributeSet as) throws BadLocationException {        super.insertString(fb, i, string, as);    }}


转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/507174.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号