【问题标题】:how add a listener for jtexfield when it changing? [duplicate]更改时如何为 jtextfield 添加侦听器? [复制]
【发布时间】:2011-07-23 13:19:46
【问题描述】:

我有一个JTextField.,我想在其中的文本发生更改时调用一个函数。

我该怎么做?

【问题讨论】:

  • 你试过setActionListener()吗?

标签: java swing jtextfield


【解决方案1】:

以这种方式使用 Key Listener

JTextField tf=new JTextField();
tf.addKeyListener(new KeyAdapter()
    {
        public void keyPressed(KeyEvent ke)
        {
            if(!(ke.getKeyChar()==27||ke.getKeyChar()==65535))//this section will execute only when user is editing the JTextField
            {
                System.out.println("User is editing something in TextField");
            }
        }
    });

【讨论】:

    【解决方案2】:

    Java 中用于跟踪 JTextField 文本内容变化的适当侦听器是 DocumentListener,您必须将其添加到 JTextField 的文档中:

    myTextField.getDocument().addDocumentListener(new DocumentListener() {
        // implement the methods
    });
    

    【讨论】:

    • 当人们只想检测变化时,这有点 OTT,但我承认这是唯一可行的解​​决方案。
    【解决方案3】:

    你可以使用 Caret Listener

            JTextField textField = new JTextField();
        textField.addCaretListener(new CaretListener() {
    
            @Override
            public void caretUpdate(CaretEvent e) {
                System.out.println("text field have changed");
    
            }
        });
    

    【讨论】:

    • 不,caretListener 与 data ... 的更改无关
    【解决方案4】:

    您可以将 KeyListener 或 ActionListener 添加到字段并捕获事件。

    【讨论】:

    • 字段中的值可能会发生变化,而无需用户直接在字段中输入值,例如根据选中的单选按钮设置字段中的值。
    猜你喜欢
    • 2021-05-23
    • 2011-04-26
    • 2014-03-21
    • 2015-05-10
    • 1970-01-01
    • 1970-01-01
    • 2012-12-27
    相关资源
    最近更新 更多