Tuesday 12 October 2010

Customizing java's JFormattedTextField

In GUIs, text fields are a very common widget. With this text field, a user can enter all sorts of text (data) that is to be used by the application. This can for example be a simple descriptive text, but also more complex data specifying files to be read when the application is executed.

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:

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);
}
});
}
};
in combination with
myFormattedTextField.addMouseListener(ml);

to get the wanted behavior.

No comments:

Post a Comment