Reputation: 295
I'm trying to set whatever is entered into "titleField" to appear in "artistField" by passing it through the string variable title
I type text into titleField, press enter, and nothing appears in artistField
can someone tell me what I'm doing wrong?
titleField.addPropertyChangeListener(new PropertyChangeListener() {
public void propertyChange(PropertyChangeEvent e){
Object source = e.getSource();
if (source == titleField) {
title = (String)titleField.getValue();
}
}
});
artistField = new JFormattedTextField();
artistField.setText(title);
Upvotes: 4
Views: 1994
Reputation: 128925
Are you sure you need to use an JFormattedTextField
or can you use a JTextField
with a DocumentListener
as camickr suggest? What Formatter
are you using?
It is only the code in the propertyChange()
method that is executed when the propery is changed. So you have to update artistField
from that method. You should also update JFormattedTectFields
using setValue()
instead of setText()
since setText()
only updates the text and not the actual content.
Try with this PropertyChangeListener:
titleField.addPropertyChangeListener("value", new PropertyChangeListener() {
public void propertyChange(PropertyChangeEvent e){
Object source = e.getSource();
if (source == titleField) {
String title = (String)titleField.getValue();
artistField.setValue(title);
}
}
});
Your JFormattedTextField
needs a Formatter
that can handle String
. Here is a dumb formatter that just returns the same String (A JTextField
and a DocumentListener
is a better choice if you don't need a Formatter
):
class StringFormatter extends AbstractFormatter {
@Override
public Object stringToValue(String text) throws ParseException {
return text;
}
@Override
public String valueToString(Object value) throws ParseException {
return (String)value;
}
}
You use it when you initilise the JFormattedTextField
like:
JFormattedTextField titleField = new JFormattedTextField(new StringFormatter());
Upvotes: 2
Reputation: 8949
Try calling commitEdit before getValue maybe. Check out the Java Doc here.
Upvotes: 1
Reputation: 324147
I type text into titleField, press enter, and nothing appears in artistField
If your requirement is to do some processing when Enter
is pressed, then you should be using an ActionListener. An ActionListion can be added to a JFormattedTextField or a JTextField. Then in the ActionLIstener code you can get the text and reset your other variable.
Upvotes: 1