Load image to ImageView JavaFX - java

I would like to display image(saved in project folder) in dialog window, but when I run my method showDialogWithImage I get FileNotFoundExcpetion: imgs\pic1.jpg (The system cannot find the file specified), although the image is located there.
I have tried load image on this way too:
Image image = new Image(getClass().getResourceAsStream(path));, but got the same problem.
Are there some others possibilities to load image to ImageView ?
Thank you for help!
My Java code is located in src\myProject\gui in project folder.
path="imgs\pic1.jpg" // imgs is located in project folder
public void showDialogWithImage(String path) {
final Stage dialogStage = new Stage();
logger.info(path);
InputStream is = null;
try {
is = new FileInputStream(path); // here I get FileNotFoundException
} catch (FileNotFoundException e) {
e.printStackTrace();
}
Image image = new Image(is);
ImageView view = new ImageView();
view.setImage(image);
Button btnOK = new Button("OK");
btnOK.setOnAction(new EventHandler<ActionEvent>() {
#Override
public void handle(ActionEvent event) {
dialogStage.close();
}
});
dialogStage.initModality(Modality.WINDOW_MODAL);
dialogStage.setScene(new Scene(VBoxBuilder.create()
.children(view, btnOK).alignment(Pos.CENTER)
.padding(new Insets(35)).build()));
dialogStage.show();
}

getClass().getResourceAsStream(path) will start its file search from the location of the calling class. So by using this path "imgs\pic1.jpg", you're saying this is your file structure
src\myProject\gui\imgs\pic1.jpg
To have the search traverse back, you need the extra separator before imgs. So
"\imgs\pic1.jpg"
Also, I think when you use a back slash as separator, you need to escape it. So
"\\imgs\\pic1.jpg
Or just use forward slash
"/imgs/pic1.jpg
Another option is to use a class loader, that will search from the root, where you don't need the beginning separator
getClass().getClassLoader().getResourceAsStream("imgs/pic1.png");

when you load an image with path you need replace seperator file "\" with "/" for example
String ImageName="MyImage.png";
File file = new File("src\\Messages\\Attachements\\Images");
try {
if (!file.exists()) {
FileUtils.forceMkdir(file);
}
}
} catch (Exception io) {
io.printStackTrace();
}
Image image = new Image("/Messages/Attachements/Images/"+ImageName=);
ImageReceived.setImage(image);

Related

Getting ImageIcon- image path in runtime

