개발

JTextField 에 숫자만 입력받기

에드몽단테스 2007. 6. 10. 00:28

사용자로부터 입력을 받을 수 있도록 하는 컴포넌트들 중에서 특정한 값들이나, 특정한 포맷으로만 입력을 받고 싶을때가 있다.
그러한 방법으로 특정포맷을 지원하는 컴포넌트를 사용하거나, 필터를 이용하거나, 특정 클래스를 상속받아 확장하여 사용법이 있다.
여기에서는 텍스트필드값 중 숫자만 입력받을 수 있도록 하기 위해서 PlainDocument 클래스를 상속받아 이를 사용하여 숫자 입력만을 받겠다.

/* IntegerDocument 클래스 */
import javax.swing.text.*;
   public class IntegerDocument extends PlainDocument {

     int currentValue = 0;

     public IntegerDocument() {
     }

     public int getValue() {
       return currentValue;
     }

     public void insertString(int offset, String string,
         AttributeSet attributes) throws BadLocationException {

       if (string == null) {
         return;
       } else {
         String newValue;
         int length = getLength();
         if (length == 0) {
           newValue = string;
         } else {
           String currentContent = getText(0, length);
           StringBuffer currentBuffer =
                new StringBuffer(currentContent);
           currentBuffer.insert(offset, string);
           newValue = currentBuffer.toString();
         }
         currentValue = checkInput(newValue, offset);
         super.insertString(offset, string, attributes);
       }
     }
     public void remove(int offset, int length)
         throws BadLocationException {
       int currentLength = getLength();
       String currentContent = getText(0, currentLength);
       String before = currentContent.substring(0, offset);
       String after = currentContent.substring(length+offset,
         currentLength);
       String newValue = before + after;
       currentValue = checkInput(newValue, offset);
       super.remove(offset, length);
     }
     public int checkInput(String proposedValue, int offset)
         throws BadLocationException {
       if (proposedValue.length() > 0) {
         try {
           int newValue = Integer.parseInt(proposedValue);
           return newValue;
         } catch (NumberFormatException e) {
           throw new BadLocationException(proposedValue, offset);
         }
       } else {
         return 0;
       }
     }
   }


위의 클래스는 컴포넌트가 입력을 받을 때 숫자이면 입력을 허락하고 숫자가 아니면 삭제를 하여 숫자만 입력받을 수 있도록 한다.

위의 클래스는 다음과 같이 사용할 수 있다.

JTextField tf = new JTextField();
IntegerDocument  id = new IntegerDocument ();
tf.setDocument(id);

참고로 텍스트필드의 커서의 위치를 계산기처럼 오른쪽으로 위치하고 싶다면, 다음과 같이 할 수 있다.

tf.setHorizontalAlignment(JTextField.RIGHT);

반응형