Java中的文本框

时间:2011-02-20 18:00:38

标签: java

我想创建一个只接受整数的TextBox类。

我该怎么做?

Thanx all。

3 个答案:

答案 0 :(得分:2)

我认为你的意思是Java Swing和桌面。

使用JTextField类;你不需要创建一个新类。你可能“想”,但我认为没有必要这样做。您需要的行为不在JTextField类中。扩展现有类应该表示不同的行为。您可以通过添加适当的侦听器来获得所需内容。

创建新课程可能会产生危害。充其量,它会增加您的维护负担;在最坏的情况下,你会错的。

编写一个监听器以确保只允许整数。

http://download.oracle.com/javase/tutorial/uiswing/components/textfield.html

答案 1 :(得分:1)

我想你正在寻找这样的东西(来源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();
        }
      }
    }
  }
}

答案 2 :(得分:0)

  

但我想制作一个新的文本框类..

它被称为JFormattedTextField。只需使用适当的面具,它只接受数字。

或者另一种方法是使用DocumentFilter