I'm trying to get the image file path or file name of an ImageIcon. I've created a screen in my Java gui app, which contains properties for a custom JButton (extends JButton). From that screen I'm setting some of the main button properties, as if it is enabled, focusable and its ImageIcon. The problem is that as if now, whenever I use this button class, which is in every screen btw, I'm loading all possible images for ImageIcons when the exdened JButton class is used. That causes the screen to freeze before any of the components are shown, while the images are loaded from classpath. In order to change that, in the settings screen, where I hava a JComboBox, containing all images for icons, there, at least that's what I can think of, should be a way to get only the name of the chosen ImageIcon- image path.
The buttons properties are stored in a properties file and that's where I intend to store the .png images names if I can get to them. The idea is to set the image name and when the button is loaded to the screen to look for and load only the image it's supposed to.
Here is a snipet of the button class now; The images are way more, but for demo purposes, I think those are enough. I'd be very grateful if anyone can help with this matter.
public class CustomButton extends JButton {
static Properties FieldProp;
public CustomButton (String text, String name) {
FieldProp = new LoadProperties().loadMainProp();
this.setText(text);
this.setName(name);
Image imgdel=null;
Image imgsmbl=null;
Image imgsmrd=null;
Image imgsmgr=null;
Image imgadd=null;
Image imgauto=null;
Image imgauto1=null;
Image imgavail=null;
Image imgbarc=null;
Image imgdb=null;
Image imgdoc=null;
Image imgexc=null;
Image imgexc1=null;
try {
imgdel = ImageIO.read(Objects.requireNonNull(getClass().getResource("/img/delete.png")));
imgsmbl = ImageIO.read(Objects.requireNonNull(getClass().getResource("/img/small_blue.png")));
imgsmrd = ImageIO.read(Objects.requireNonNull(getClass().getResource("/img/small_red.png")));
imgsmgr = ImageIO.read(Objects.requireNonNull(getClass().getResource("/img/small_green.png")));
imgadd = ImageIO.read(Objects.requireNonNull(getClass().getResource("/img/add_plus.png")));
imgauto = ImageIO.read(Objects.requireNonNull(getClass().getResource("/img/automation.png")));
imgauto1 = ImageIO.read(Objects.requireNonNull(getClass().getResource("/img/automation1.png")));
imgavail = ImageIO.read(Objects.requireNonNull(getClass().getResource("/img/available.png")));
imgbarc = ImageIO.read(Objects.requireNonNull(getClass().getResource("/img/barcode.png")));
imgdb = ImageIO.read(Objects.requireNonNull(getClass().getResource("/img/db.png")));
imgdoc = ImageIO.read(Objects.requireNonNull(getClass().getResource("/img/doc.png")));
imgexc = ImageIO.read(Objects.requireNonNull(getClass().getResource("/img/excel.png")));
imgexc1 = ImageIO.read(Objects.requireNonNull(getClass().getResource("/img/import.png")));
} catch (NullPointerException e) {
JOptionPane.showMessageDialog(null,e+"\n"+e.getMessage()+"\n"+ Arrays.toString(e.getStackTrace()),"",JOptionPane.ERROR_MESSAGE);
} catch (IOException e) {
JOptionPane.showMessageDialog(null,e+"\n"+e.getMessage()+"\n"+ Arrays.toString(e.getStackTrace()),"",JOptionPane.ERROR_MESSAGE);
}catch (Exception e) {
JOptionPane.showMessageDialog(null,e+"\n"+e.getMessage()+"\n"+ Arrays.toString(e.getStackTrace()),"",JOptionPane.ERROR_MESSAGE);
}
ImageIcon delIcon = new ImageIcon(imgdel);
ImageIcon blIcon = new ImageIcon(imgsmbl);
ImageIcon rdIcon = new ImageIcon(imgsmrd);
ImageIcon grIcon = new ImageIcon(imgsmgr);
ImageIcon addIcon = new ImageIcon(imgadd);
ImageIcon autoIcon = new ImageIcon(imgauto);
ImageIcon autoIcon1 = new ImageIcon(imgauto1);
ImageIcon availIcon = new ImageIcon(imgavail);
ImageIcon barcIcon = new ImageIcon(imgbarc);
ImageIcon dbIcon = new ImageIcon(imgdb);
ImageIcon docIcon = new ImageIcon(imgdoc);
ImageIcon excIcon = new ImageIcon(imgexc);
ImageIcon excIcon1 = new ImageIcon(imgexc1);
Object[] items =
{
noIcon,
delIcon,
blIcon,
rdIcon,
grIcon,
addIcon,
autoIcon,
autoIcon1,
availIcon,
barcIcon,
dbIcon,
docIcon,
excIcon,
excIcon1
};
try {
int iconPosition = Integer.parseInt(FieldProp.getProperty(this.getName() + "Icon"));
String iconProp = FieldProp.getProperty(this.getName() + "Icon");
if (!iconProp.equals("0")) {
this.setIcon((ImageIcon) items[iconPosition]);
}
}catch (Exception e){
e.printStackTrace();
}
try {
this.setEnabled((Boolean.parseBoolean(FieldProp.getProperty(this.getName() + "Enabled"))));
this.setFocusable((Boolean.parseBoolean(FieldProp.getProperty(this.getName() + "Focusable"))));
}catch(Exception e){}

Is there a way to load (with new File()) image that had been imported into the Project Folder?

I can't load image into BufferedImage Object with new File() without full path of the image.
When i'm trying to load an image.png into BufferedImage Object with new File() I face to results:
Success - when I write the whole path (C://Users//benja//Desktop/...) it works fine
Fail - when i write the path of the image that i have imported into my project. Is there a way to make it work even if i'm using new File(...)?
public class PicturePanel extends JPanel {
BufferedImage image=null;
public PicturePanel() {
try {
image = ImageIO.read(new
/*Works fine with full path: */
File("C://Users//benjamin//Desktop//Pictures//whiteFish.png"));
/*fail - throw an exception: */
//image = ImageIO.read(new
File("//RandomThingsInGui/whiteFish.png"));
} catch (IOException e) { e.printStackTrace(); }
repaint();
}
public void paintComponent(Graphics g) {
super.paintComponent(g);
g.drawImage(image, 0,0,500,250,null);
}
public static void main(String[] args) {
JFrame f = new JFrame();
f.add(new PicturePanel());
f.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
f.setSize(600,400);
f.setVisible(true);
}
What i need is to know if there is a way (and how) to load the image from an imported path (I mean from inside eclipse) or when I use new File(...) I must use full path.
thanks for helpers :)
Copy the 'whiteFish.png' file to the 'RandomThingsInGui' directory.
Can you try this?
try {
// AS-IS
//image = ImageIO.read(new File("//RandomThingsInGui/whiteFish.png"));
// TO-BE (replace '//' to '/')
image = ImageIO.read(new File("/RandomThingsInGui/whiteFish.png"));
} catch (IOException e) {
e.printStackTrace();
}

JavaFX error-dialog doesn't show up in runnable jar file because of changed graphic

I made a JavaFX error-dialog and changed default image.
This seemed fine in the first place, but when I exported the project as a runnable *.jar, this dialog simply didn't show up anymore.
I figured, when I leave the image out everything works fine but this is not a solution for me.
Code
public static void alert() throws IOException {
Alert alert = new Alert(Alert.AlertType.CONFIRMATION);
alert.setTitle("FATAL ERROR");
alert.setHeaderText("/*Error message*/");
ImageView alertImage = new ImageView(new Image(new FileInputStream(new File("*/Image-path*/"))));
alert.setGraphic(alertImage);
alert.setContentText("/*query*/");
//Button funktions
Optional<ButtonType> result = alert.showAndWait();
if (result.isPresent() && (result.get() == ButtonType.OK)) {
/*unimportant code*/
}
if (result.isPresent() && (result.get() == ButtonType.CANCEL)) {
/*unimportant code*/
}
}
Create your image as follows:
ImageView alertImage = new ImageView(getClass().getResource("/Images/image.png").toExternalForm());
It uses the ImageView(String url) constructor which will load the Image for you. As the Images folder is inside the jar the getResource will return a 'special' URL to that file. You can't reference it as a file, as the JAR is the single file that contains the image, there is no separate file of the image.

Java Swing error Exception in thread “AWT-EventQueue-0” java.lang.IllegalArgumentException: input == null [duplicate]

I am having a error for my GUI. Trying to set title bar icon then be included in a Runnable JAR.
BufferedImage image = null;
try {
image = ImageIO.read(getClass().getClassLoader().getResource("resources/icon.gif"));
}
catch (IOException e) {
e.printStackTrace();
}
frame.setIconImage(image);
Here is the error I am getting:
Exception in thread "main" java.lang.IllegalArgumentException: input == null!
at javax.imageio.ImageIO.read(Unknown Source)
at GUI.<init>(GUI.java:39)
at GUI.main(GUI.java:351)
The image is in the correct directory which "resources" folder is the root of the
project file
First of all, change this line :
image = ImageIO.read(getClass().getClassLoader().getResource("resources/icon.gif"));
to this :
image = ImageIO.read(getClass().getResource("/resources/icon.gif"));
More info, on as to where lies the difference between the two approaches, can be found on this thread - Different ways of loading a Resource
For Eclipse:
How to add Images to your Resource Folder in the Project
For NetBeans:
Handling Images in a Java GUI Application
How to add Images to the Project
For IntelliJ IDEA:
Right-Click the src Folder of the Project. Select New -> Package
Under New Package Dialog, type name of the package, say resources. Click OK
Right Click resources package. Select New -> Package
Under New Package Dialog, type name of the package, say images. Click OK
Now select the image that you want to add to the project, copy it. Right click resources.images package, inside the IDE, and select Paste
Use the last link to check how to access this file now in Java code. Though for this example, one would be using
getClass().getResource("/resources/images/myImage.imageExtension");
Press Shift + F10, to make and run the project. The resources and images folders, will be created automatically inside the out folder.
If you are doing it manually :
How to add Images to your Project
How to Use Icons
A Little extra clarification, as given in this answer's first
code example.
QUICK REFERENCE CODE EXAMPLE(though for more detail consider, A little extra clarification link):
package swingtest;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.IOException;
import javax.imageio.ImageIO;
import javax.swing.*;
/**
* Created with IntelliJ IDEA.
* User: Gagandeep Bali
* Date: 7/1/14
* Time: 9:44 AM
* To change this template use File | Settings | File Templates.
*/
public class ImageExample {
private MyPanel contentPane;
private void displayGUI() {
JFrame frame = new JFrame("Image Example");
frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
contentPane = new MyPanel();
frame.setContentPane(contentPane);
frame.pack();
frame.setLocationByPlatform(true);
frame.setVisible(true);
}
private class MyPanel extends JPanel {
private BufferedImage image;
public MyPanel() {
try {
image = ImageIO.read(MyPanel.class.getResource("/resources/images/planetbackground.jpg"));
} catch (IOException ioe) {
ioe.printStackTrace();
}
}
#Override
public Dimension getPreferredSize() {
return image == null ? new Dimension(400, 300): new Dimension(image.getWidth(), image.getHeight());
}
#Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
g.drawImage(image, 0, 0, this);
}
}
public static void main(String[] args) {
Runnable runnable = new Runnable() {
#Override
public void run() {
new ImageExample().displayGUI();
}
};
EventQueue.invokeLater(runnable);
}
}
There's a much easier way to load and set an image as a frame icon:
frame.setIconImage(
new ImageIcon(getClass().getResource("/resources/icon.gif")).getImage());
And thats all :)! You don't even have to use a try-catch block because ImageIcon does not throw any declared exceptions. And due to getClass().getResource(), it works both from file system and from a jar depending how you run your application.
If you need to check whether the image is available, you can check if the URL returned by getResource() is null:
URL url = getClass().getResource("/resources/icon.gif");
if (url == null)
System.out.println( "Could not find image!" );
else
frame.setIconImage(new ImageIcon(url).getImage());
The image files must be in the directory resources/ in your JAR, as shown in How to Use Icons and this example for the directory named images/.

