0
0

【Java】備忘録:Swing + Timer

Posted at

2日目(連投)


Timer の処理を Swing で画面表示してみた。


結果(貼り付けられない...)

画面内の文字が更新されていく感じのプログラム


source


import javax.swing.JFrame;
import javax.swing.JLabel;

import java.awt.Dimension;
import java.awt.Toolkit;
import java.util.Timer;
import java.util.TimerTask;

public class App extends JFrame {
	
	// timer
	static MainFrame mainFrame;

	public static void main( String[] args ) {
		mainFrame	= new MainFrame();
		mainFrame.setVisible(true);
		mainFrame.run();
	}

	private static class MainFrame extends JFrame {

		// gloabl
		int		num_run;
		JLabel	label;

		// 画面サイズの設定
		private boolean	is_full		= true;
		private int		width		= 300;
		private int		height		= 200;
		private boolean	is_resize	= false;

		public MainFrame() {

			// global
			// ------------------------------------------------------------------------
			this.num_run	= 0;
			this.label		= new JLabel( "init" );

			// 画面関連
			// ------------------------------------------------------------------------
			// 画面サイズ
			if ( is_full ) {
				Dimension screenSize	= Toolkit.getDefaultToolkit().getScreenSize();
				width	= (int) ( 0.75 * screenSize.getWidth()  );
				height	= (int) ( 0.75 * screenSize.getHeight() );
			};	this.setBounds( 10, 10, width, height );
				
			// 画面サイズ変更の可否
			this.setResizable( is_resize );
		
			// "×"ボタンを押したときの処理
			this.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE );

			this.add( this.label );
		
		}

		public void run() {
			Timer		tmpTimer		= new Timer();
			TimerTask	tmpTimerTask	= new TimerTask() {
				@Override
				public void run() {
					// ラベルの更新
					num_run	+= 1;
					label.setText( "run test_schedule : " + num_run );

					// num_run が 10g になった時の処理
					if ( num_run == 10 ) {
						this.cancel();								// タイマータスクを取り消す。
						System.out.println( "FINISH PROGRAM..." );	// 画面に出力して、
						System.exit(0);								// プログラムを終了する。
					}
				}
			};
			tmpTimer.schedule( tmpTimerTask, 3000, 500 );
		}

	}
	
}

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0