[英]How can I limit JTextField input to just numbers and only 2 chars?
我正在嘗試制作一個JTextField,它將僅允許數字輸入並且僅允許兩個字符(換句話說,將僅允許數字0-99)。 到目前為止,我已經看過一些教程,並試圖將輸入限制為僅數字。 到目前為止,我的代碼存在的問題是可以接受所有關鍵輸入。 我嘗試反轉大於和小於符號,並且它完全停止接受任何輸入。 我認為問題出在關鍵字符代碼上,但是有些幫助還是對的,因為我找不到任何有用的信息(我看上去的每個地方都有針對Java的不同按鍵映射)。
if(event.getSource() == txtMasterSound)
{
if(event.getKeyCode() < 0 || event.getKeyCode() > 9)
{
System.out.println("Your input was invalid");
event.consume();
}
else
{
System.out.println("Your input was valid");
return;
}
}
至於限制字符,我真的不知道從哪里開始,所以有些指向正確方向的人也很好。
例如,一個DoumentFilter
import javax.swing.*;
import javax.swing.text.AttributeSet;
import javax.swing.text.BadLocationException;
import javax.swing.text.DocumentFilter;
import javax.swing.text.PlainDocument;
public class MyDocFilter {
private static void createAndShowGUI() {
JTextField field1 = new JTextField(10);
PlainDocument doc = (PlainDocument) field1.getDocument();
doc.setDocumentFilter(new DocumentFilter() {
private boolean isValid(String testText) {
if (testText.length() > 2) {
return false;
}
if (testText.isEmpty()) {
return true;
}
int intValue = 0;
try {
intValue = Integer.parseInt(testText.trim());
} catch (NumberFormatException e) {
return false;
}
if (intValue < 0 || intValue > 99) {
return false;
}
return true;
}
@Override
public void insertString(FilterBypass fb, int offset, String text,
AttributeSet attr) throws BadLocationException {
StringBuilder sb = new StringBuilder();
sb.append(fb.getDocument().getText(0, fb.getDocument().getLength()));
sb.insert(offset, text);
if (isValid(sb.toString())) {
super.insertString(fb, offset, text, attr);
}
}
@Override
public void replace(FilterBypass fb, int offset, int length,
String text, AttributeSet attrs) throws BadLocationException {
StringBuilder sb = new StringBuilder();
sb.append(fb.getDocument().getText(0, fb.getDocument().getLength()));
int end = offset + length;
sb.replace(offset, end, text);
if (isValid(sb.toString())) {
super.replace(fb, offset, length, text, attrs);
}
}
@Override
public void remove(FilterBypass fb, int offset, int length)
throws BadLocationException {
StringBuilder sb = new StringBuilder();
sb.append(fb.getDocument().getText(0, fb.getDocument().getLength()));
int end = offset + length;
sb.delete(offset, end);
if (isValid(sb.toString())) {
super.remove(fb, offset, length);
}
}
});
JPanel panel = new JPanel();
panel.add(field1);
JFrame frame = new JFrame("MyDocFilter");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().add(panel);
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
createAndShowGUI();
}
});
}
}
這可能有點草率,但是您可以添加一個偵聽器來檢測更改(鍵入內容時),每次鍵入內容時,您都要檢查鍵入的內容,如果不是0-9,則刪除最后一個字符,如果有更多字符然后刪除2個字符。
這可能會起作用(我還沒有嘗試過),但是我認為JFormattedTextField更專業。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.