我设计了一个带有一些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); } }); }更多推荐
输入文本只接受数字
发布评论