JFormattedTextFiled仅限制为0或1 [英] JFormattedTextFiled limit only to 0 or 1
本文介绍了JFormattedTextFiled仅限制为0或1的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我要限制哪些字符,用户应该被允许在输入文本字段。如何限制JFormattedTextField上只接受8位的0或1?
I want to limit the what characters the user should be allowed to type in a text field. How can I limit JFormattedTextField to accept only 8 digits of either 0 or 1?
推荐答案
使用的DocumentFilter 与模式的的JTextField
,那么也许使用有不要求的JFormattedTextField
Use DocumentFilter with Pattern for JTextField
, then maybe there isn't required to use JFormattedTextField
一个示例程序来帮助您的原因:
A sample program to help your cause :
import java.awt.Toolkit;
import javax.swing.JFrame;
import javax.swing.JPanel;
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;
public class TextFieldLimit
{
private void createAndDisplayGUI()
{
JFrame frame = new JFrame("JTextField Limit");
frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
frame.setLocationByPlatform(true);
JPanel contentPane = new JPanel();
JTextField tfield = new JTextField(10);
/*
* Here we are using Document Filter
* to specify the size of the content
* i.e. 8 in your case.
*/
((AbstractDocument)tfield.getDocument()).setDocumentFilter(
new DocumentLimitAndInput(8));
contentPane.add(tfield);
frame.getContentPane().add(contentPane);
frame.pack();
frame.setVisible(true);
}
public static void main(String... args)
{
SwingUtilities.invokeLater(new Runnable()
{
public void run()
{
new TextFieldLimit().createAndDisplayGUI();
}
});
}
}
class DocumentLimitAndInput extends DocumentFilter
{
private int maxCharacters;
public DocumentLimitAndInput(int size)
{
maxCharacters = size;
}
public void insertString(FilterBypass fb, int offset
, String text, AttributeSet aset)
throws BadLocationException
{
int size = fb.getDocument().getLength() + text.length();
/*
* If the size is less than or equal to the permissible value
* and the input character is either 0 or 1, only in that
* case we will allow it to go through, else a BEEP
* sound is what a user will hear :-)
*/
if (size <= maxCharacters && (text.equals("0") || text.equals("1")))
super.insertString(fb, offset, text, aset);
else
Toolkit.getDefaultToolkit().beep();
}
public void replace(FilterBypass fb, int offset, int length
, String text, AttributeSet aset)
throws BadLocationException
{
int size = fb.getDocument().getLength() + text.length();
/*
* If the size is less than or equal to the permissible value
* and the input character is either 0 or 1, only in that
* case we will allow it to go through, else a BEEP
* sound is what a user will hear :-)
*/
if (size <= maxCharacters && (text.equals("0") || text.equals("1")))
super.replace(fb, offset, length, text, aset);
else
Toolkit.getDefaultToolkit().beep();
}
}
这篇关于JFormattedTextFiled仅限制为0或1的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文