我需要两个相互影响的 JTextField [英] I need two JTextFields that influence each other

查看:24
本文介绍了我需要两个相互影响的 JTextField的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个带有两个 JTextField 的 JPanel.如果用户在文本字段 A 中写入一些文本,则相同的文本应出现在文本字段 B 中,反之亦然.

I have a JPanel with two JTextFields. If the user writes some text into textfield A the same text should appear in textfield B and vice versa.

如何在不陷入无限循环的情况下实现这一点.

How can that be implemented without getting an infinite loop.

到目前为止,我有以下内容导致无限循环.

So far I have the following which leds to a infinite loop.

        JTextField textFieldA;
        JTextField textFieldB;

        textFieldA.getDocument().addDocumentListener(new DocumentListener() {
            public void insertUpdate(DocumentEvent e) {  
                Document doc = (Document)e.getDocument();
                String line = doc.getText(0, doc.getLength());  
                textFieldB.setText(line);
            }
            textFieldB.getDocument().addDocumentListener(new DocumentListener() {
                public void insertUpdate(DocumentEvent e) {  
                    Document doc = (Document)e.getDocument();
                    String line = doc.getText(0, doc.getLength());  
                    textFieldA.setText(line);
                }

推荐答案

您可以在传播更改时使用布尔值进行标记.

You can use a boolean to mark when you are propagating changes.

    JTextField textFieldA;
    JTextField textFieldB;
    boolean updating = false;

    textFieldA.getDocument().addDocumentListener(new DocumentListener() {
        public void insertUpdate(DocumentEvent e) {  
            if(!updating) {
            updating = true;
            Document doc = (Document)e.getDocument();
            String line = doc.getText(0, doc.getLength());  
            textFieldB.setText(line);
            updating = false;
            }
        }
    textFieldB.getDocument().addDocumentListener(new DocumentListener() {
        public void insertUpdate(DocumentEvent e) {  
            if(!updating) {
            updating = true;
            Document doc = (Document)e.getDocument();
            String line = doc.getText(0, doc.getLength());  
            textFieldA.setText(line);
            updating = false;
            }
        }

这篇关于我需要两个相互影响的 JTextField的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