JAVAの初心者です。練習でJavaFXを使って既に読み込んである画像をクリアして新たにダイアログから選択した画像を表示させるプログラムを作成しているのですが、どのようにコードを書いたらベストなのか(初心者なので)思いつきません。
if文を使って書こうと思いますが、なんか他に良いのが思いつきません。ネットで探しても見つかりませんでした。
なんかいいアドバイスがあったら教えてください。よろしくお願いします。
いままでできたソースコードを上げておきます
Java
1package rensyuuyou; 2 3import java.io.*; 4import java.util.logging.Level; 5import java.util.logging.Logger; 6 7import javafx.application.Application; 8import javafx.event.ActionEvent; 9import javafx.event.EventHandler; 10import javafx.geometry.Insets; 11import javafx.geometry.Pos; 12import javafx.scene.Scene; 13import javafx.scene.control.Button; 14import javafx.scene.layout.VBox; 15import javafx.stage.Stage; 16import javafx.stage.FileChooser; 17import javafx.scene.image.Image; 18import javafx.scene.image.ImageView; 19import javafx.stage.FileChooser; 20import javafx.scene.control.Alert; 21 22 23public class Rensyuuyou extends Application { 24 25 String filepath; 26 VBox imageBox = new VBox(); 27 28 29 @Override 30 public void start(Stage stage) { 31 stage.setTitle("練習用"); 32 stage.setWidth(2000); 33 stage.setHeight(1000); 34 35 Button botan = new Button("画像表示"); 36 botan.setPrefSize(900, 30); 37 botan.setOnAction(new EventHandler<ActionEvent>() { 38 39 @Override 40 public void handle(ActionEvent event) { 41 42 FileChooser fileChooser = new FileChooser(); 43 fileChooser.setTitle("画像を開く"); 44 fileChooser.getExtensionFilters().addAll( 45 new FileChooser.ExtensionFilter("イメージファイル", "*.jpg", "*.png")); 46 File file = fileChooser.showOpenDialog(stage); 47 filepath = file.getAbsolutePath(); 48 /* 49 画像を表示する 50 */ 51 FileInputStream fis = null; 52 try{ 53 fis = new FileInputStream(filepath); 54 }catch(IOException e){ 55 Alert keikoku = new Alert(Alert.AlertType.ERROR); 56 keikoku.setContentText("ファイルが読み込めません"); 57 58 59 }finally{ 60 if(fis != null){ 61 try { 62 } catch (Exception e) { 63 } 64 } 65 } 66 Image image = new Image(fis); 67 ImageView imageView = new ImageView(image); 68 imageView.setFitHeight(500); 69 imageView.setFitWidth(1000); 70 71 imageBox.setAlignment(Pos.TOP_CENTER); 72 imageBox.setPadding(new Insets(40, 40, 40, 40)); 73 imageBox.getChildren().addAll(imageView); 74 75 } 76 }); 77 VBox hyouji = new VBox(); 78 hyouji.setAlignment(Pos.CENTER); 79 hyouji.setPadding(new Insets(30, 30, 30, 30)); 80 hyouji.getChildren().addAll(imageBox,botan); 81 82 stage.setScene(new Scene(hyouji)); 83 stage.show(); 84 85 86 87 } 88 89 public static void main(String[] args) { 90 launch(args); 91 } 92 93}
(追記)
すいません。どこの部分を変えたらいいのでしょうか? 具体的にどのように書けばいいのでしょうか? よろしくお願いします。
バッドをするには、ログインかつ
こちらの条件を満たす必要があります。
2017/02/13 13:56
2017/02/13 14:46
2017/02/15 14:25