Reputation: 107
I have a JFormattedTextField that's supposed to show 4 decimals.
jftSourceWidth.setText("0.0000");
jftSourceWidth.setHorizontalAlignment(SwingConstants.CENTER);
jftSourceWidth.setBounds(51, 69, 57, 20);
jftSourceWidth.setFormatterFactory(new javax.swing.text.DefaultFormatterFactory(new javax.swing.text.NumberFormatter(new java.text.DecimalFormat("#0.0000"))));
pnSource.add(jftSourceWidth);
And when the form loads, its given a value from somewhere (using setText()) and it doesn't format it. For example, it'll show 1.0 instead of 1.0000
Now here's the weird(?) part... if I click on it, then once I click anywhere else, the formatter will kick in and format it to 4 decimals.
How do I get it to format without having to click on it?????????
Thanks!
Upvotes: 0
Views: 50
Reputation: 285450
A possible cause is if you set the text of your JFormattedTextField before setting its format specifier. If you do this, you might lose the text. Consider setting your JFormattedTextField's text after you've given it a formatter not before. So instead of this:
jftSourceWidth.setText("0.0000");
jftSourceWidth.setHorizontalAlignment(SwingConstants.CENTER);
jftSourceWidth.setBounds(51, 69, 57, 20);
jftSourceWidth.setFormatterFactory(new javax.swing.text.DefaultFormatterFactory(new javax.swing.text.NumberFormatter(new java.text.DecimalFormat("#0.0000"))));
pnSource.add(jftSourceWidth);
do this:
//jftSourceWidth.setText("0.0000"); // not here
jftSourceWidth.setHorizontalAlignment(SwingConstants.CENTER);
// jftSourceWidth.setBounds(51, 69, 57, 20); // don't do this -- use layout managers instead
jftSourceWidth.setFormatterFactory(new javax.swing.text.DefaultFormatterFactory(
new javax.swing.text.NumberFormatter(new java.text.DecimalFormat("#0.0000"))));
pnSource.add(jftSourceWidth);
// **** set the text here ***
jftSourceWidth.setText("0.0000");
Also as an aside, you'll want to avoid use of null layouts and setBounds as this leads to creation of rigid difficult to enhance GUI's.
Note that if this does not solve your problem, then consider creating and posting a minimal example program.
Upvotes: 2