JavaFXを中心軸にJavaを学習しています。
コレクションクラスという物があることを知ったのですが。
ArrayListとTimeAPIを組み合わせれば、タイムスタンプを自作できると思い、実験として以下のコードを書きました。
GUIのボタンが押されれば、その都度ArrayListの箱が増えていき、箱の中にnowされたその時の現在時刻が格納されていくと考えたためです。
ところが拡張for文で配列を回して箱の中身を出してみると、実験結果は予想に反して一個の時刻しか格納されていませんでした。
これはイベントハンドラーが動作する度に初期化がされるということなのでしょうか、このような処理を実現するためには考え方としてやはりSQLなどのデーターベースの知識が必要となってくるのでしょうか?
Java
1package ArrayListとtimeAPIの実験; 2 3import java.time.LocalTime; 4import java.util.ArrayList; 5import javafx.application.Application; 6import javafx.event.ActionEvent; 7import javafx.event.EventHandler; 8import javafx.scene.Scene; 9import javafx.scene.control.Button; 10import javafx.scene.layout.StackPane; 11import javafx.stage.Stage; 12 13/** 14 * 15 * @author test 16 */ 17public class ArrayListとTimeAPIの実験 extends Application { 18 19 @Override 20 public void start(Stage primaryStage) { 21 Button btn = new Button(); 22 btn.setText("ArrayListに現在時刻を格納する'"); 23 btn.setOnAction(new EventHandler<ActionEvent>() { 24 25 @Override 26 public void handle(ActionEvent event) { 27 28 ArrayList<LocalTime>timestamp=new ArrayList<LocalTime>(); 29 timestamp.add(LocalTime.now()); 30 for(LocalTime i:timestamp){ 31 System.out.println("格納された時刻"+i); 32 } 33 } 34 }); 35 36 StackPane root = new StackPane(); 37 root.getChildren().add(btn); 38 39 Scene scene = new Scene(root, 300, 250); 40 41 primaryStage.setTitle("タイムスタンプ"); 42 primaryStage.setScene(scene); 43 primaryStage.show(); 44 } 45 46 /** 47 * @param args the command line arguments 48 */ 49 public static void main(String[] args) { 50 launch(args); 51 } 52 53} 54
回答2件
あなたの回答
tips
プレビュー
バッドをするには、ログインかつ
こちらの条件を満たす必要があります。
2018/03/13 23:35