2013-10-06 3 views
0

) 사용자가 계산할 Jtextfield에 Double 값을 입력해야한다고 가정 해 보겠습니다.
그러나 사용자가 갑자기 1보다 많은 기간을 사용하면 NumberFormatException이 트리거되므로 문서 필터를 사용하여 추가 기간을 필터링하거나 예외를 catch하고 잘못된 입력을 사용자에게 알리는 것으로 가정합니다.문서 필터를 사용하여 여러 마침표 필터링 (

1.2.2

:

단지 숫자와 기간을 허용하도록하는 DocumentFilter를 사용하여 Currenty하지만 내 문제는 두 번째 기간

PlainDocument filter = new PlainDocument(); 
      filter.setDocumentFilter(new DocumentFilter() { 
        @Override 
        public void insertString(FilterBypass fb, int off, String str, AttributeSet attr) 
        throws BadLocationException 
        { 
        fb.insertString(off, str.replaceAll("[^0-9.]", ""), attr); 
        } 
        @Override 
        public void replace(FilterBypass fb, int off, int len, String str, AttributeSet attr) 
        throws BadLocationException 
        { 
        fb.replace(off, len, str.replaceAll("[^0-9.]", ""), attr); 
        } 
      }); 

      apm.setDocument(filter); 

잘못된 입력을 필터링하는 방법입니다

유효 INPUT : 1.22

+1

더 나은 도움을 얻기 위해 나에게 도움이되는 아이디어가 없다. [SSCCE] (http://sscce.org/), 짧고 실행 가능한 컴파일 가능 – mKorbel

+1

나는 두 번째 마침표를 허용하지 않기 위해 필터를 작성한다. . 너 뭐 해봤 니? 어떻게 작동하지 않습니까? 그리고 안녕하세요 @ mKorbel! –

+0

나 자신, 나는 기다릴거야. –

답변

0

나의 제안은 어떤 "." 이전이 삽입 전에 삽입하거나 교체하고 '기간'은 대체 될 수있는 방식으로 필터를 변경되었는지 여부를 확인하도록 당신이 무시 insertStringreplace 방법을 바꿀 수 있다는 것입니다 후속 시간에 사용자가 period 문자를 삽입하면 빈 문자열. 나는 다음과 같이 설명했다 :

@Override 
public void insertString(FilterBypass fb, int off, String str, AttributeSet attr) 
       throws BadLocationException { 
    String regExp; 
    Document doc = fb.getDocument(); 
    if(doc.getText(0, doc.getLength()).indexOf(".") == -1){ 
     regExp = "[^0-9.]"; 
    } else { 
     regExp = "[^0-9]"; 
    } 
    fb.insertString(off, str.replaceAll(regExp, ""), attr); 
} 

@Override 
public void replace(FilterBypass fb, int off, int len, String str, AttributeSet attr) 
       throws BadLocationException { 
    String regExp; 
    Document doc = fb.getDocument(); 
    if(doc.getText(0, doc.getLength()).indexOf(".") == -1){ 
     regExp = "[^0-9.]"; 
    } else { 
     regExp = "[^0-9]"; 
    } 
    fb.replace(off, len, str.replaceAll(regExp, ""), attr); 
} 

위의 코드 만 '기간'한 번만 Document에있는이 DocumentFilter로 설정 한 경우에 삽입 할 수 있도록합니다.

0

예, try catch 블록을 사용하십시오. try 블록 내에 행복한 경로 (즉, 올바른 형식의 번호)를 구현하고 catch 블록에 오류 케이스를 구현하십시오. 예를 들어, 상자를 빨간색으로 강조 표시하거나 오류 메시지를 표시하려면 catch 블록에 해당 논리를 삽입 (또는 호출)하십시오.

관련 문제