Hello,
I am trying to create a decimal input field with two fraction digits. Sounds
quite ordinary. But with both formats used in the code below I meet the
following unwanted behaviour (the decimal point is displayed locale dependent):
- If the value starts with "0." and the cursor is before the decimal point, the
cursor is incorrectly moved to the right of the decimal point after the first
entered cypher.
- If the cursor is at the right edge of the textfield where no further input
should be possible, still you can type an invisible third decimal digit which
is accepted and the whole decimal part is rounded to two digits; the rounding
of course, becomes visible only if you enter ciphers >5 (or with the first
5 after a cipher >5).
Any idea for a workaround?
[There are even two more bugs, but they are already reported:
- setCaretPosition does not work. Bug ID: 6575394
- if the cusor is to the right of the decimal point and the integer part is
unequal to zero, after pressing <DEL> the fraction part is moved to the
integer part and two additional zeros are inserted.
Bug ID: 4678007]
import java.awt.*;
import java.awt.event.*;
import java.text.*;
import javax.swing.*;
import javax.swing.text.NumberFormatter;
public class Decimal extends JFrame {
JFormattedTextField ftf1 = new JFormattedTextField();
JFormattedTextField ftf2 = new JFormattedTextField();
public Decimal() {
setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
setSize(200, 150);
try {
NumberFormat nf = NumberFormat.getNumberInstance();
nf.setMinimumIntegerDigits(1);
nf.setMaximumFractionDigits(2);
nf.setMinimumFractionDigits(2);
NumberFormatter formatter = new NumberFormatter(nf);
formatter.setAllowsInvalid(false);
ftf1 = new JFormattedTextField(formatter);
ftf1.setHorizontalAlignment(SwingConstants.RIGHT);
ftf1.setValue(new Double(0.));
// Doesn't work, even when put in SwingUtilities.invokeLater(...).
// ftf1.setCaretPosition(1);
}
catch (Exception ex) {
System.out.println(ex);
}
try {
NumberFormatter formatter = new NumberFormatter(
new DecimalFormat("#,##0.00"));
formatter.setAllowsInvalid(false);
ftf2 = new JFormattedTextField(formatter);
ftf2.setHorizontalAlignment(SwingConstants.RIGHT);
ftf2.setValue(new Double(0.));
}
catch (Exception ex) {
System.out.println(ex);
}
Container cp= getContentPane();
cp.setLayout(null);
ftf1.setBounds(20, 11, 139, 20);
ftf2.setBounds(20, 41, 139, 20);
cp.add(ftf1);
cp.add(ftf2);
setVisible(true);
}
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
new Decimal();
}
});
}
}