【问题标题】:Value Change Listener to JTextFieldJTextField 的值更改侦听器
【发布时间】:2011-04-26 13:49:29
【问题描述】:

我希望在用户更改文本字段中的值后立即显示消息框。目前,我需要按回车键才能弹出消息框。我的代码有什么问题吗?

textField.addActionListener(new java.awt.event.ActionListener() {
    public void actionPerformed(java.awt.event.ActionEvent e) {

        if (Integer.parseInt(textField.getText())<=0){
            JOptionPane.showMessageDialog(null,
                    "Error: Please enter number bigger than 0", "Error Message",
                    JOptionPane.ERROR_MESSAGE);
        }       
    }
}

任何帮助将不胜感激!

【问题讨论】:

    标签: java swing listener jtextfield documentlistener


    【解决方案1】:

    为基础文档添加一个侦听器,该侦听器会自动为您创建。

    // Listen for changes in the text
    textField.getDocument().addDocumentListener(new DocumentListener() {
      public void changedUpdate(DocumentEvent e) {
        warn();
      }
      public void removeUpdate(DocumentEvent e) {
        warn();
      }
      public void insertUpdate(DocumentEvent e) {
        warn();
      }
    
      public void warn() {
         if (Integer.parseInt(textField.getText())<=0){
           JOptionPane.showMessageDialog(null,
              "Error: Please enter number bigger than 0", "Error Message",
              JOptionPane.ERROR_MESSAGE);
         }
      }
    });
    

    【讨论】:

    • 警告/类型转换的良好格式。相同的模式可用于处理双倍金额(输入或显示的销售数字/价格)
    • 它工作正常,但我有一个查询,当我在文本字段中插入一些文本时,我想调用一个方法。我不太了解它是如何完成的..
    • 点击另一个表格单元格时,JTable 没有从可编辑的 JComboBox 获取文本框更新时遇到问题,此处的 insertUpdate 函数是使其正常工作的唯一方法。
    • “错误按摩”
    【解决方案2】:

    对此的通常回答是“使用DocumentListener”。但是,我总是觉得那个界面很麻烦。说实话,界面被过度设计了。它有三种方法,用于文本的插入、删除和替换,而它只需要一种方法:替换。 (插入可以看作是用一些文本替换没有文本,删除可以看作是用没有文本替换一些文本。)

    通常您只想知道框中的文本何时发生变化,因此典型的DocumentListener 实现具有三个方法调用一个方法。

    因此我制作了以下实用方法,它可以让您使用更简单的ChangeListener 而不是DocumentListener。 (它使用 Java 8 的 lambda 语法,但如果需要,您可以将其调整为旧 Java。)

    /**
     * Installs a listener to receive notification when the text of any
     * {@code JTextComponent} is changed. Internally, it installs a
     * {@link DocumentListener} on the text component's {@link Document},
     * and a {@link PropertyChangeListener} on the text component to detect
     * if the {@code Document} itself is replaced.
     * 
     * @param text any text component, such as a {@link JTextField}
     *        or {@link JTextArea}
     * @param changeListener a listener to receieve {@link ChangeEvent}s
     *        when the text is changed; the source object for the events
     *        will be the text component
     * @throws NullPointerException if either parameter is null
     */
    public static void addChangeListener(JTextComponent text, ChangeListener changeListener) {
        Objects.requireNonNull(text);
        Objects.requireNonNull(changeListener);
        DocumentListener dl = new DocumentListener() {
            private int lastChange = 0, lastNotifiedChange = 0;
    
            @Override
            public void insertUpdate(DocumentEvent e) {
                changedUpdate(e);
            }
    
            @Override
            public void removeUpdate(DocumentEvent e) {
                changedUpdate(e);
            }
    
            @Override
            public void changedUpdate(DocumentEvent e) {
                lastChange++;
                SwingUtilities.invokeLater(() -> {
                    if (lastNotifiedChange != lastChange) {
                        lastNotifiedChange = lastChange;
                        changeListener.stateChanged(new ChangeEvent(text));
                    }
                });
            }
        };
        text.addPropertyChangeListener("document", (PropertyChangeEvent e) -> {
            Document d1 = (Document)e.getOldValue();
            Document d2 = (Document)e.getNewValue();
            if (d1 != null) d1.removeDocumentListener(dl);
            if (d2 != null) d2.addDocumentListener(dl);
            dl.changedUpdate(null);
        });
        Document d = text.getDocument();
        if (d != null) d.addDocumentListener(dl);
    }
    

    与直接向文档添加侦听器不同,这可以处理(不常见的)您在文本组件上安装新文档对象的情况。此外,它还解决了 Jean-Marc Astesana's answer 中提到的问题,即文档有时会触发比它需要的更多的事件。

    不管怎样,这个方法可以让你替换烦人的代码,看起来像这样:

    someTextBox.getDocument().addDocumentListener(new DocumentListener() {
        @Override
        public void insertUpdate(DocumentEvent e) {
            doSomething();
        }
    
        @Override
        public void removeUpdate(DocumentEvent e) {
            doSomething();
        }
    
        @Override
        public void changedUpdate(DocumentEvent e) {
            doSomething();
        }
    });
    

    与:

    addChangeListener(someTextBox, e -> doSomething());
    

    代码发布到公共领域。玩得开心!

    【讨论】:

    • 类似的解决方案:创建一个带有额外抽象方法 change(DocumentEvent e)abstract class DocumentChangeListener implements DocumentListener,您可以从所有其他 3 个方法调用该方法。对我来说似乎更明显,因为它使用或多或少与abstract *Adapter 侦听器相同的逻辑。
    • +1 as changedUpdate 方法应通过insertUpdateremoveUpdate 中的每个调用显式调用,以使其工作..
    【解决方案3】:

    只需创建一个扩展 DocumentListener 并实现所有 DocumentListener 方法的接口:

    @FunctionalInterface
    public interface SimpleDocumentListener extends DocumentListener {
        void update(DocumentEvent e);
    
        @Override
        default void insertUpdate(DocumentEvent e) {
            update(e);
        }
        @Override
        default void removeUpdate(DocumentEvent e) {
            update(e);
        }
        @Override
        default void changedUpdate(DocumentEvent e) {
            update(e);
        }
    }
    

    然后:

    jTextField.getDocument().addDocumentListener(new SimpleDocumentListener() {
        @Override
        public void update(DocumentEvent e) {
            // Your code here
        }
    });
    

    或者你甚至可以使用 lambda 表达式:

    jTextField.getDocument().addDocumentListener((SimpleDocumentListener) e -> {
        // Your code here
    });
    

    【讨论】:

    • 不要忘记,在 Java 8 之前的所有版本中,此解决方案都需要抽象类而不是接口。
    【解决方案4】:

    请注意,当用户修改字段时,DocumentListener 有时会接收两个事件。例如,如果用户选择了整个字段内容,然后按一个键,您将收到一个 removeUpdate(所有内容都被删除)和一个 insertUpdate。 在你的情况下,我认为这不是问题,但一般来说,它是。 不幸的是,似乎没有办法在不继承 JTextField 的情况下跟踪 textField 的内容。 这是提供“文本”属性的类的代码:

    package net.yapbam.gui.widget;
    
    import javax.swing.JTextField;
    import javax.swing.text.AttributeSet;
    import javax.swing.text.BadLocationException;
    import javax.swing.text.PlainDocument;
    
    /** A JTextField with a property that maps its text.
     * <br>I've found no way to track efficiently the modifications of the text of a JTextField ... so I developed this widget.
     * <br>DocumentListeners are intended to do it, unfortunately, when a text is replace in a field, the listener receive two events:<ol>
     * <li>One when the replaced text is removed.</li>
     * <li>One when the replacing text is inserted</li>
     * </ul>
     * The first event is ... simply absolutely misleading, it corresponds to a value that the text never had.
     * <br>Anoter problem with DocumentListener is that you can't modify the text into it (it throws IllegalStateException).
     * <br><br>Another way was to use KeyListeners ... but some key events are throw a long time (probably the key auto-repeat interval)
     * after the key was released. And others events (for example a click on an OK button) may occurs before the listener is informed of the change.
     * <br><br>This widget guarantees that no "ghost" property change is thrown !
     * @author Jean-Marc Astesana
     * <BR>License : GPL v3
     */
    
    public class CoolJTextField extends JTextField {
        private static final long serialVersionUID = 1L;
    
        public static final String TEXT_PROPERTY = "text";
    
        public CoolJTextField() {
            this(0);
        }
    
        public CoolJTextField(int nbColumns) {
            super("", nbColumns);
            this.setDocument(new MyDocument());
        }
    
        @SuppressWarnings("serial")
        private class MyDocument extends PlainDocument {
            private boolean ignoreEvents = false;
    
            @Override
            public void replace(int offset, int length, String text, AttributeSet attrs) throws BadLocationException {
                String oldValue = CoolJTextField.this.getText();
                this.ignoreEvents = true;
                super.replace(offset, length, text, attrs);
                this.ignoreEvents = false;
                String newValue = CoolJTextField.this.getText();
                if (!oldValue.equals(newValue)) CoolJTextField.this.firePropertyChange(TEXT_PROPERTY, oldValue, newValue);
            }
    
            @Override
            public void remove(int offs, int len) throws BadLocationException {
                String oldValue = CoolJTextField.this.getText();
                super.remove(offs, len);
                String newValue = CoolJTextField.this.getText();
                if (!ignoreEvents && !oldValue.equals(newValue)) CoolJTextField.this.firePropertyChange(TEXT_PROPERTY, oldValue, newValue);
            }
        }
    

    【讨论】:

    • Swing 已经 具有 一种将文档更改映射到属性的 textField - 它被称为 JFormattedTextField :-)
    【解决方案5】:

    我知道这与一个非常老的问题有关,但是,它也给我带来了一些问题。正如kleopatra 在上面的评论中回复的那样,我用JFormattedTextField 解决了这个问题。但是,该解决方案需要更多的工作,但更整洁。

    JFormattedTextField 默认情况下不会在字段中的每个文本更改后触发属性更改。 JFormattedTextField 的默认构造函数不会创建格式化程序。

    但是,要执行 OP 建议的操作,您需要使用格式化程序,该格式化程序将在每次有效编辑字段后调用 commitEdit() 方法。 commitEdit() 方法是从我所看到的并且没有格式化程序的情况下触发属性更改的原因,默认情况下这是在焦点更改或按下回车键时触发的。

    更多详情请见http://docs.oracle.com/javase/tutorial/uiswing/components/formattedtextfield.html#value

    创建一个默认格式化程序 (DefaultFormatter) 对象,以通过其构造函数或 setter 方法传递给 JFormattedTextField。默认格式化程序的一种方法是setCommitsOnValidEdit(boolean commit),它将格式化程序设置为在每次更改文本时触发commitEdit() 方法。然后可以使用PropertyChangeListenerpropertyChange() 方法来获取它。

    【讨论】:

      【解决方案6】:
      textBoxName.getDocument().addDocumentListener(new DocumentListener() {
         @Override
         public void insertUpdate(DocumentEvent e) {
             onChange();
         }
      
         @Override
         public void removeUpdate(DocumentEvent e) {
            onChange();
         }
      
         @Override
         public void changedUpdate(DocumentEvent e) {
            onChange();
         } 
      });
      

      但我不会将用户(可能是偶然)在其键盘上触摸的任何内容解析为Integer。您应该捕获任何抛出的Exceptions,并确保JTextField 不为空。

      【讨论】:

        【解决方案7】:

        如果我们在使用 Document listener 时使用可运行方法 SwingUtilities.invokeLater() 有时会卡住并且需要时间来更新结果(根据我的实验)。取而代之的是,我们还可以使用 KeyReleased 事件作为 here 中提到的文本字段更改侦听器。

        usernameTextField.addKeyListener(new KeyAdapter() {
            public void keyReleased(KeyEvent e) {
                JTextField textField = (JTextField) e.getSource();
                String text = textField.getText();
                textField.setText(text.toUpperCase());
            }
        });
        

        【讨论】:

          【解决方案8】:

          这是 Codemwnci 的更新版本。他的代码很好,除了错误消息外,效果很好。为避免错误,您必须更改条件语句。

            // Listen for changes in the text
          textField.getDocument().addDocumentListener(new DocumentListener() {
            public void changedUpdate(DocumentEvent e) {
              warn();
            }
            public void removeUpdate(DocumentEvent e) {
              warn();
            }
            public void insertUpdate(DocumentEvent e) {
              warn();
            }
          
            public void warn() {
               if (textField.getText().length()>0){
                 JOptionPane.showMessageDialog(null,
                    "Error: Please enter number bigger than 0", "Error Massage",
                    JOptionPane.ERROR_MESSAGE);
               }
            }
          });
          

          【讨论】:

          • 只要在文本字段中输入任何长度超过 length=0 的字符串,您的适配就会触发错误消息对话框。所以这基本上是除空字符串之外的任何字符串。这不是要求的解决方案。
          【解决方案9】:

          一种优雅的方法是将侦听器添加到插入符号位置,因为每次键入/删除某些内容时它都会改变,然后只需将旧值与当前值进行比较。

          String oldVal = ""; // empty string or default value
          JTextField tf = new JTextField(oldVal);
          
          tf.addCaretListener(e -> {
              String currentVal = login.getText();
          
              if(!currentVal.equals(oldVal)) {
                  oldVal = currentVal;
                  System.out.println("Change"); // do something
              }
          });
          

          (每次用户点击文本字段时也会触发此事件。

          【讨论】:

            【解决方案10】:

            您甚至可以使用“MouseExited”进行控制。 示例:

             private void jtSoMauMouseExited(java.awt.event.MouseEvent evt) {                                    
                    // TODO add your handling code here:
                    try {
                        if (Integer.parseInt(jtSoMau.getText()) > 1) {
                            //auto update field
                            SoMau = Integer.parseInt(jtSoMau.getText());
                            int result = SoMau / 5;
            
                            jtSoBlockQuan.setText(String.valueOf(result));
                        }
                    } catch (Exception e) {
            
                    }
            
                }   
            

            【讨论】:

            • 不是真的:要求是在更改文本时做某事 - 这与 mouseEvents 无关 ;-)
            【解决方案11】:

            使用 KeyListener(在任何键上触发)而不是 ActionListener(在输入时触发)

            【讨论】:

            • 这不起作用,因为没有正确捕获该字段的值,field.getText() 返回初始值。并且事件 (arg0.getKeyChar()) 返回按键错误检查以确定是否应该与字段文本连接。
            • @glend,您可以使用 keyReleased 事件而不是 keyTyped 事件。它对我有用并获得了完整的价值。
            【解决方案12】:

            DocumentFilter ?它使您能够操纵。

            [http://www.java2s.com/Tutorial/Java/0240__Swing/FormatJTextFieldstexttouppercase.htm]

            对不起。 J 正在使用 Jython(Java 中的 Python)- 但易于理解

            # python style
            # upper chars [ text.upper() ]
            
            class myComboBoxEditorDocumentFilter( DocumentFilter ):
            def __init__(self,jtext):
                self._jtext = jtext
            
            def insertString(self,FilterBypass_fb, offset, text, AttributeSet_attrs):
                txt = self._jtext.getText()
                print('DocumentFilter-insertString:',offset,text,'old:',txt)
                FilterBypass_fb.insertString(offset, text.upper(), AttributeSet_attrs)
            
            def replace(self,FilterBypass_fb, offset, length, text, AttributeSet_attrs):
                txt = self._jtext.getText()
                print('DocumentFilter-replace:',offset, length, text,'old:',txt)
                FilterBypass_fb.replace(offset, length, text.upper(), AttributeSet_attrs)
            
            def remove(self,FilterBypass_fb, offset, length):
                txt = self._jtext.getText()
                print('DocumentFilter-remove:',offset, length, 'old:',txt)
                FilterBypass_fb.remove(offset, length)
            
            // (java style ~example for ComboBox-jTextField)
            cb = new ComboBox();
            cb.setEditable( true );
            cbEditor = cb.getEditor();
            cbEditorComp = cbEditor.getEditorComponent();
            cbEditorComp.getDocument().setDocumentFilter(new myComboBoxEditorDocumentFilter(cbEditorComp));
            

            【讨论】:

              【解决方案13】:

              我是 WindowBuilder 的新手,事实上,几年后才回到 Java,但我实现了“一些东西”,然后我想我会查找它并遇到这个线程。

              我正在对此进行测试,因此,基于对这一切的陌生,我确定我一定遗漏了一些东西。

              这是我所做的,其中“runTxt”是一个文本框,“runName”是该类的一个数据成员:

              public void focusGained(FocusEvent e) {
                  if (e.getSource() == runTxt) {
                      System.out.println("runTxt got focus");
                      runTxt.selectAll();
                  }
              }
              
              public void focusLost(FocusEvent e) {
                  if (e.getSource() == runTxt) {
                      System.out.println("runTxt lost focus");
                      if(!runTxt.getText().equals(runName))runName= runTxt.getText();
                      System.out.println("runText.getText()= " + runTxt.getText() + "; runName= " + runName);
                  }
              }
              

              似乎比目前这里的要简单得多,而且似乎正在工作,但是,由于我正在写这篇文章,我希望听到任何被忽视的问题。用户可以在不进行更改的情况下进入和离开文本框是否存在问题?我认为你所做的只是一项不必要的任务。

              【讨论】:

                【解决方案14】:

                这是@Boann 答案的 Kotlin 端口,这是一个很好的解决方案,对我来说效果很好。

                import java.beans.*
                import javax.swing.*
                import javax.swing.event.*
                import javax.swing.text.*
                
                /**
                 * Installs a listener to receive notification when the text of this
                 * [JTextComponent] is changed. Internally, it installs a [DocumentListener] on the
                 * text component's [Document], and a [PropertyChangeListener] on the text component
                 * to detect if the `Document` itself is replaced.
                 *
                 * @param changeListener a listener to receive [ChangeEvent]s when the text is changed;
                 * the source object for the events will be the text component
                 */
                fun JTextComponent.addChangeListener(changeListener: ChangeListener) {
                    val dl: DocumentListener = object : DocumentListener {
                        private var lastChange = 0
                        private var lastNotifiedChange = 0
                        override fun insertUpdate(e: DocumentEvent) = changedUpdate(e)
                        override fun removeUpdate(e: DocumentEvent) = changedUpdate(e)
                        override fun changedUpdate(e: DocumentEvent) {
                            lastChange++
                            SwingUtilities.invokeLater {
                                if (lastNotifiedChange != lastChange) {
                                    lastNotifiedChange = lastChange
                                    changeListener.stateChanged(ChangeEvent(this))
                                }
                            }
                        }
                    }
                    addPropertyChangeListener("document") { e: PropertyChangeEvent ->
                        (e.oldValue as? Document)?.removeDocumentListener(dl)
                        (e.newValue as? Document)?.addDocumentListener(dl)
                        dl.changedUpdate(null)
                    }
                    document?.addDocumentListener(dl)
                }
                

                您可以在任何文本组件上使用它,如下所示:

                myTextField.addChangeListener { event -> myEventHandler(event) }
                

                就像他的代码一样,也是公共领域。

                【讨论】:

                  猜你喜欢
                  • 2015-05-10
                  • 2021-05-23
                  • 2014-03-21
                  • 2013-03-23
                  • 2012-12-27
                  • 1970-01-01
                  • 2011-07-23
                  相关资源
                  最近更新 更多