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

Java 将JTextField输入限制为整数

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

Java 将JTextField输入限制为整数

请勿为此使用KeyListener,因为你会错过很多内容,包括粘贴文本。同样,KeyListener是一个非常低级的构造,因此在Swing应用程序中应避免使用它。

SO上已经多次描述了该解决方案:使用documentFilter。这个站点上有几个示例,其中一些是我写的。

例如:using-documentfilter-filterbypass

同样对于教程帮助,请查看:实现documentFilter。

编辑

例如:

import javax.swing.JOptionPane;import javax.swing.JPanel;import javax.swing.JTextField;import javax.swing.text.AttributeSet;import javax.swing.text.BadLocationException;import javax.swing.text.document;import javax.swing.text.documentFilter;import javax.swing.text.Plaindocument;public class DocFilter {   public static void main(String[] args) {      JTextField textField = new JTextField(10);      JPanel panel = new JPanel();      panel.add(textField);      Plaindocument doc = (Plaindocument) textField.getdocument();      doc.setdocumentFilter(new MyIntFilter());      JOptionPane.showMessageDialog(null, panel);   }}class MyIntFilter extends documentFilter {   @Override   public void insertString(FilterBypass fb, int offset, String string,         AttributeSet attr) throws BadLocationException {      document doc = fb.getdocument();      StringBuilder sb = new StringBuilder();      sb.append(doc.getText(0, doc.getLength()));      sb.insert(offset, string);      if (test(sb.toString())) {         super.insertString(fb, offset, string, attr);      } else {         // warn the user and don't allow the insert      }   }   private boolean test(String text) {      try {         Integer.parseInt(text);         return true;      } catch (NumberFormatException e) {         return false;      }   }   @Override   public void replace(FilterBypass fb, int offset, int length, String text,         AttributeSet attrs) throws BadLocationException {      document doc = fb.getdocument();      StringBuilder sb = new StringBuilder();      sb.append(doc.getText(0, doc.getLength()));      sb.replace(offset, offset + length, text);      if (test(sb.toString())) {         super.replace(fb, offset, length, text, attrs);      } else {         // warn the user and don't allow the insert      }   }   @Override   public void remove(FilterBypass fb, int offset, int length)         throws BadLocationException {      document doc = fb.getdocument();      StringBuilder sb = new StringBuilder();      sb.append(doc.getText(0, doc.getLength()));      sb.delete(offset, offset + length);      if (test(sb.toString())) {         super.remove(fb, offset, length);      } else {         // warn the user and don't allow the insert      }   }}

为什么这很重要?

  • 如果用户使用复制和粘贴将数据插入文本组件怎么办?KeyListener可以错过吗?
  • 你似乎希望检查数据是否可以表示int。如果他们输入了不合适的数字数据怎么办?
  • 如果要允许用户以后输入重复数据怎么办?用科学计数法?


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

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

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