JavaFXの質問です。ファイルから文字列を読み込んでTextAreaに表示させようとしているのですが、以下のコードでsetTextで設定しようとするとNullPointerExceptionが出ます。初期設定がまずいかと思われますがJavaFXはよくわかりません。なお、以下のコードでは読み込んだファイルの文字列は無視し、「USA!」という文字列を出力するようにしています。
よろしくお願いします。
java
1package application; 2 3import java.io.BufferedReader; 4import java.io.File; 5import java.io.FileReader; 6import java.io.PrintWriter; 7import java.io.StringWriter; 8 9import javafx.application.Application; 10import javafx.fxml.FXML; 11import javafx.fxml.FXMLLoader; 12import javafx.scene.Scene; 13import javafx.scene.control.Alert; 14import javafx.scene.control.Alert.AlertType; 15import javafx.scene.control.TextArea; 16import javafx.scene.layout.BorderPane; 17import javafx.stage.Stage; 18 19 20public class Main extends Application { 21 @FXML 22 private TextArea txtA; 23 24 @Override 25 26 public void start(Stage primaryStage) { 27 try { 28 BorderPane root = (BorderPane)FXMLLoader.load(getClass().getResource("Sample.fxml")); 29 Scene scene = new Scene(root,400,400); 30 scene.getStylesheets().add(getClass().getResource("application.css").toExternalForm()); 31 primaryStage.setScene(scene); 32 primaryStage.show(); 33 34 35 36 File file = new File("C:\\Users\\mscat\\tmpData.dat"); 37 if (!file.exists()) { 38 file.createNewFile(); 39 Alert alert = new Alert(AlertType.INFORMATION); 40 alert.setTitle("Information Dialog"); 41 alert.setHeaderText("ファイルが無かったので作りました"); 42 alert.setContentText(null); 43 alert.show(); 44 } else { 45 FileReader filereader = new FileReader(file); 46 BufferedReader br = new BufferedReader(filereader); 47 String str = br.readLine(); 48 49 while(str != null){ 50 txtA.setText("USA!"); 51// tx.setText(str); 52 str = br.readLine(); 53 } 54 55 br.close(); 56 57 58 } 59 60 61 } catch (Exception e) { 62 // エラーのスタックトレースを表示 63 StringWriter sw = new StringWriter(); 64 PrintWriter pw = new PrintWriter(sw); 65 e.printStackTrace(pw); 66 pw.flush(); 67 String str = sw.toString(); 68 69 Alert alert = new Alert(AlertType.INFORMATION); 70 alert.setTitle("Information Dialog"); 71 alert.setHeaderText("例外発生!"+ str); 72 alert.setContentText(null); 73 alert.show(); 74 75 } 76 } 77 78 public static void main(String[] args) { 79 launch(args); 80 } 81} 82 83Sample.fxmlは 84<?xml version="1.0" encoding="UTF-8"?> 85 86<?import javafx.scene.text.*?> 87<?import javafx.scene.control.*?> 88<?import java.lang.*?> 89<?import javafx.scene.layout.*?> 90<?import javafx.scene.layout.BorderPane?> 91 92<BorderPane xmlns="http://javafx.com/javafx/8" xmlns:fx="http://javafx.com/fxml/1" fx:controller="application.SampleController"> 93 <center> 94 <Pane prefHeight="400.0" prefWidth="600.0" BorderPane.alignment="TOP_LEFT"> 95 <children> 96 <TextArea layoutY="48.0" prefHeight="352.0" prefWidth="600.0"> 97 <font> 98 <Font size="14.0" /> 99 </font></TextArea> 100 </children> 101 </Pane> 102 </center> 103</BorderPane> 104
回答1件
あなたの回答
tips
プレビュー
バッドをするには、ログインかつ
こちらの条件を満たす必要があります。
2017/02/14 15:14
2017/02/14 15:58