Google
 
Web itpro-blogger.blogspot.com
日曜日, 10月 15, 2006

[Java]フォーマット

▼質問
数値をフォーマットしたい時はどうすんだい?

▼回答
DecimalFormatクラスを使用すればできるよ。使用方法は次のようになるよ。

DecimalFormat decimalFormat = new DecimalFormat( "###.0" );
String str = decimalFormat.format( 1234 );

▼質問
文字列をフォーマットしたい時はどうすんだい?

▼回答


▼質問
テキストフィールドの入力値をフィルタしたい時はどうすればいいの?

▼回答

JFormattedTextFieldクラスを使うとこうなるけど・・・。
文字数でしか入力制限ができない。。。

private MaskFormatter setMaskFormatter( int length ) {
MaskFormatter mf = null;
try {
String format = "";
for ( int i = 0 ; i < length-1 ; i++ ) format = format + "*";
mf = new MaskFormatter( format );
mf.setPlaceholderCharacter('_');
} catch (ParseException e) {
// TODO 自動生成された catch ブロック
e.printStackTrace();
}
return mf;
}
MaskFormatter mf = null;
try{
mf = new MaskFormatter("〒###-####");
mf.setPlaceholderCharacter('_');
}catch(ParseException pe){
}
JFormattedTextField ftf3 = new JFormattedTextField(mf);
ftf3.setColumns(10);

private MaskFormatter setMaskFormatter() {
MaskFormatter mf = null;
try {
mf = new MaskFormatter("###-##-####");
mf.setPlaceholderCharacter('_');
} catch (ParseException e) {
// TODO 自動生成された catch ブロック
e.printStackTrace();
}
return mf;
}


小数点を含む数値の入力のフォーマットはこうするとできたぞっ!

JFormattedTextField ftf = new JFormattedTextField();
DecimalFormat df = new DecimalFormat( "0.00" );

// 整数部分の最小桁数を設定する.
df.setMinimumIntegerDigits( 1 );
// 整数部分の最大桁数を設定する.
df.setMaximumIntegerDigits( 1 );
// 小数部分の最小桁数を設定する.
df.setMinimumFractionDigits( 2 );
// 小数部分の最大桁数を設定する.
df.setMaximumFractionDigits( 2 );
NumberFormatter nf = new NumberFormatter( df );
// 編集時には必要に応じてリテラル文字がスキップする.
nf.setAllowsInvalid( false );
nf.install( ftf );

■参考サイト
【Java:Swing:JFormattedTextField】
http://www.javadrive.jp/tutorial/jformattedtextfield/index.html

▼質問
入力ベリファイア(InputVerifier)って何?

▼回答
フォーカスが移動した時に実行され、trueになるまでフォーカスが移動できないみたい!?

JFormattedTextField tf = new JFormattedTextField();
tf.setInputVerifier( new InputVerifier() {
public boolean verify( javax.swing.JComponent input ) {
System.out.println( "InputVerifier" );
boolean returnValue = false;
JFormattedTextField tf = (JFormattedTextField)input;
try {
Integer.parseInt( tf.getText() );
returnValue = true;
}
catch ( NumberFormatException e ) {
tf.setText( "" );
returnValue = false;
}
return returnValue;
}
});

▼質問
JFormattedTextFieldでNumberFormatterをinstallしたんだけど・・・。
入力したものをクリアするためにsetText( "" )したんだけどうまくいかないんだ!
どうしたらうまくいくのか教えてくれ!!

▼回答
こうやるとできるよ(^^)v
JFormattedTextField ftf = new JFormattedTextField();
PlainDocument doc = new PlainDocument();
doc.insertString( 0, "", ftfgetDocument().getDefaultRootElement().getAttributes() );
ftf.setDocument( doc );

悲しい・・・お知らせです。

この方法では、設定したフォーマットが削除されてしまうことがわかりました。(;_;)

回避方法は、もう一度フォーマットし直す方法しか見つけれなかった。

とほほ。。。






Comments: コメントを投稿

<< Home

This page is powered by Blogger. Isn't yours?