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

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);
        }       
    }
}

任何帮助,将不胜感激!

有帮助吗?

解决方案

将侦听器添加到基础文档中,该文档将自动为您创建。

// 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);
     }
  }
});

其他提示

通常的答案是“使用 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);
}

与直接向文档添加侦听器不同,这可以处理在文本组件上安装新文档对象的(不常见)情况。此外,它还解决了中提到的问题 让-马克·阿泰萨纳的回答, ,文档有时会触发比需要的更多的事件。

不管怎样,这个方法可以让你替换恼人的代码,如下所示:

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());

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

请注意,当用户修改字段时,DocumentListener可以在某个时候接收两个事件。例如,如果用户选择整个字段内容,请按键,您将收到一个删除update(所有内容is remove)和一个插入程序。就您而言,我认为这不是问题,但总的来说,是。不幸的是,似乎没有办法在不划分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);
        }
    }

只需板条一个扩展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
});

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

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

但是,要执行OP建议的事情,您需要使用将调用的格式化器 commitEdit() 每个有效的字段编辑之后的方法。这 commitEdit() 方法是触发属性从我所看到的变化的原因,没有格式化,默认情况下会触发焦点更改或按下Enter键时触发。

http://docs.oracle.com/javase/tutorial/uiswing/components/formattedtextfield.html#value 更多细节。

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

这是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);
     }
  }
});
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. 。你应该抓住任何 Exception抛出并确保 JTextField 不是空的。

您甚至可以使用“ 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) {

        }

    }   

使用钥匙列表(在任何键上触发任何键),而不是actionListener(在Enter上触发)

我是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);
        }
    }

似乎比到目前为止的问题要简单得多,而且似乎正在起作用,但是,由于我正在写这篇文章,因此我很高兴听到任何被忽视的Gotchas。用户可以输入并留下带有更改的文本框的问题吗?我认为您所做的只是不必要的任务。

如果我们使用可运行的方法swingutilities.invokelater()使用文档侦听器应用程序有时会陷入困境,并花时间更新结果(根据我的实验)。如上所述 这里.

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

文档窗 ?它使您能够操纵。

[ http://www.java2s.com/tutorial/java/0240__swing/formatjtextfieldstexttexttexttexttexttexttexttexttexttexttexttexttexttexttexttexttexttexttexttexttexttexttexttexttexttexttexttexttexttexttexttexttexttexttexttouppercase.htm ]

对不起。 J am使用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));
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top