タイトル
TOPJavaSwingJFormattedTextField → This Page

JFormattedTextField@Swing サンプル03

概要

Java - Swing - JFormattedTextField のサンプルです。
・日時系[DateFormat]

解説

入力した日付文字列を整形して表示します。
日付フォーマットは SHORT, MEDIUM, LONG, FULL の4パターンから選択します。

サンプルイメージ

サンプル画像


サンプルソース

import java.awt.Dimension;
import java.awt.Font;
import java.text.DateFormat;
import java.util.Date;

import javax.swing.JFormattedTextField;
import javax.swing.JFrame;
import javax.swing.JPanel;

/**
 * JFormattedTextField サンプル03
 * ・日時系[DateFormat]
 * 
 * @author みっちー
 */
public class JFormattedTextField03 extends JFrame {
	
	private static final long serialVersionUID = 1L;
	
	/**
	 * 開始メソッド
	 * 
	 * @param args	パラメータ
	 */
	public static void main(String[] args) {
		JFormattedTextField03 frame = new JFormattedTextField03();
		
		// 閉じるボタンをクリックされた場合の動作を設定
		frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		
		// ウインドウのタイトルを設定
		frame.setTitle("JFormattedTextField サンプル03");
		
		// フレームの X座標、Y座標、幅、高さを設定
		frame.setBounds(100, 200, 250, 150);
		
		// フレームを表示(これをしないと透明のフレームが立ち上がってしまう)
		frame.setVisible(true);
	}
	
	/**
	 * コンストラクタ
	 */
	public JFormattedTextField03() {
		// パネルを作成
		JPanel panelBase = new JPanel();
		
		// フォーマットを設定
		DateFormat df1 = DateFormat.getDateTimeInstance(DateFormat.SHORT, DateFormat.SHORT);
		DateFormat df2 = DateFormat.getDateTimeInstance(DateFormat.MEDIUM, DateFormat.MEDIUM);
		DateFormat df3 = DateFormat.getDateTimeInstance(DateFormat.LONG, DateFormat.LONG);
		DateFormat df4 = DateFormat.getDateTimeInstance(DateFormat.FULL, DateFormat.FULL);
		
		// テキストを作成
		JFormattedTextField text1 = new JFormattedTextField(df1);
		JFormattedTextField text2 = new JFormattedTextField(df2);
		JFormattedTextField text3 = new JFormattedTextField(df3);
		JFormattedTextField text4 = new JFormattedTextField(df4);
		
		// 初期値
		Date dt = new Date();
		
		// 初期値を設定
		// setText() だと初期表示時にフォーマットが評価されないので setValue() を使う
		text1.setValue(dt);
		text2.setValue(dt);
		text3.setValue(dt);
		text4.setValue(dt);
		
		// サイズを設定
		text1.setPreferredSize(new Dimension(220, 20));
		text2.setPreferredSize(new Dimension(220, 20));
		text3.setPreferredSize(new Dimension(220, 20));
		text4.setPreferredSize(new Dimension(220, 20));
		
		// フォントの設定
		text1.setFont(new Font("MS ゴシック", Font.PLAIN, 16));
		text2.setFont(new Font("MS ゴシック", Font.PLAIN, 16));
		text3.setFont(new Font("MS ゴシック", Font.PLAIN, 16));
		text4.setFont(new Font("MS ゴシック", Font.PLAIN, 16));
		
		// テキストを追加
		panelBase.add(text1);
		panelBase.add(text2);
		panelBase.add(text3);
		panelBase.add(text4);
		
		// パネルを追加
		getContentPane().add(panelBase);
	}
}

サンプルソースのダウンロード

ソースのダウンロード(Eclipse用のプロジェクトファイルも同梱)

更新履歴

2016/05/13 Windows 8.1 + Java 7 環境で全体を見直し
2007/12/27 新規作成


TOPJavaSwingJFormattedTextField → This Page