Search code examples
javaswingjtextfielddocumentlistener

read data from file to jtextfield1 and display in jtextfield2


I am trying to read data from a text file to Jtextfield1 and display it in jtextfield2,the data reads from text file to jtextfield1 but does not displays anything in jtextfield2 until we input a value in jtextfield1.I want as soon as the data is read in jtextfield1 it should reflect in jtextfield2.

 import java.awt.BorderLayout;
 import javax.swing.JFrame;
 import javax.swing.JPanel;
 import javax.swing.JTextField;
 import java.io.*;
 import java.util.*;
 import javax.swing.event.DocumentEvent;
 import javax.swing.event.DocumentListener;
 import javax.swing.text.AbstractDocument;
 import javax.swing.text.AttributeSet;
 import javax.swing.text.BadLocationException;
 import javax.swing.text.Document;
 import javax.swing.text.DocumentFilter;

 public class Sh extends JFrame
 {
  public Sh()
 {
    super("SH");
    final JPanel panel = new JPanel();
    getContentPane().add(panel, BorderLayout.NORTH);

    final JTextField field = new JTextField(10);
    panel.add(field);

  try{
        InputStream ips=new FileInputStream("test.txt"); 
        InputStreamReader ipsr=new InputStreamReader(ips);
        BufferedReader br=new BufferedReader(ipsr);
        String line;
        while ((line=br.readLine())!=null){
            field.setText(line);
          }
        br.close(); 
    }       
    catch (Exception e){
        e.printStackTrace();
    }


    final JTextField field1 = new JTextField(10);
    panel.add(field1);

    final DocumentListener docListener = new DocumentListener(){

        private Document originator;

        @Override
        public void changedUpdate(DocumentEvent e) {
            updateLabel(e);
        }

        @Override
        public void insertUpdate(DocumentEvent e) {
            updateLabel(e);
        }

        @Override
        public void removeUpdate(DocumentEvent e) {
            updateLabel(e);
        }

        private void updateLabel(DocumentEvent e) {
            if (null == originator) {
                originator = e.getDocument();
                String text = "";
                try {
                    text = originator.getText(0, originator.getLength());
                } catch (final Exception ex) {
                    ex.printStackTrace();
                }

                if (!text.isEmpty()) {
                    final int p = Integer.parseInt(text);
                    if (originator.equals(field.getDocument())) {
                        final int i = (p + 1);
                        final String s = String.valueOf(i);
                        field1.setText(s);
                    } else {
                        final int i = (p - 1);
                        final String s = String.valueOf(i);
                        field.setText(s);
                    }
                } else {
                  field.setText(text);
                  field1.setText(text);
                }

                originator = null;
            }

        }
    };
    field.getDocument().addDocumentListener(docListener);
    field1.getDocument().addDocumentListener(docListener);

    final DocumentFilter docFilter = new DocumentFilter(){
        @Override
        public void insertString(FilterBypass fb, int off, String str, AttributeSet     attr)
                throws BadLocationException {
            fb.insertString(off, str.replaceAll("\\D++", ""), attr);  // remove non-digits
        }

        @Override
        public void replace(FilterBypass fb, int off, int len, String str, AttributeSet attr)
                throws BadLocationException {
            fb.replace(off, len, str.replaceAll("\\D++", ""), attr);  // remove non-digits
        }
    };
    ((AbstractDocument) field.getDocument()).setDocumentFilter(docFilter);
    ((AbstractDocument) field1.getDocument()).setDocumentFilter(docFilter);

}
public static void main(String[] args)
{
    final Sh s = new Sh();
    s.setDefaultCloseOperation(EXIT_ON_CLOSE);
    s.pack();
    s.setVisible(true);
   }
 }

text file: 5487


Solution

  • your logic almost correct.but the main problem in your code you update textfield by a .txtfile before add document listener .you have to add document listner before you changed the textfield otherwise textfield not listen to document changes ..all you wanna do is move settext() code part to end of the document listener code

    field.getDocument().addDocumentListener(docListener);
    field1.getDocument().addDocumentListener(docListener);
    
    ///////////you should change text field after adding document listner not before//////////////////
    /* move textfield settext code part like that*/
    try {
        InputStream ips = new FileInputStream("test.txt");
        InputStreamReader ipsr = new InputStreamReader(ips);
        BufferedReader br = new BufferedReader(ipsr);
        String line;
        while ((line = br.readLine()) != null) {
            field.setText(line);
        }
        br.close();
    } catch (Exception e) {
        e.printStackTrace();
    }
    //////////////////////////////////////////////////////////////////////////////////////
    

    and alternative good solution....

    you can share same document with both textfields so when you change one textfield another one also get changed .then you can't have different text in fields .you have a text in field1 .same text is in textfield 2.

    field.setDocument(field1.getDocument());