[PR]上記の広告は3ヶ月以上新規記事投稿のないブログに表示されています。新しい記事を書く事で広告が消えます。
ただいまコメントを受けつけておりません。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 | package application; import javafx.animation.Interpolator; import javafx.animation.RotateTransition; import javafx.application.Application; import javafx.event.ActionEvent; import javafx.scene.Scene; import javafx.scene.control.Button; import javafx.scene.layout.BorderPane; import javafx.scene.shape.Rectangle; import javafx.stage.Stage; import javafx.util. Duration ; public class TestThread1 extends Application { public static void main( String [] args) { launch(args); } @Override public void start(Stage primaryStage) throws Exception { // フォント色がおかしくなることへの対処 System.setProperty( "prism.lcdtext" , "false" ); // シーングラフの作成 BorderPane root = new BorderPane(); Rectangle rect = new Rectangle( 40 , 40 ); Button button = new Button( "sleep!" ); root.setCenter( rect ); root.setBottom( button ); // シーンの作成 Scene scene = new Scene( root , 100 , 100 ); // ウィンドウ表示 primaryStage.setScene( scene ); primaryStage.show(); // アニメーションの追加 RotateTransition anim = new RotateTransition( Duration .millis( 3000 ) , rect ); anim.setByAngle( 180 ); anim.setInterpolator( Interpolator.LINEAR ); anim.setCycleCount( RotateTransition.INDEFINITE ); anim.play(); // ボタンのイベントハンドラ button.addEventHandler( ActionEvent.ACTION , e -> { try { Thread.sleep( 1000 ); } catch (Exception e1) { e1.printStackTrace(); } } ); } } |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 | //ラベル作成 Label label1 = new Label( "now loading..." ); // ラベルの文字を5秒後に変更するタスクを定義 Task< Boolean > task = new Task< Boolean >() { @Override protected Boolean call() throws Exception { // 5秒待つ Thread.sleep( 5000 ); // ラベルの値を変更する // Platform.runLater関数により、 // 変更はJavaFXアプリケーションスレッド上で処理される Platform.runLater( () -> label1.setText( "Hello world!" ) ); return true ; } }; // タスクを実行1 Thread t = new Thread( task ); t.setDaemon( true ); t.start(); // タスクを実行2 //ExecutorService ex = Executors.newSingleThreadExecutor(); //ex.execute( task ); //ex.shutdown(); |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 | //ラベルの作成 Label label2 = new Label( "now loading..." ); // ラベルの文字を10秒後に変更するサービスを定義 Service< Boolean > service = new Service< Boolean >() { // 経過時間を保持 private int time = 0 ; @Override protected Task< Boolean > createTask() { // タスクを定義 Task< Boolean > task = new Task< Boolean >() { @Override protected Boolean call() throws Exception { // 10秒待つ Thread.sleep( 10000 ); // 経過時間を更新 time += 10 ; // ラベルの値を変更する // Platform.runLater関数により、 // 変更はJavaFXアプリケーションスレッド上で処理される Platform.runLater( () -> label2.setText( "current time is " + time ) ); return true ; }; }; <br> // 作成したタスクを返す return task; }; }; // サービスを開始 service.start(); |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 | // ラベルの作成 Label label3 = new Label( "now loading..." ); // ラベルの文字を15秒後と、以降5秒間隔で変更するサービスを定義 ScheduledService< Boolean > ss = new ScheduledService< Boolean >() { // 経過時間を保持 private int time = 10 ; @Override protected Task< Boolean > createTask() { // タスクを定義 Task< Boolean > task = new Task< Boolean >() { @Override protected Boolean call() throws Exception { // 5秒待つ Thread.sleep( 5000 ); // 経過時間を更新 time += 5 ; // ラベルの値を変更する // Platform.runLater関数により、 // 変更はJavaFXアプリケーションスレッド上で処理される Platform.runLater( () -> label3.setText( "current time is " + time ) ); return true ; }; }; // 作成したタスクを返す return task; } }; // 10秒遅れでサービスを実行 ss.setDelay( Duration .seconds( 10 ) ); ss.start(); |
取消処理の発生タイミング | ユーザコードによる対応 |
繰り返し処理中 (for, while等) |
isCancelled関数でキャンセル状態か確認し、処理を分岐させる |
ブロッキング関数呼び出し中 (Thread::sleep, InputStream::read等) |
InterruptedExceptionが発生するため、例外処理内でisCancelled関数を呼び出して処理を分岐させる |
状態 | イベントハンドラ登録関数 | protectedメソッド |
READY | - | - |
SCHEDULED | setOnScheduled(EventHandler<WorkerStateEvent>) | scheduled()のオーバーライド |
RUNNING | setOnRunninng(EventHandler<WorkerStateEvent>) | running()のオーバーライド |
SUCCEEDED | setOnSucceeded(EventHandler<WorkerStateEvent>) | succeeded()のオーバーライド |
FAILED | setOnCanceled(EventHandler<WorkerStateEvent>) | failed()のオーバーライド |
CANCELLED | setOnFailed(EventHandler<WorkerStateEvent>) | canceled()のオーバーライド |
値取得関数 (JavaFXアプリケーションスレッド側) |
値設定関数 (バックグラウンドスレッド側) |
getValue() | updateValue( T ) |
getMessage() | updateMessage( String ) |
getState() | - |
getTitle() | updateTitle( String ) |
getProgress() | updateProgress( double , double ) updateProgress( long , long ) |
getWorkDone() | *updateProgressの第1引数で設定 |
getTotalWork() | *updateProgressの第2引数で設定 |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 | package application; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import javafx.application.Application; import javafx.application.Platform; import javafx.concurrent.ScheduledService; import javafx.concurrent.Service; import javafx.concurrent.Task; import javafx.concurrent.WorkerStateEvent; import javafx.event.ActionEvent; import javafx.scene.Node; import javafx.scene.Scene; import javafx.scene.control.Button; import javafx.scene.control.Label; import javafx.scene.control.ProgressIndicator; import javafx.scene.layout.HBox; import javafx.scene.layout.VBox; import javafx.stage.Stage; import javafx.util. Duration ; public class TestThread2 extends Application { public static void main( String [] args) { launch(args); } @Override public void start(Stage primaryStage) throws Exception { // フォント色がおかしくなることへの対処 System.setProperty( "prism.lcdtext" , "false" ); // シーングラフの作成 VBox root = new VBox(); Node taskTestNode = createTaskTestNode(); Node serviceTestNode = createServiceTestNode(); Node sServiceTestNode = createSServiceTestNode(); root.getChildren().addAll( taskTestNode, serviceTestNode, sServiceTestNode ); // シーンの作成 Scene scene = new Scene( root , 300 , 100 ); // ウィンドウ表示 primaryStage.setScene( scene ); primaryStage.show(); } /** * Taskクラスのテスト用ノード作成 * 画面表示5秒後に値が変わるラベル * * @return */ public Node createTaskTestNode() { // 画面出力用のラベルを作成 Label label = new Label( "now loading..." ); // ラベルの文字を5秒後に変更するタスクを定義 Task< Boolean > task = new Task< Boolean >() { @Override protected Boolean call() throws Exception { // 5秒待つ Thread.sleep( 5000 ); // ラベルの値を変更する // Platform.runLater関数により、 // 変更はJavaFXアプリケーションスレッド上で処理される Platform.runLater( () -> label.setText( "Hello world!" ) ); return true ; } }; // タスクを実行 ExecutorService ex = Executors.newSingleThreadExecutor(); ex.execute( task ); ex.shutdown(); return label; } /** * Serviceクラスのテスト用ノード作成 * 1%づつ進捗率が上がる進捗インジケータ * @return */ public Node createServiceTestNode() { // 画面表示用の進捗インジケータと // 進捗中止(取消)用のボタンを作成 HBox root = new HBox(); ProgressIndicator pi = new ProgressIndicator( 0 ); Button button = new Button( "Service cancel!" ); root.getChildren().addAll( pi , button ); // インジケータの値を1%づつ上げていくサービスを作成 Service< Boolean > service = new Service< Boolean >() { // 定数定義 final long max = 10000 ; // 完了までの時間[ms] final long inc = 100 ; // 進捗が1%終わる時間[ms] @Override protected Task< Boolean > createTask() { // タスクを定義 Task< Boolean > task = new Task< Boolean >() { @Override protected Boolean call() throws Exception { // 進捗状況を0.1秒ごとに上昇させる for ( int i= 0 ; i<(max/inc) ; i++ ) { // 0.1秒待つ try { Thread.sleep( inc ); } finally { // キャンセルされていないか確認 if ( isCancelled() ){ break ; } } // 進捗を更新 this .updateProgress( (i+ 1 ) * inc , max ); } // タスクを終了 return true ; }; }; // 作成したタスクを返す return task; }; }; // 進捗インジケータと進捗状況をリンクさせる service.progressProperty().addListener( e -> pi.setProgress( service.getProgress() ) ); // ボタン押下時にサービスを中止するように設定 button.addEventHandler( ActionEvent.ACTION , e -> service.cancel() ); // サービスを開始 service.start(); return root; } /** * ScheduledServiceクラスのテスト用ノード作成 * 現在のScheduledServiceクラスの状況を出力するラベル * @return */ public Node createSServiceTestNode() { // ラベルの作成 HBox root = new HBox(); Label label1 = new Label( "now loading..." ); Label label2 = new Label( "now loading..." ); root.getChildren().addAll( label1 , label2 ); // 状況 ScheduledService< Boolean > ss = new ScheduledService< Boolean >() { // カウンタ int count = 0 ; @Override protected Task< Boolean > createTask() { // タスクを定義 Task< Boolean > task = new Task< Boolean >() { @Override protected Boolean call() throws Exception { // カウンタ値を表示 Platform.runLater( () -> label2.setText( "count is " + count ) ); // 5秒待つ Thread.sleep( 5000 ); // カウンタ値をインクリメント count++; // タスクを終了 return true ; }; }; // タスクを返す return task; } @Override protected void running() { // 変更前の関数を呼び出し super .running(); // 追加する処理を記述 Platform.runLater( () -> System.out.println( "Running! (by protected method)" ) ); } }; // サービスの状態変更時、ラベル1のテキストを変更するように設定 ss.stateProperty().addListener( e -> label1.setText( ss.getState().toString() + ":" ) ); // Scheduled状態に遷移した際、ラベル2のテキストを変更するように設定 ss.addEventFilter(WorkerStateEvent.WORKER_STATE_SCHEDULED , e -> System.out.println( "Scheduled! (by EventHandler)" ) ); // 7秒遅れでサービスを実行 ss.setDelay( Duration .seconds( 7 ) ); ss.start(); return root; } } |
1 2 3 4 5 | Scheduled! (by EventHandler) Running! (by protected method) Scheduled! (by EventHandler) Running! (by protected method) … |
ただいまコメントを受けつけておりません。
(11/14) | JavaFX 画面キャプチャ(コマ撮り) |
(11/11) | JavaFX WebP画像ファイルを開く(webp-imageioライブラリ) |
(11/07) | EclipseでJavaFX入門(Java17での環境構築) |
(06/29) | Java DeepLearning4j 単語のベクトル化(Word2Vec) |
(06/11) | Java DeepLearning4j パラメータの設定 |