Reputation: 1764
I have a problem with JFormattedTextField, namely keeping it in non-overwriting mode. I found out how to set it to non-overwriting, namely with setOverwriteMode(false).
However, although this function lets me type in the field without overwriting, when focus is lost and I re-enter the field, overWriteMode is on again!
Is there a way to keep overWriteMode false? I would prefer a solution which doesn't set it to false everytime I lose focus, but if that's the only possible solution, so be it.
This is what I've got now:
DefaultFormatter format = new DefaultFormatter();
format.setOverwriteMode(false);
inputField = new JFormattedTextField();
inputField.setValue("don't overwrite this!");
inputField.setColumns(20);
format.install(inputField);// This does the trick only the first time I enter the field!
I hope someone can help me!
Solution, as proposed by Robin:
DefaultFormatter format = new DefaultFormatter();
format.setOverwriteMode(false);
inputField = new JFormattedTextField(format); // put the formatter in the constructor
inputField.setValue("don't overtype this!");
inputField.setColumns(20);
Thanks for the help! Regards
Upvotes: 5
Views: 2135
Reputation: 109823
shot to the dark, is there something that I missed
import java.awt.GridLayout;
import java.math.RoundingMode;
import java.text.NumberFormat;
import javax.swing.JFormattedTextField;
import javax.swing.JFrame;
import javax.swing.text.NumberFormatter;
public class MaskFormatterTest {
public static void main(String[] args) throws Exception {
NumberFormat format = NumberFormat.getNumberInstance();
format.setMaximumFractionDigits(2);
format.setMinimumFractionDigits(2);
format.setParseIntegerOnly(true);
format.setRoundingMode(RoundingMode.HALF_UP);
NumberFormatter formatter = new NumberFormatter(format);
formatter.setMaximum(1000);
formatter.setMinimum(0.0);
formatter.setAllowsInvalid(false);
//formatter.setOverwriteMode(false);
JFormattedTextField tf = new JFormattedTextField(formatter);
tf.setColumns(10);
tf.setValue(123456789.99);
JFormattedTextField tf1 = new JFormattedTextField(formatter);
tf1.setValue(1234567890.99);
JFormattedTextField tf2 = new JFormattedTextField(formatter);
tf2.setValue(1111.1111);
JFormattedTextField tf3 = new JFormattedTextField(formatter);
tf3.setValue(-1111.1111);
JFormattedTextField tf4 = new JFormattedTextField(formatter);
tf4.setValue(-56);
JFrame frame = new JFrame("Test");
frame.setLayout(new GridLayout(5, 0));
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add(tf);
frame.add(tf1);
frame.add(tf2);
frame.add(tf3);
frame.add(tf4);
frame.pack();
frame.setVisible(true);
}
}
Upvotes: 2