Re: Problems with using JFormattedTextField



Philipp wrote:

I try to use a JFormattedTextField to show and enter numbers but can't
really figure out how to make it work.

Try the appended code, it's just your code with a few changes:
+ We set the format's idea of how many decimal digits to use
explicitly.
+ We don't use setText(), but setValue() which respects the
requested formatting.
+ We don't use Double.parseDouble(), but ask the formatter to do the
parsing for us.

(Double.parseDouble() would barf on:
1,234.567
which is how that number is printed in my locale. In others it would be:
1.234,567
which Double.parseDouble() can't handle either ;-)

-- chris

=====================
import java.awt.BorderLayout;
import java.beans.PropertyChangeEvent;
import java.beans.PropertyChangeListener;
import java.text.NumberFormat;
import java.text.ParseException;

import javax.swing.JFormattedTextField;
import javax.swing.JFrame;
import javax.swing.JTextField;

public class TestFrame
extends JFrame implements PropertyChangeListener
{
JFormattedTextField deltaXTf;
JFormattedTextField xCalTf;
NumberFormat format = NumberFormat.getNumberInstance();
Double zero = Double.valueOf(0.0);

public static void main(String[] args)
{
TestFrame n = new TestFrame();
}

public TestFrame()
{
format.setMinimumFractionDigits(2);
format.setMaximumFractionDigits(4);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
deltaXTf = new JFormattedTextField(format);
xCalTf= new JFormattedTextField(format);
deltaXTf.addPropertyChangeListener("value", this);
getContentPane().add(deltaXTf, BorderLayout.NORTH);
getContentPane().add(xCalTf, BorderLayout.SOUTH);
deltaXTf.setValue(zero);
xCalTf.setValue(zero);
pack();
setVisible(true);
}

public void propertyChange(PropertyChangeEvent evt)
{
Object src = evt.getSource();
Number deltaXTfVal = zero;
try
{
deltaXTfVal = format.parse(deltaXTf.getText());
}
catch (ParseException e)
{
System.err.println(e);
}
double newValue = deltaXTfVal.doubleValue() * 1.5;
xCalTf.setValue(Double.valueOf(newValue));
}
}



.