Home > Blockchain >  How can I synchronize two JTextFields in Java swing?
How can I synchronize two JTextFields in Java swing?

Time:12-01

I'm trying to synchronize two JTextFields. If I write in one JTextField, I want to write the same text in other JTextField simultaneously.

I'm not sure what event use for this requirement.

My example code:

private void txt_idEstablecimientoActionPerformed(java.awt.event.ActionEvent evt) {                                                      
    // TODO add your handling code here:
    txt_codigoEstablecimiento.addActionListener(new ActionListener() {
        @Override
        public void actionPerformed(ActionEvent e) {
            txt_codEstabQVT.setText(txt_codigoEstablecimiento.getText().trim());
            System.out.println(txt_codEstabQVT);
        }
    });
}

My example code:

 private void txt_idEstablecimientoActionPerformed(java.awt.event.ActionEvent evt) { // TODO add your handling code here: txt_codigoEstablecimiento.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { txt_codEstabQVT.setText(txt_codigoEstablecimiento.getText().trim()); System.out.println(txt_codEstabQVT); } }); }

CodePudding user response:

If I write in one JTextField, I want to write the same text in other JTextField simultaneously.

Share the "model" between the two components. In the case of a JTextField the model is the Document:

JTextField textField1 = new JTextField(...);
JTextField textField2 = new JTextField(...);
textField2.setDocument( textField1.getDocument() );

There is no need for any listeners.

CodePudding user response:

The solution is use the event Keyreleased. private void txt_emailEstablecQVTKeyReleased(java.awt.event.KeyEvent evt) {
// TODO add your handling code here: txt_emailE.setText(txt_emailEstablecQVT.getText().trim()); }

  • Related