Java 有没有办法只接受 JTextField 中的数值?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/1313390/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Is there any way to accept only numeric values in a JTextField?
提问by Johanna
Is there any way to accept only numeric values in a JTextField
? Is there any special method for this?
有没有办法只接受 a 中的数值JTextField
?对此有什么特殊的方法吗?
回答by Stefan Kendall
numberField = new JFormattedTextField(NumberFormat.getInstance());
numberField = new JFormattedTextField(NumberFormat.getInstance());
回答by OscarRyz
You would like to take a look at JFormattedTextField
Formatted text fields provide a way for developers to specify the valid set of characters that can be typed in a text field
格式化文本字段为开发人员提供了一种指定可在文本字段中键入的有效字符集的方法
This is a subclass of JTextField, so you can use it like this:
这是 JTextField 的子类,因此您可以像这样使用它:
JTextField textField = new JFormattedTextField(NumberFormat.getInstance());
回答by Zed
Look at JFormattedTextField.
回答by Tom Hawtin - tackline
Although there is the pure evil JFormattedTextField
there isn't a trivial way to do it using only the Swing library. The best way to implement this sort of feature is with a DocumentFilter
.
尽管存在纯粹的邪恶,JFormattedTextField
但仅使用 Swing 库并没有一种简单的方法来做到这一点。实现此类功能的最佳方法是使用DocumentFilter
.
回答by Michal
I think it is the best solution:
我认为这是最好的解决方案:
JTextField textField = new JFormattedTextField(new MaskFormatter("###")); //
回答by Chris
回答by Andrew Thompson
This question was cited as an 'exact duplicate' of another question that has since been closed. The answers to this question were so poor that I was inspired to help out anybody that might find it later, by linking to a much better answer for this use case.
这个问题被引用为另一个已经关闭的问题的“完全重复”。这个问题的答案太糟糕了,以至于我受到启发,通过链接到此用例的更好答案来帮助以后可能会找到它的任何人。
It is an answer to the closed question& can be summed up as..
Use a JSpinner
instead.
使用 aJSpinner
代替。
回答by trashgod
Also, consider using an InputVerifier
.
另外,请考虑使用InputVerifier
.
回答by trashgod
import javax.swing.*;
import javax.swing.text.*;
public class JNumberTextField extends JTextField
{
private static final char DOT = '.';
private static final char NEGATIVE = '-';
private static final String BLANK = "";
private static final int DEF_PRECISION = 2;
public static final int NUMERIC = 2;
public static final int DECIMAL = 3;
public static final String FM_NUMERIC = "0123456789";
public static final String FM_DECIMAL = FM_NUMERIC + DOT;
private int maxLength = 0;
private int format = NUMERIC;
private String negativeChars = BLANK;
private String allowedChars = null;
private boolean allowNegative = false;
private int precision = 0;
protected PlainDocument numberFieldFilter;
public JNumberTextField()
{
this( 10, NUMERIC );
}
public JNumberTextField( int maxLen )
{
this( maxLen, NUMERIC );
}
public JNumberTextField( int maxLen, int format )
{
setAllowNegative( true );
setMaxLength( maxLen );
setFormat( format );
numberFieldFilter = new JNumberFieldFilter();
super.setDocument( numberFieldFilter );
}
public void setMaxLength( int maxLen )
{
if (maxLen > 0)
maxLength = maxLen;
else
maxLength = 0;
}
public int getMaxLength()
{
return maxLength;
}
public void setPrecision( int precision )
{
if ( format == NUMERIC )
return;
if ( precision >= 0 )
this.precision = precision;
else
this.precision = DEF_PRECISION;
}
public int getPrecision()
{
return precision;
}
public Number getNumber()
{
Number number = null;
if ( format == NUMERIC )
number = new Integer(getText());
else
number = new Double(getText());
return number;
}
public void setNumber( Number value )
{
setText(String.valueOf(value));
}
public int getInt()
{
return Integer.parseInt( getText() );
}
public void setInt( int value )
{
setText( String.valueOf( value ) );
}
public float getFloat()
{
return ( new Float( getText() ) ).floatValue();
}
public void setFloat(float value)
{
setText( String.valueOf( value ) );
}
public double getDouble()
{
return ( new Double( getText() ) ).doubleValue();
}
public void setDouble(double value)
{
setText( String.valueOf(value) );
}
public int getFormat()
{
return format;
}
public void setFormat(int format)
{
switch ( format )
{
case NUMERIC:
default:
this.format = NUMERIC;
this.precision = 0;
this.allowedChars = FM_NUMERIC;
break;
case DECIMAL:
this.format = DECIMAL;
this.precision = DEF_PRECISION;
this.allowedChars = FM_DECIMAL;
break;
}
}
public void setAllowNegative( boolean value )
{
allowNegative = value;
if ( value )
negativeChars = "" + NEGATIVE;
else
negativeChars = BLANK;
}
public boolean isAllowNegative()
{
return allowNegative;
}
public void setDocument( Document document )
{
}
class JNumberFieldFilter extends PlainDocument
{
public JNumberFieldFilter()
{
super();
}
public void insertString(int offset, String str, AttributeSet attr) throws BadLocationException
{
String text = getText(0,offset) + str + getText(offset,(getLength() - offset));
if ( str == null || text == null )
return;
for ( int i=0; i<str.length(); i++ )
{
if ( ( allowedChars + negativeChars ).indexOf( str.charAt(i) ) == -1)
return;
}
int precisionLength = 0, dotLength = 0, minusLength = 0;
int textLength = text.length();
try
{
if ( format == NUMERIC )
{
if ( ! ( ( text.equals( negativeChars ) ) && ( text.length() == 1) ) )
new Long(text);
}
else if ( format == DECIMAL )
{
if ( ! ( ( text.equals( negativeChars ) ) && ( text.length() == 1) ) )
new Double(text);
int dotIndex = text.indexOf(DOT);
if( dotIndex != -1 )
{
dotLength = 1;
precisionLength = textLength - dotIndex - dotLength;
if( precisionLength > precision )
return;
}
}
}
catch(Exception ex)
{
return;
}
if ( text.startsWith( "" + NEGATIVE ) )
{
if ( !allowNegative )
return;
else
minusLength = 1;
}
if ( maxLength < ( textLength - dotLength - precisionLength - minusLength ) )
return;
super.insertString( offset, str, attr );
}
}
}
回答by BJ Peter DeLaCruz
A quick solution:
一个快速的解决方案:
JTextField textField = new JTextField() {
public void processKeyEvent(KeyEvent ev) {
char c = ev.getKeyChar();
if (c >= 48 && c <= 57) { // c = '0' ... c = '9'
super.processKeyEvent(ev);
}
}
};
The problem with the above solution is that the user cannot use the Delete, Left Arrow, Right Arrow, or Backspace keys in the text field, so I suggest using this solution:
上述解决方案的问题在于用户无法在文本字段中使用 Delete、左箭头、右箭头或 Backspace 键,因此我建议使用此解决方案:
this.portTextField = new JTextField() {
public void processKeyEvent(KeyEvent ev) {
char c = ev.getKeyChar();
try {
// Ignore all non-printable characters. Just check the printable ones.
if (c > 31 && c < 127) {
Integer.parseInt(c + "");
}
super.processKeyEvent(ev);
}
catch (NumberFormatException nfe) {
// Do nothing. Character inputted is not a number, so ignore it.
}
}
};