2015-01-08 9 views
1

사용자가 특정 문자를 채울 때 자동으로 문자를 추가하는 방법을 만들 수 있습니다.사용자가 값을 입력하는 동안 문자 추가

12 자 길이의 코드를 입력해야한다고 가정 해 봅시다.
enter image description here

네 번째 문자를 전달할 때마다 대시를 추가해야합니다. (4-5,8-9) 총 2 개의 대시.

enter image description here

나는 어디서부터 시작 자바에 새로운 조금 그래서 나도 몰라입니다.

미리 감사드립니다. 당신이 입력 마스크 정의 할 수있는

+0

을 추가하고 키를 누를 때의 코드에는 것 'if (Textbox.length % 4 == 0) {Textbox.Text + = '-'; }'(매우 간단하게) KeyPress 이벤트는 여기에있는 것처럼 보입니다. http://stackoverflow.com/questions/24018373/is-there-an-on-change-for-java –

답변

4

사용하십시오 JFormattedTextField

JFormattedTextField textField = new JFormattedTextField(); 
textField.setFormatterFactory(new DefaultFormatterFactory(new MaskFormatter("HHHH-HHHH-HHHH"))); 

편집의 OnChange/키 누름에 대한 이벤트 만들기 작업 예를

public class SimpleInputMask { 

    private static void createAndShowGUI() { 
     JFrame frame = new JFrame("MaskFormatteExample"); 
     frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); 
     JPanel panel = new JPanel(); 
     JLabel label = new JLabel("input: "); 
     panel.add(label); 

     // define the text field with an input mask 
     JFormattedTextField textField = new JFormattedTextField(); 
     textField.setFont(new Font(Font.MONOSPACED, Font.PLAIN, 14)); 
     try { 
      String inputMask = "HHHH-HHHH-HHHH"; 
      textField.setFormatterFactory(new DefaultFormatterFactory(new MaskFormatter(inputMask))); 
     } catch (ParseException ex) { 
      // will be raised if the inputMask cannot be parsed 
      // add your own exception handling here 
     } 

     panel.add(textField); 

     frame.add(panel); 
     frame.pack(); 
     frame.setVisible(true); 
    } 

    public static void main(String[] args) { 
     SwingUtilities.invokeLater(new Runnable() { 
      @Override 
      public void run() { 
       createAndShowGUI(); 
      } 
     }); 
    } 
} 
+0

Nice. 나는 그런 존재가 있는지조차 몰랐다. 그러나 OP는 12자를 필요로합니다. 아마도 "#### - #### - ####"'또는 "AAAA-AAAA-AAAA"' –

+0

@tobias_k 12 자리로 마스크를 수정합니다. – SubOptimal

+0

jpanel에서 스윙 구성 요소를 사용합니다.이 코드는 txtfield를 시작하거나 try-catch 클래스의 시작 부분에 넣으시겠습니까? – Lobato

관련 문제