Main.java Source code

Java tutorial

Introduction

Here is the source code for Main.java

Source

import java.text.NumberFormat;

import javax.swing.JFormattedTextField;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.event.DocumentEvent;
import javax.swing.event.DocumentListener;
import javax.swing.text.Document;
import javax.swing.text.NumberFormatter;

public class Main {

    NumberFormatter formatter = new NumberFormatter(NumberFormat.getNumberInstance());
    DocumentListener listener;
    JFormattedTextField input = new JFormattedTextField(formatter), input2 = new JFormattedTextField(formatter);

    public Main() {
        listener = new DocumentListener() {
            Document source = null;

            protected void update(Document doc) {
                if (source == null) {
                    System.out.println("Update");
                    source = doc;
                    if (source.equals(input.getDocument())) {
                        input2.setText(input.getText());
                    } else if (source.equals(input2.getDocument())) {
                        input.setText(input2.getText());
                    }
                    source = null;
                }
            }

            @Override
            public void insertUpdate(DocumentEvent e) {
                update(e.getDocument());
            }

            @Override
            public void removeUpdate(DocumentEvent e) {
                update(e.getDocument());
            }

            @Override
            public void changedUpdate(DocumentEvent e) {
                update(e.getDocument());
            }
        };

        input.getDocument().addDocumentListener(listener);
        input2.getDocument().addDocumentListener(listener);

        input.setColumns(4);
        input2.setColumns(4);

        input.setValue(0.0);
        JPanel panel = new JPanel();
        panel.add(input);
        panel.add(input2);

        JOptionPane.showMessageDialog(null, panel);
    }

    public static void main(String[] args) {
        new Main();
    }
}