自分用メモ:Java:xxFormatの悪癖

オボエガキ:JFormattedTextFieldにNumberFormatのような書式設定をつけた場合、BSで値を削除してもGained時に復活する。


数字を入力後、BSで削除してTABで移動すると、消した値が復活する

import java.awt.*;
import java.awt.event.*;
import java.text.*;
import javax.swing.*;
class Swing_Test1 extends JFrame implements FocusListener{
    private    JFormattedTextField    tfInputField;
    private    JFormattedTextField    tfInputField2;
    Toolkit    tk = getToolkit();
    {
       //レイアウトレイヤー設定
       JLayeredPane contentPane = this.getLayeredPane();
       contentPane.setLayout(null);//フリーレイアウト
	
       //「0.50」といったように表示したい
       NumberFormat  nf1 = NumberFormat.getNumberInstance();
       nf1.setMaximumFractionDigits(2);	//小数部の最大桁数
       nf1.setMinimumFractionDigits(2);	//小数部の最小桁数
       nf1.setMaximumIntegerDigits(2);	//整数部の最大桁数
       nf1.setMinimumIntegerDigits(1);	//少数部の最小桁数
       tfInputField = new JFormattedTextField(nf1);
       tfInputField.addFocusListener(this);
       tfInputField.setBounds(20,10,160,20);
       tfInputField2 = new JFormattedTextField(nf1);
       tfInputField2.addFocusListener(this);
       tfInputField2.setBounds(20,40,160,20);
       contentPane.add(tfInputField);
       contentPane.add(tfInputField2);
       //画面中央に表示
       this.setLocation((tk.getScreenSize().height/2 - this.getHeight()/2), (tk.getScreenSize().width/2 - this.getWidth())/2);
       this.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
    }
    public static void main(String  [] args){
       Swing_Test1 f = new Swing_Test1();
       f.setResizable(false);
       f.setTitle("JFrameTest");
       f.setSize(200, 100);
       f.setVisible(true);
    }
    public void focusGained(FocusEvent arg0) {
       System.out.println("Gained:tfInputField=" + tfInputField.getText());
       System.out.println("Gained:tfInputField2=" + tfInputField2.getText());
    }
    public void focusLost(FocusEvent arg0) {
       System.out.println("Lost:tfInputField=" + tfInputField.getText());
       System.out.println("Lost:tfInputField2=" + tfInputField2.getText());
    }
}