2016-01-19 11 views
0

Я пытаюсь использовать DocumentListener на нескольких JTextFields. Мне нужно знать, какой textField входит в DocumentEvent, чтобы я мог выполнять некоторые конкретные процессы. Ниже приведено то, как я кодировал DocumentListener и один из установленных JTextFields [благодаря этому примеру: How to get JTextField name in which is Document placed?] (мой текстField объявлен в более высокой области).Как узнать, что JTextField входит в DocumentListener

Как исправить это?

final DocumentListener documentListener = new DocumentListener() { 
     @Override 
     public void changedUpdate(DocumentEvent documentEvent) { 
      printIt(documentEvent); 
      } 
      @Override 
     public void insertUpdate(DocumentEvent documentEvent) { 
      printIt(documentEvent); 
      } 
      @Override 
     public void removeUpdate(DocumentEvent documentEvent) { 
      printIt(documentEvent); 
      } 
      private void printIt(DocumentEvent documentEvent) { 
      final DocumentEvent.EventType type = documentEvent.getType(); 
      String typeString = null; 
      final JTextField textField = (JTextField) documentEvent.getDocument().getProperty("parent"); 
      if (type.equals(DocumentEvent.EventType.CHANGE)) { 
       typeString = "(parent: " + textField + ") Change"; 
      } else if (type.equals(DocumentEvent.EventType.INSERT)) { 
       typeString = "(parent: " + textField + ") Insert"; 
      } else if (type.equals(DocumentEvent.EventType.REMOVE)) { 
       typeString = "(parent: " + textField + ") Remove"; 
      } 
      System.out.print("Type : " + typeString); 
      final Document source = documentEvent.getDocument(); 
      final int length = source.getLength(); 
      System.out.println("Length: " + length); 
      } 
     }; 

Мой JTextField кодируется как следующее ...

textFieldFencing_LC1 = new JTextField(); 
    textFieldFencing_LC1.setHorizontalAlignment(SwingConstants.CENTER); 
    textFieldFencing_LC1.setFont(new Font("Tahoma", Font.PLAIN, 9)); 
    textFieldFencing_LC1.setColumns(10); 
    textFieldFencing_LC1.setBounds(234, 535, 85, 14); 
    panelLC.add(textFieldFencing_LC1); 
    textFieldFencing_LC1.getDocument().addDocumentListener(documentListener); 
    textFieldFencing_LC1.getDocument().putProperty("parent",textFieldFencing_LC1); 

Выход я хочу должен выглядеть следующим образом

Type : (parent: textFieldFencing_LC1) InsertLength: 1 
Type : (parent: textFieldFencing_LC1) InsertLength: 1 

Выходной сигнал я получаю выглядит так ...

Type : (parent: javax.swing.JTextField[,234,535,85x14,layout=javax.swing.plaf.basic.BasicTextUI$UpdateHandler,alignmentX=0.0,alignmentY=0.0,bo[email protected]384cdfdd,flags=296,maximumSize=,minimumSize=,preferredSize=,caretColor=sun.swing.PrintColorUIResource[r=51,g=51,b=51],disabledTextColor=javax.swing.plaf.ColorUIResource[r=184,g=207,b=229],editable=true,margin=javax.swing.plaf.InsetsUIResource[top=0,left=0,bottom=0,right=0],selectedTextColor=sun.swing.PrintColorUIResource[r=51,g=51,b=51],selectionColor=javax.swing.plaf.ColorUIResource[r=184,g=207,b=229],columns=10,columnWidth=0,command=,horizontalAlignment=CENTER]) InsertLength: 2 
Type : (parent: javax.swing.JTextField[,234,535,85x14,layout=javax.swing.plaf.basic.BasicTextUI$UpdateHandler,alignmentX=0.0,alignmentY=0.0,bo[email protected]384cdfdd,flags=296,maximumSize=,minimumSize=,preferredSize=,caretColor=sun.swing.PrintColorUIResource[r=51,g=51,b=51],disabledTextColor=javax.swing.plaf.ColorUIResource[r=184,g=207,b=229],editable=true,margin=javax.swing.plaf.InsetsUIResource[top=0,left=0,bottom=0,right=0],selectedTextColor=sun.swing.PrintColorUIResource[r=51,g=51,b=51],selectionColor=javax.swing.plaf.ColorUIResource[r=184,g=207,b=229],columns=10,columnWidth=0,command=,horizontalAlignment=CENTER]) InsertLength: 3 
+0

Мысль, поместив '.getName()' на textField, как и 'textFieldFencing_LC1.getDocument(). PutProperty (" parent ", textFieldFencing_LC1.getName());' может решить проблему. Но это не так. Теперь вывод читается как 'Type: (parent: null) InsertLength: 1' – EricG

ответ

0

После прочтения t он документально подтвердил этот класс, я понял, что метод putProperty(Object,Object) позволит мне поместить в него String. Итак, теперь мой слушатель на моей JTextField выглядит так ...

textFieldFencing_LC1.getDocument().addDocumentListener(documentListener); 
textFieldFencing_LC1.getDocument().putProperty("parent","LC1"); // String, String 

Обратите внимание, что второй параметр в putProperty() является строка со значением для меня, так что я могу проверить для LC#. В то время как обновление в DocumentListener выглядит следующим образом ...

final DocumentEvent.EventType type = documentEvent.getType(); 
String typeString = null; 

// Cast documentEvent to String 
txtField.setText((String) documentEvent.getDocument().getProperty("parent")); 

      if (type.equals(DocumentEvent.EventType.CHANGE)) { 
       typeString = "(parent: " + txtField.getText() + ") Change"; 
      } else if (type.equals(DocumentEvent.EventType.INSERT)) { 
       typeString = "(parent: " + txtField.getText() + ") Insert"; 
      } else if (type.equals(DocumentEvent.EventType.REMOVE)) { 
       typeString = "(parent: " + txtField.getText() + ") Remove"; 
     } 
    System.out.print("Type : " + typeString); 
    final Document source = documentEvent.getDocument(); 
    final int length = source.getLength(); 
    System.out.println("Length: " + length); 
} 

Выходной теперь выглядит ...

Type : (parent: LC1) RemoveLength: 0 
Type : (parent: LC1) InsertLength: 1 
Type : (parent: LC1) InsertLength: 2 
Type : (parent: LC1) InsertLength: 3 

Нижняя линия: ссылочное класса и две строки кода, размещенные на JTextFields мне нужно для прослушивания так, что происходит автоматическое обновление, намного лучше, чем добавление CaretListener во все эти поля.