Anyway, when making GUIs with Java the JFormattedTextField is a very useful feature. However, in case of a textual input, for example for a descriptive piece of text, one might want two additional features not present in the default JFormattedTextField.
First is the default overwrite setting. This is not wanted in this case. This can be avoided by changing the formatter of the widget.
Use
AbstractFormatterFactory abstractFormatter = new AbstractFormatterFactory() {
@Override
public AbstractFormatter getFormatter(JFormattedTextField tf) {
InternationalFormatter format = new InternationalFormatter();
return format;
}
};
and
myFormattedTextField.setFormatterFactory(abstractFormatter);
to get a text field that can be edited without overwriting existing text.
Secondly, when focusing a text field, one normally want the caret to be on the position where the mouse pointer was clicked. Default behavior results in the caret being positioned on the left.
Use, as found here:
in combination with
MouseListener ml = new MouseAdapter() {
@Override
public void mousePressed(final MouseEvent e) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
JTextField tf = (JTextField) e.getSource();
int offset = tf.viewToModel(e.getPoint());
tf.setCaretPosition(offset);
}
});
}
};
myFormattedTextField.addMouseListener(ml);
to get the wanted behavior.
No comments:
Post a Comment