Java - A program that displays 4 images. I can get this to work with the URLs on
ID: 3598487 • Letter: J
Question
Java - A program that displays 4 images. I can get this to work with the URLs online, but when I using my file, the images turn up blank. My code has one part with a file and three with URLs.
package exercise1;
import javafx.scene.image.Image;
import javafx.scene.image.ImageView;
import javafx.application.Application;
import javafx.geometry.Insets;
import javafx.geometry.Pos;
import javafx.scene.Scene;
import javafx.scene.layout.GridPane;
import javafx.stage.Stage;
public class DisplayImages extends Application {
@Override
public void start(Stage primaryStage)
{
GridPane pane = new GridPane();
pane.setAlignment(Pos.CENTER);
pane.setPadding(new Insets(11, 12, 13, 14));
pane.setHgap(5);
pane.setVgap(5);
//Add image nodes
Image canada = new Image("file:image/canada.bmp");
ImageView canadaView = new ImageView(canada);
pane.add(canadaView, 1, 1);
Image uk = new Image("http://3.bp.blogspot.com/-62PQ6EWMfBk/TcG3u-jRR3I/AAAAAAAAAfA/EUyVonvxG0E/s1600/British+Flag+Wallpapers+%25281%2529.png");
ImageView ukView = new ImageView(uk);
ukView.setFitHeight(50);
ukView.setFitWidth(75);
pane.add(ukView, 1, 2);
Image china = new Image("http://1.bp.blogspot.com/-UzuUsSjP9bQ/Ta5ERQOoOAI/AAAAAAAAAAQ/_653LZlNx0k/s1600/Flag_of_China.png");
ImageView chinaView = new ImageView(china);
chinaView.setFitHeight(50);
chinaView.setFitWidth(75);
pane.add(chinaView, 2, 1);
Image us = new Image("http://rapidfirebunker.net/wp-content/uploads/2013/03/american-flag2.jpg");
ImageView usView = new ImageView(us);
usView.setFitHeight(50);
usView.setFitWidth(75);
pane.add(usView, 2, 2);
Scene scene = new Scene(pane);
primaryStage.setTitle("DisplayImages");
primaryStage.setScene(scene);
primaryStage.show();
}
}
Explanation / Answer
Image class constructor takes URL of file not a file system path. In order to use your local file, u will need to load that from the same place as your classes are loaded e:g jar file in your final deployment.
A very good alternative is to use hetResource() on ur local file
Try using
Image canada = new Image(getClass().getResourceAsStream("image/canada.bmp"));
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.