Mirroring a JTextField by Sharing Its Model With Another JTextField - Java Swing

Java examples for Swing:JTextField

Description

Mirroring a JTextField by Sharing Its Model With Another JTextField

Demo Code

import java.awt.Container;
import java.awt.GridLayout;

import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JTextField;
import javax.swing.text.Document;

public class Main extends JFrame {
  JLabel nameLabel = new JLabel("Name:");
  JLabel mirroredNameLabel = new JLabel("Mirrored Name:");
  JTextField name = new JTextField(20);
  JTextField mirroredName = new JTextField(20);

  public Main() {
    super("Mirrored JTextField");
    setDefaultCloseOperation(EXIT_ON_CLOSE);
    setLayout(new GridLayout(2, 0));
    Container contentPane = this.getContentPane();
    contentPane.add(nameLabel);// ww w. j  ava2 s .  c o  m
    contentPane.add(name);
    contentPane.add(mirroredNameLabel);
    contentPane.add(mirroredName);

    Document nameModel = name.getDocument();
    mirroredName.setDocument(nameModel);
  }

  public static void main(String[] args) {
    Main frame = new Main();
    frame.pack();
    frame.setVisible(true);
  }
}

Related Tutorials