I'm trying to make an application to manage some drink recipes...
I need to show the drink image in a JPanel already working with the file path like this:
ImageIcon image = new ImageIcon("src/fotos/trinidad.jpg");
The problem is that when I try to set this path setting it with the object name, the image is not being loaded.
String s = ("src/fotos/"+b.getNome().toLowerCase()+".jpg");
ImageIcon image = new ImageIcon(s);
Printing this string s I have this result:
System.out.println(s);
src/fotos/trinidad.jpg
Apparently it looks the same path, but the image is not being loaded.
What am I doing wrong?
Try something like this, if the image (path) does not exist you can catch the exception and treat accordingly.
BufferedImage drinkImage = null;
try {
drinkImage= ImageIO.read(new File("src/fotos/trinidad.jpg"));
} catch (IOException e) {
// TODO
e.printStackTrace();
}
ImageIcon image = new ImageIcon(drinkImage);
// Put image in your JPanel
Related
I'm making a small application in Java that requires me to scrape an image from a website and display it in a GUI. Now I'm not asking how to get the image's absolute URL, I'm asking how I can display it once I've gotten the absolute URL. I'm using the jsoup library as the web scraper.
I used the following piece of code to get the desired output shown in the image below (Use appropriate imports):
BufferedImage myPicture = null;
try {
URL url = new URL("https://www.w3schools.com/css/img_fjords.jpg");
URLConnection connection = url.openConnection();
connection.setRequestProperty("User-Agent", "MyAppName");
myPicture = ImageIO.read(url);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
JLabel picLabel = new JLabel(new ImageIcon(myPicture));
frame.getContentPane().add(picLabel);
For setRequestProperty, use any string in place of MyAppName, it's just a value to the User-Agent attribute in the http request made by your app
Reference Image
I've been having an issue with displaying images in Java with the ImageIcon class. The code is very simple, but it simply displays a window like
.
import javax.swing.*;
public class TestButtonIcons {
public static void main(String[] args) {
ImageIcon usFlag = new ImageIcon("images/usFlag.png");
JFrame frame = new JFrame();
JButton jbt = new JButton(usFlag);
frame.add(jbt);
frame.setSize(500, 500);
frame.setLocationRelativeTo(null);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
}
}
My image is located under the src folder, and my IDE can also detect it, since it shows
.
Also, if I change the path mentioned above into the full path, like
"/Users/Mac/Documents/Java TB/ImageIcons/src/images/usFlag.png"
The program works normally.
Any help will be appreciated.
Thanks!
ImageIcon(String) assumes that the image is located on the disk somewhere. When you place the image inside the src directory, most IDE's will bundle the image into the resulting Jar (AKA embedded resource), which means that they are no longer a "file" on the disk, but a byte stream in a zip file, so you need to access them differently.
Start by using ImageIO.read, unlike ImageIcon, it will throw an IOException when the image can't be loaded.
You need to use Class#getResource or Class#getResourceAsStream depending on how need to reference it, for example...
BufferedImage image = null;
try {
image = ImageIO.read(getClass().getResource("/images/usFlag.png"));
} catch (IOException ex) {
ex.printStackTrace();
}
Take a look at Reading/Loading an Image for more details
Make sure you use "./path" or else it might think it's an absolute path. "." is the current directory, which indicates a relative path instead of an absolute one.
Problem is in the location of the image. Place your image in source folder. Try like
JButton button = new JButton();
try {
Image img = ImageIO.read(getClass().getResource("images/usFlag.png"));
button.setIcon(new ImageIcon(img));
} catch (IOException ex) {
}
I assume that the image is in src/images.
The path you give to the constructor of ImageIcon is relative to the location of your class.
So if your class is org.example.TestButtonIcons it will look for org/example/images/usFlag.png
Hope this helps.
Currently I pass a hardcoded string file location to my object method which uses the string in the .getResources() method to load an image file. I am now trying to chooses an image using a load button and pass the loaded file location as a string into the getResource() method. I am using the filename.getAbsolutePath() method to retrieve the file location then passing the filename variable into the object method however this provides me with the following error -
Exception in thread "AWT-EventQueue-0" java.lang.NullPointerException.
The line of code that it points to having the error is the .getResources line where the image is loaded. I will post the code below to better understand my problem.
btnLoad.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
JFileChooser fc = new JFileChooser();
if (fc.showOpenDialog(null) == JFileChooser.APPROVE_OPTION)
{
File loadImage = fc.getSelectedFile();
String filename = loadImage.getAbsolutePath();
filename = filename.replaceAll("\\\\", "\\\\\\\\");
picLocation = filename;
ImageSwing imageSwing = new ImageSwing(filename);
System.out.println(filename);
}
}
The output of the file name is correct yet it still wont pass into the object.
public class ImageSwing extends JFrame
{
public JLabel label;
public ImageSwing(String S){
super("Card Stunt"); //Window Title
setLayout(new FlowLayout()); //lookup grid layout
Icon flag = new ImageIcon(getClass().getResource(S));
label = new JLabel(flag);
label.setToolTipText(S);
setSize(1350, 800);
//setMinimumSize(new Dimension(1200, 760));
}//main
}
It seems like you create an absolute filename with loadImage.getAbsolutePath(), but then you try to use this as a class path resource with new ImageIcon(getClass().getResource(S)).
Instead, you should just pass the absolute filename, as a string, to ImageIcon:
Icon flag = new ImageIcon(S);
Also, don't forget to add the label to the frame...
getContentPane().add(label);
Also, I'm not on Windows right now, but I don't think filename.replaceAll("\\\\", "\\\\\\\\"); is necessary.
I have found plenty of details on how to set a wallpaper from a drawable etc however is it possible to do this from a file location.
I have confirmed that the following code prints out the location of the file
Toast.makeText(MyWallpapers.this, "" + listFile[position].getAbsolutePath(), Toast.LENGTH_SHORT).show();
String ImageLocation = listFile[position].getAbsolutePath();
And so I have been trying something like this to get it to set the wallpaper.
WallpaperManager myWallpaperManager
= WallpaperManager.getInstance(getApplicationContext());
try {
myWallpaperManager.setResource(ImageLocation);
} catch (IOException e) {
e.printStackTrace();
}
But it doesn't like it.
Any advice?
Load the file into a Bitmap using BitmapFactory and call WallpaperManager.setBitmap
I have tried several methods to add an Icon to a JFrame. Every method work perfectly when I run it using the source code.
for example:
jframe.setIconImage(Toolkit.getDefaultToolkit().getImage("iconimages/icon.png"));
But none of them work when I run it using the jar file. I know the problem is with the path of the image file. How can I solve this?
Edit:
public Ui() {
initComponents();
setLocationRelativeTo(null);
this.setIconImage(getImageIcon("icon.png").getImage());
}
private ImageIcon getImageIcon(String fileName) {
String imageDirectory = "iconimages/";
imgURL = getClass().getResource(imageDirectory + fileName);
return new ImageIcon(imgURL);
}
I tried this but now I get a null pointer exception.
--------------------------------------------------------------------------------
Edit [Solution] : I found the solution.
I added ../ to the path additionally and it works perfectly!!! :D
ImageIcon imageIcon = new ImageIcon("../imageicons/icon.png");
this.setIconImage(imageIcon.getImage());
Thanks all for try to help me. :)
You should use a URL. Like this:
/**
* Loads and returns an {#link Image} resource.
* #param fileName name of the image resource.
* #return Image as resource.
*/
public Image getResourceImage(String fileName) {
String imageDirectory = "images/";
URL imgURL = getClass().getResource(imageDirectory + fileName);
Image image = null;
try {
image = ImageIO.read(imgURL);
} catch (IOException e) {}
return image;
}