Java fx Image path - image

i have a problem with javafx' ImageView.
I try to load a simple jpg, as an image and add it to an ImageView.
But Javafx can't finde the resouce.
Image image = new Image("image.jpg");
ImageView iv1_1 = new ImageView();
iv1_1.setImage(image);
the exception i get is this one:
Exception in thread "JavaFX Application Thread" java.lang.IllegalArgumentException: Invalid URL: Invalid URL or resource not found
it is crashing in the line, where the image is created.
Here is a picture of the Project:
enter link description here
(I am not allowed to post pictures.)

Use getClass().getResource("image.jpg)

Please find below example to load image using JavaFX.
import javafx.application.Application;
import javafx.scene.Scene;
import javafx.scene.image.Image;
import javafx.scene.image.ImageView;
import javafx.scene.layout.StackPane;
import javafx.stage.Stage;
public class LoadImage extends Application {
public static void main(String[] args) {
Application.launch(args);
}
#Override
public void start(Stage primaryStage) {
primaryStage.setTitle("Load Image");
StackPane sp = new StackPane();
Image img = new Image("javafx.jpg");
ImageView imgView = new ImageView(img);
sp.getChildren().add(imgView);
//Adding HBox to the scene
Scene scene = new Scene(sp);
primaryStage.setScene(scene);
primaryStage.show();
}
}
Create one source folder with name Image in your project and add your image to that folder otherwise you can directly load image from external URL like following.
Image img = new Image(
"http://mikecann.co.uk/wp-content/uploads/2009/12/javafx_logo_color_1.jpg"
);

this worked for me
Image image = null;
try {
image = new Image(new FileInputStream("image.jpg"));
} catch (FileNotFoundException e) {
e.printStackTrace();
}
ImageView view = new ImageView();
view.setImage(image);

Related

Load external images in JavaFX

I am trying to load external images using JavaFX, but since using the new raspberry 4, I am unable to load external images, I can however load images internal to the Jar file.
as an example I have attached the code below. this works on my mac and raspberry pi3 but does not work for the raspberry pi 4 running Debian Buster, the only difference between the raspberry pi 4 and the there computers is that the RPI4 is running the latest JavaFX openjdk 14.0.1 and the other computers are running version 1.8.0_20.
on all instances i get a print of true for System.out.println(file.exists());
the RPI4 can load images inside the Jar, any help please
Code:
package application;
import java.io.File;
import javafx.application.Application;
import javafx.stage.Stage;
import javafx.scene.Scene;
import javafx.scene.image.Image;
import javafx.scene.image.ImageView;
import javafx.scene.layout.BorderPane;
import javafx.scene.layout.StackPane;
public class Main extends Application {
public static void main(String[] args) {
launch(args);
}
#Override
public void start(Stage primaryStage) throws Exception {
Scene scene = new Scene(setupScene(), 300, 300);
primaryStage.setScene(scene);
primaryStage.setTitle("Image Screen");
primaryStage.show();
}
StackPane setupScene() {
StackPane root = new StackPane();
ImageView imageView = new ImageView();
imageView.setPreserveRatio(true);
imageView.setSmooth(true);
File file = new File("/home/pi/dscf4452.jpg");
System.out.println(file.exists());
System.out.println(file);
Image image = new Image(file.toURI().toString());
// Image image = new Image(getClass().getClassLoader().getResource("test.jpg").toString());
imageView.setImage(image);
root.setPrefSize(250, 250);
imageView.setFitHeight(root.getPrefHeight());
imageView.setFitWidth(root.getPrefWidth());
root.getChildren().add(imageView);
return root;
}
}

How to change size of ImageView when changing size of window in javafx gui

I have not worked much with gui before, but I am trying to learn it by building a javafx application using SceneBuilder. Now I have trouble getting ImageView to resize when I resize the window.
I am using a gridPane, and i have placed a ImageView on a anchorPane inside one of the routes in the gridPane. The gridPane is changing size when I change the size of my window when i run the application, but the ImageView does not change size. I want the Imageview to change size correspondingly when i change the size of the window when i run the application.
have tried to read similar issues here on the forum, but have not found a solution that I can use, Does anyone have a good way to do this?
Really appreciate all answers.
You can use binding for simplicity, here the full example code
import javafx.application.Application;
import javafx.scene.Scene;
import javafx.scene.image.Image;
import javafx.scene.image.ImageView;
import javafx.scene.layout.AnchorPane;
import javafx.scene.layout.GridPane;
import javafx.stage.Stage;
public class Main extends Application {
#Override
public void start(Stage primaryStage){
GridPane gridPane = new GridPane();
AnchorPane anchorPane = new AnchorPane();
// Set image with url
Image image = new Image("https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcR-524e2cCaY9TUn8vglN3nqqOlT0jIJIIty-Z81S49q9Np6Yws");
ImageView imageView = new ImageView(image);
// Bind the imageView width property to gridPane width property
// So, if width of gridPane change, the width of imageView automatically will be change
imageView.fitWidthProperty().bind(gridPane.widthProperty());
// Make the ratio same with original image
imageView.setPreserveRatio(true);
anchorPane.getChildren().add(imageView);
gridPane.getChildren().add(anchorPane);
Scene scene = new Scene(gridPane, 600, 400);
primaryStage.setTitle("Hello World");
primaryStage.setScene(scene);
primaryStage.show();
}
public static void main(String[] args) {
launch(args);
}
}

Can't load an Image file onto my class

public class Picture extends Application {
#Override
public void start(Stage primaryStage){
Pane pane = new HBox(100);
pane.setPadding(new Insets(5,5,5,5));
Next I am trying to upload an image form class package
I have copied the image file from my laptop into the
same package as where this class is (Picture)
Image image = new Image("https://
picturethismaths.files.wordpress.com/2016/03/fig6bigfor
blog.png?w=419&h=364");
Next I am trying to upload an image from online
/*Image image2 = new Image(getClass().getResourceAsStream("Image image =
new Image(getClass().getResourceAsStream(\"pic.png\"));\n" +
" title.setImage(image);"));*/
/* This is the ERROR it gives me ----->> Caused by:
java.lang.IllegalArgumentException: Invalid URL or resource
not found
at javafx.scene.image.Image.validateUrl(Image.java:983)*/
pane.getChildren().add(new ImageView(image));
ImageView imageView2 = new ImageView(image);
imageView2.setFitHeight(100);
imageView2.setFitWidth(100);
pane.getChildren().add(imageView2);
ImageView imageView3 = new ImageView(image);
imageView3.setRotate(90);
pane.getChildren().add(imageView3);
Scene scene= new Scene(pane);
primaryStage.setTitle("ShowImage");
primaryStage.setScene(scene);
primaryStage.show();
}
public static void main(String[] args){
Application.launch(args);
}
}
I know this question been before, but believe me I have tried all the solutions given in the answers any nothing worked.
Please only ones who want to help write, no Jokers!
If the image you want to load is in the same directory as the class then try
Image image2 = new Image(getClass().getResourceAsStream("pic.png"));

When Loading Image Using BufferdImage and ImageIO it Clears my Whole Frame and Does Not Display Image

I and making a program using basic GUI involving buttons, frames, and panels, and everything was fine until I tried to load an image from my project folder. When i add the line of code
try{
titleImage = ImageIO.read(new File("mouse_title_resize.png"));
}
catch(Exception e){}
After I run the program my whole frame just becomes blank whereas before I had some JButtons on it.All the code I had before the try-catch line worked perfectly fine and I tested to see that the only thing that breaks it is this line of code. I receive no errors or anything and I have the image in my project folder and it seems that the image loaded fine, except it wont show up on the frame, and everything else on the frame disappears. I just don't understand why it clears my whole frame when i load the image.
Here is the full code:
This is the class that extends JFrame
package mouse.click.game;
import java.awt.Dimension;
import java.awt.Point;
import java.awt.Toolkit;
import javax.swing.JFrame;
public class MouseClickGame extends JFrame {
//Constants to define the frame width and height including borders
public final int FRAME_WIDTH = 600;
public final int FRAME_HEIGHT = 600;
//Dimension from Toolkit to be able to get width and height of screen
public Dimension sizeTool = Toolkit.getDefaultToolkit().getScreenSize();
//Using sizeTool to get width of screen
public double xResolution = sizeTool.getWidth();
//Using sizeTool to get height of screen
public double yResolution = sizeTool.getHeight();
//Creating a point object that is defined as the center of the screen
public Point middleOfScreen = new Point((int) (xResolution / 2) - (FRAME_WIDTH / 2), (int) (yResolution / 2) - (FRAME_HEIGHT / 2));
public MouseClickGame() {
super("WELCOME :D");
setSize(FRAME_WIDTH, FRAME_HEIGHT);
setResizable(false);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setVisible(true);
setLocation(middleOfScreen);
add(new MouseClickPanel());
}
public static void main(String[] args) {
//Calling constructor
MouseClickGame mainClickGame = new MouseClickGame();
}
}
And here is the class that extends JPanel (these are the only two classes in my project)
package mouse.click.game;
import java.awt.Dimension;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import javax.imageio.ImageIO;
import javax.swing.Box;
import javax.swing.BoxLayout;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JLabel;
import javax.swing.JPanel;
public class MouseClickPanel extends JPanel {
JButton buttonPlay = new JButton("Play");
JButton buttonContinue = new JButton("Continue");
JButton buttonOptions = new JButton("Options");
JButton buttonExit = new JButton("Exit");
BoxLayout boxLay = new BoxLayout(this, BoxLayout.Y_AXIS);
Dimension menuButtonSize = new Dimension(300, 30);
Dimension spacingBetweenButtons = new Dimension(0, 30);
BufferedImage titleImage;
public MouseClickPanel() {
try {
titleImage = ImageIO.read(new File("C:\\Users\\Justin\\Desktop\\mouse_title.png"));
} catch (IOException e) {
}
setLayout(boxLay);
add(Box.createVerticalGlue());
add(new JLabel(new ImageIcon(titleImage)));
//Adding glue to force buttons away from top of panel
add(Box.createVerticalGlue());
add(buttonPlay);
//Vertical spacing between buttons
add(Box.createRigidArea(spacingBetweenButtons));
add(buttonContinue);
add(Box.createRigidArea(spacingBetweenButtons));
add(buttonOptions);
add(Box.createRigidArea(spacingBetweenButtons));
add(buttonExit);
//Adding glue to force buttons away from bottom of panel
add(Box.createVerticalGlue());
//Aligning all buttons to centered horizontally
buttonPlay.setAlignmentX(Box.CENTER_ALIGNMENT);
buttonContinue.setAlignmentX(Box.CENTER_ALIGNMENT);
buttonOptions.setAlignmentX(Box.CENTER_ALIGNMENT);
buttonExit.setAlignmentX(Box.CENTER_ALIGNMENT);
//Setting button sizes
buttonPlay.setMaximumSize(menuButtonSize);
buttonContinue.setMaximumSize(menuButtonSize);
buttonOptions.setMaximumSize(menuButtonSize);
buttonExit.setMaximumSize(menuButtonSize);
}
}
Literally if i get ride of the titleImage = and add(new JLabel) lines everything goes back to normal
My guess is that you've just got the path wrong -- a common mistake. In that case, you should be getting an exception like:
Exception in thread "main" javax.imageio.IIOException: Can't read input file!
at javax.imageio.ImageIO.read(ImageIO.java:1301)
at jonathanrmiproject.MyProject.main(JonathanRmiProject.java:24)
This simple example works for me:
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import javax.imageio.ImageIO;
import javax.naming.NamingException;
import javax.swing.ImageIcon;
import javax.swing.JFrame;
import javax.swing.JLabel;
public class MyProject {
public static void main(String[] args) throws NamingException, IOException {
BufferedImage img = ImageIO.read(new File("myimage.jpg"));
JLabel label = new JLabel(new ImageIcon(img));
JFrame f = new JFrame();
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.getContentPane().add(label);
f.pack();
f.setLocation(200, 200);
f.setVisible(true);
}
}
I am using Netbeans IDE, and I have saved the image file to "C:\Users\David.Sharpe\MyProject\myimage.jpg".
I should add that if this is not the case, and you do have the correct path, then you need to post a more detailed question so that someone can help you. Include the code to reproduce the problem.
UPDATE: Wow literally the reason it wasn't showing up was because i called setVisble(true) too early. I can't believe it was something that simple. I guess that explains why one time everything would show up and it would be fine but then every time after nothing showed up.
So in my constructor I had
public class MouseClickGame extends JFrame {
public MouseClickGame() {
super("WELCOME :D");
setSize(FRAME_WIDTH, FRAME_HEIGHT);
setResizable(false);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setLocation(middleOfScreen);
setVisible(true);
add(new MouseClickPanel());
}
public static void main(String[] args) {
//Calling constructor
MouseClickGame mainClickGame = new MouseClickGame();
}
}
when all I had to do was put the setVisble() after the add(newMouseClickPanel())
Thank you DavidS for your suggestions :D

How to add an inline image to the end of a string in a TextArea in JavaFX?

I am trying to add an emoji to my chat program when my client types :)
I am trying to add this in the FXML controller. I have captured when the user types :) using the following code snippet :
if(chat.contains(":)")) {
...
}
My chat is printed into a textarea named taChat
taChat.appendText(chat + '\n');
Any help is appreciated!
A better approach would be to use TextFlow instead of using TextArea.
Advantages :
Individual Text are treated as children to the TextFlow. They can be added and accessed individually.
ImageView can be added directly to the TextFlow as a child.
A simple chat window with support for smiley :)
import javafx.application.Application;
import javafx.geometry.Insets;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.control.TextField;
import javafx.scene.image.ImageView;
import javafx.scene.input.KeyCode;
import javafx.scene.layout.HBox;
import javafx.scene.layout.Priority;
import javafx.scene.layout.VBox;
import javafx.scene.text.Text;
import javafx.scene.text.TextFlow;
import javafx.stage.Stage;
public class ChatWindowWithSmiley extends Application {
public void start(Stage primaryStage) {
TextFlow textFlow = new TextFlow();
textFlow.setPadding(new Insets(10));
textFlow.setLineSpacing(10);
TextField textField = new TextField();
Button button = new Button("Send");
button.setPrefWidth(70);
VBox container = new VBox();
container.getChildren().addAll(textFlow, new HBox(textField, button));
VBox.setVgrow(textFlow, Priority.ALWAYS);
// Textfield re-sizes according to VBox
textField.prefWidthProperty().bind(container.widthProperty().subtract(button.prefWidthProperty()));
// On Enter press
textField.setOnKeyPressed(e -> {
if(e.getCode() == KeyCode.ENTER) {
button.fire();
}
});
button.setOnAction(e -> {
Text text;
if(textFlow.getChildren().size()==0){
text = new Text(textField.getText());
} else {
// Add new line if not the first child
text = new Text("\n" + textField.getText());
}
if(textField.getText().contains(":)")) {
ImageView imageView = new ImageView("http://files.softicons.com/download/web-icons/network-and-security-icons-by-artistsvalley/png/16x16/Regular/Friend%20Smiley.png");
// Remove :) from text
text.setText(text.getText().replace(":)"," "));
textFlow.getChildren().addAll(text, imageView);
} else {
textFlow.getChildren().add(text);
}
textField.clear();
textField.requestFocus();
});
Scene scene = new Scene(container, 300, 400);
primaryStage.setScene(scene);
primaryStage.show();
}
public static void main(String[] args) {
launch(args);
}
}
Output
For unicode Emoji support, please visit How to support Emojis

Resources