输入文本只接受数字

编程入门 行业动态 更新时间:2024-10-27 16:38:15
本文介绍了输入文本只接受数字的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我设计了一个带有一些JTextFields的小摆动GUI,但是它有一个validateVariables方法,它必须验证接口内的所有字段,有一个JTextField调用(IP)必须只接受int变量我该如何设置它这样吗?

I desinged a little swing GUI that has some JTextFields, but it has a validateVariables method that has to validate all the fields that are inside the interface, there's one JTextField called (IP) must accept only int Variables how can i set it up like that?

PS JTextfield是用nette工具创建的。

P.S the JTextfield was created it in netbeans with the palete tool.

推荐答案

这是JTextField的javadoc docs.oracle/javase/7/docs/api/javax/swing/JTextField.html

This is the javadoc of JTextField docs.oracle/javase/7/docs/api/javax/swing/JTextField.html

有示例

public class UpperCaseField extends JTextField { public UpperCaseField(int cols) { super(cols); } protected Document createDefaultModel() { return new UpperCaseDocument(); } static class UpperCaseDocument extends PlainDocument { public void insertString(int offs, String str, AttributeSet a) throws BadLocationException { if (str == null) { return; } char[] upper = str.toCharArray(); for (int i = 0; i < upper.length; i++) { upper[i] = Character.toUpperCase(upper[i]); } super.insertString(offs, new String(upper), a); } } }

此示例更改所有用户输入大写。 只需修改insertString方法,删除所有非数字字符,即可使文本字段仅接受数字。

This example changes all user input to upper case. Just modify the insertString method, remove all non-digit characters, you can make your text field accept digits only.

示例:

public void insertString(int offs, String str, AttributeSet a) throws BadLocationException { if (str == null) { return; } super.insertString(offs, str.replaceAll("[^0-9]", ""), a); }

----编辑----

---- EDIT ----

正如@MadProgrammer所说,DocumentFilter是另一种方法,例如:

As @MadProgrammer said, DocumentFilter is another way to do so, for example:

Document document = someJTextField.getDocument(); if (document instanceof AbstractDocument) { ((AbstractDocument) doc).setDocumentFilter(new DocumentFilter() { public void insertString(DocumentFilter.FilterBypass fb, int offset, String str, AttributeSet a) throws BadLocationException { fb.insertString(offset, str.replaceAll("[^0-9]", ""), a); } }); }

更多推荐

输入文本只接受数字

本文发布于:2023-11-23 14:54:52,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1621856.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:文本   数字

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!