Component Position (Vaadin)

I have a simple portlet with a few components : 3 Button objects, 1 Slider, 1 MenuBar and a picture assigned to a Label (generated by servlet). Now when I switch between pictures for a Label (I have more of them), I want the picture Label to be placed at the old picture Label object's position:
My picture Label is in the left corner of the portlet. The Button objects, MenuBar, and the Slider are under the picture Label when I select another picture Label the new picture Label is being drawn under the other components (under the Button objects , MenuBar , Slider ) so the Button objects... are top and the picture Label is at the bottom of the portlet
for example, I change the background of the picture Label by selecting the color in the menu :
newItem1.addItem("Blue",new Command(){
public void menuSelected(MenuItem selectedItem){
if(pictureA.isVisible()){
pictureB.setVisible(false);
pictureC.setVisible(false);
window.removeComponent(pictureA);
pictureA= new Label("<img src=http://localhost:8888/portlet/KiviatDiagramm?background=blue", Label.CONTENT_XHTML);
window.addComponent(pictureA);
} else {
window.showNotification("", Notification.TYPE_WARNING_MESSAGE);
}
}
});
UPDATE :
I have switched from Label objects to embedded images (Embedded) (which is a lot better) I have tried to reassign the resource on the Embedded object with the new color but it doesn't work, here is what I've done :
public void init() {
URL PictureAUrl= null;
try {
pictureAUrl= new URL("http://localhost:8888/portlet/pictureA");
} catch (MalformedURLException e) {
e.printStackTrace();
}
URL PictureBUrl= null;
try {
pictureAUrl= new URL("http://localhost:8888/portlet/pictureB");
} catch (MalformedURLException e) {
e.printStackTrace();
}
URL pictureCUrl= null;
try {
pictureCUrl= new URL("http://localhost:8888/portlet/pictureC");
} catch (MalformedURLException e) {
e.printStackTrace();
}
final Embedded pictureA = new Embedded("", new ExternalResource(pictureAURL));
pictureA .setType(Embedded.TYPE_IMAGE);
final Embedded pictureB = new Embedded("", new ExternalResource(pictureBURL));
pictureB .setType(Embedded.TYPE_IMAGE);
final Embedded pictureC = new Embedded("", new ExternalResource(pictureCURL));
pictureC .setType(Embedded.TYPE_IMAGE);
newItem.addItem("ColorBlue", new Command(){
public void menuSelected(MenuItem selectedItem) {
if(!pictureA.equals(pictureB )){
Resource newPictureResource = new ExternalResource("http://localhost:8888/portlet/pictureA?background=blue");
newPictureResource.setType(Embedded.TYPE_IMAGE);
pictureA.setResource(newPictureResource);
}
else {
window.showNotification("Please select pictureA");
}
}
});
rickthomas is correct, you should use the replaceComponent method. I'm pretty sure that the main problem here is that after you have removed the picture, you call addComponent(pictureA) which actually adds the component to the end of the component list. If you don't have a reference to the old picture and it's the first component, then you can use this:
window.replaceComponent(window.getComponentIterator().next(), newPicture);
In addition to that, you don't have to write HTML to show images. You can use Embedded.
If the images are in your classpath, you can use the following:
Embedded newPicture = new Embedded("", new ClassResource("my-picture.png", myApplication));
newPicture.setType(Embedded.TYPE_IMAGE);
window.replaceComponent(oldPicture, newPicture);
If they are found somewhere else, use this:
URL url = new URL("http://localhost:8888/portlet/KiviatDiagramm?background=blue");
Embedded newPicture = new Embedded("", new ExternalResource(url));
newPicture.setType(Embedded.TYPE_IMAGE);
window.replaceComponent(oldPicture, newPicture);
This might solve your problem.
Looking at the Vaadin API javadoc,
I found this
public void replaceComponent(Component oldComponent,Component newComponent)
I haven't tested it... but it should work.

Categories