我的应用程序中有 JFormattedTextFields 来显示一些现金价值。
最初所有字段都设置为 0.00f;
但是,具有焦点的第一个组件将值显示为“.00”。其他人则按预期显示其值。
当格式化的文本字段具有焦点时,我应该如何将显示值设为“0.00”。
以下是 Mmy 示例代码。
import java.awt.GridLayout;
import java.awt.event.FocusEvent;
import java.awt.event.FocusListener;
import java.text.DecimalFormat;
import java.text.DecimalFormatSymbols;
import java.text.ParseException;
import javax.swing.JFormattedTextField;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.SwingUtilities;
import javax.swing.text.DefaultFormatterFactory;
import javax.swing.text.NumberFormatter;
public class MainFrame extends JFrame {
public MainFrame()
{
setSize(300, 300);
}
/**
* @param args
*/
public static void main(String[] args)
{
final MainFrame frame = new MainFrame();
JPanel panel = new JPanel();
panel.setLayout(new GridLayout(3, 1));
ExtedndedFormattedTextField tf = new ExtedndedFormattedTextField();
tf.setAmount(0.00f);
ExtedndedFormattedTextField tf1 = new ExtedndedFormattedTextField();
tf1.setAmount(0.00f);
ExtedndedFormattedTextField tf2 = new ExtedndedFormattedTextField();
tf2.setAmount(0.00f);
tf.setColumns(20);
panel.add(tf);
panel.add(tf1);
panel.add(tf2);
frame.add(panel);
frame.pack();
SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
frame.setVisible(true);
}
});
}
}
class ExtedndedFormattedTextField extends JFormattedTextField
{
private String negativeSymbol = "";
public ExtedndedFormattedTextField()
{
super();
setFormatterFactory(getCurrencyFormaterFactory());
this.addFocusListener(new FocusListener() {
@Override
public void focusLost(FocusEvent e) {
}
@Override
public void focusGained(FocusEvent e) {
SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
select(0, getText().length());
}
});
}
});
}
private AbstractFormatterFactory getCurrencyFormaterFactory()
{
NumberFormatter displayFormatter = new NumberFormatter(DecimalFormat.getCurrencyInstance());
DecimalFormatSymbols formatSymbols = new DecimalFormatSymbols();
negativeSymbol = String.valueOf(formatSymbols.getMinusSign());
NumberFormatter editFormatter = new NumberFormatter(new DecimalFormat("#.00",
formatSymbols));
editFormatter.setAllowsInvalid(false);
editFormatter.setOverwriteMode(false);
return new DefaultFormatterFactory(displayFormatter, displayFormatter, editFormatter);
}
public float getAmount()
{
try
{
commitEdit();
}
catch (ParseException e)
{
return 0;
}
Object o = getValue();
if (o instanceof Number)
{
return ((Number) getValue()).floatValue();
}
return 0;
}
public void setAmount(float amount)
{
setValue(new Float(amount));
}
@Override
public boolean requestFocusInWindow() {
this.select(0, getText().length());
return super.requestFocusInWindow();
}
}