Text Box in Java
I want to make a T开发者_开发百科extBox class which only accepts integers.
How can i do it?
Thanx all.
I'll assume that you mean Java Swing and desktop.
Use a JTextField class; you need not create a new class. You may "wanna", but I'm arguing that there's no need to do it. The behavior you need doesn't reside in the JTextField class. Extending an existing class should mean different behavior. You can get what you want by adding the appropriate Listener.
Creating a new class may turn out to be harmful. At best, it increases your maintenance burden; at worst, you'll get it wrong.
Write a Listener to ensure that only integers are allowed.
http://download.oracle.com/javase/tutorial/uiswing/components/textfield.html
I suppose you are looking for something like this (Source java2s.com):
import java.awt.Toolkit;
import javax.swing.JTextField;
import javax.swing.text.AttributeSet;
import javax.swing.text.BadLocationException;
import javax.swing.text.Document;
import javax.swing.text.PlainDocument;
/**
* This class is a <CODE>TextField</CODE> that only allows integer
* values to be entered into it.
*
* @author <A HREF="mailto:colbell@users.sourceforge.net">Colin Bell</A>
*/
public class IntegerField extends JTextField
{
/**
* Default ctor.
*/
public IntegerField()
{
super();
}
/**
* Ctor specifying the field width.
*
* @param cols Number of columns.
*/
public IntegerField(int cols)
{
super(cols);
}
/**
* Retrieve the contents of this field as an <TT>int</TT>.
*
* @return the contents of this field as an <TT>int</TT>.
*/
public int getInt()
{
final String text = getText();
if (text == null || text.length() == 0)
{
return 0;
}
return Integer.parseInt(text);
}
/**
* Set the contents of this field to the passed <TT>int</TT>.
*
* @param value The new value for this field.
*/
public void setInt(int value)
{
setText(String.valueOf(value));
}
/**
* Create a new document model for this control that only accepts
* integral values.
*
* @return The new document model.
*/
protected Document createDefaultModel()
{
return new IntegerDocument();
}
/**
* This document only allows integral values to be added to it.
*/
static class IntegerDocument extends PlainDocument
{
public void insertString(int offs, String str, AttributeSet a)
throws BadLocationException
{
if (str != null)
{
try
{
Integer.decode(str);
super.insertString(offs, str, a);
}
catch (NumberFormatException ex)
{
Toolkit.getDefaultToolkit().beep();
}
}
}
}
}
But i wanna make a new text box class..
It is called a JFormattedTextField. Just use the appropriate mask and it will only accept numbers.
Or the other approach is to use a DocumentFilter.
精彩评论