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

Jtextfield和keylistener

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

Jtextfield和keylistener

不要

KeyListener
在文本组件上使用,存在一系列问题(未通知,突变异常,当用户将某些内容粘贴到字段时未通知),相反,您应该使用
documentFilter

例如…

import java.awt.EventQueue;import java.awt.GridBagLayout;import javax.swing.Jframe;import javax.swing.JTextField;import javax.swing.UIManager;import javax.swing.UnsupportedLookAndFeelException;import javax.swing.text.Abstractdocument;import javax.swing.text.AttributeSet;import javax.swing.text.BadLocationException;import javax.swing.text.documentFilter;public class TextFieldExample {    public static void main(String[] args) {        new TextFieldExample();    }    public TextFieldExample() {        EventQueue.invokeLater(new Runnable() { @Override public void run() {     try {         UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());     } catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {     }     JTextField field = new JTextField(20);     ((Abstractdocument)field.getdocument()).setdocumentFilter(new ExampleExpandingdocumentFilter());     Jframe frame = new Jframe("Testing");     frame.setDefaultCloseOperation(Jframe.EXIT_ON_CLOSE);     frame.setLayout(new GridBagLayout());     frame.add(field);     frame.pack();     frame.setLocationRelativeTo(null);     frame.setVisible(true); }        });    }    public class ExampleExpandingdocumentFilter extends documentFilter {        @Override        public void insertString(FilterBypass fb, int offset, String text, AttributeSet attr) throws BadLocationException { System.out.println("I" + text); super.insertString(fb, offset, text, attr);        }        @Override        public void replace(FilterBypass fb, int offset, int length, String text, AttributeSet attrs) throws BadLocationException { if ("e".equalsIgnoreCase(text)) {     text = "example"; } super.replace(fb, offset, length, text, attrs);         }    }}


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

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

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