Java JPanel import image using eclipse - java

I am using eclipse and wondering where to put an image so that I can import it into java. I am trying to import an image called viewport.png into JPanel from a folder called pictures that I have placed in my src folder within my workspace. This is what I have tried:
private Image viewport = new ImageIcon("src/images/viewport.png").getImage();
then of course later,
g.drawImage(viewport, 2, 2, null);
I really just want to be able to import a picture from the same folder, as this project is being moved to another computer where it will have a different path, but still be in the same folder. I was wondering if there is a shortcut to finding it that way (just be looking in the same folder as the classes are in).

Access the image via the classpath. You can do it by using getClass().getResource() which returns an URL you can pass the ImageIcon(URL) or ImageIO.read(URL) (which returns an Image. The latter is preferred, as an exception will be thrown is something is wrong with the path
BufferedImage viewPort;
...
try {
viewPort = ImageIO.read(getClass().getResource("/pictures/viewport.png"));
} catch (IOException ex) {
// print some message
}
Your pictures should be in the src
ProjectRoot
src
pictures
viewport.png

Related

Changed LWJGL icon not staying the same after export through JARSPLICE (Java)

I've got a problem with changing the taskbar icon in LWJGL after exporting to a runnable program. Changing the icon in the debug mode is not a problem.
I can change the icon like so:
Display.setIcon(loadIcon("src/com/root/game/res/favicon.png"));
private static ByteBuffer[] byteBufferArray;
private static BufferedImage bufferedImage;
private static ImageIOImageData imageIOdata;
private static ByteBuffer[] loadIcon(String path) {
imageIOdata = new ImageIOImageData();
try {
bufferedImage = ImageIO.read(new File(path));
byteBufferArray = new ByteBuffer[] {imageIOdata.imageToByteBuffer(bufferedImage, false, false, null)};
} catch (IOException e) {
e.printStackTrace();
}
return byteBufferArray;
}
After doing all of that, the icon indeed changes.
The problem is, that after I actually export the program to .jar file and subsequently export the program to a new runnable .jar file with all the native libraries and needed .jar files through a program called Jarsplice, the icon changes back to the default LWJGL icon, as if I didn't even change it in the first place.
Could someone please give me a tip or preferably a solution to how I could make this work?
Thank you!
Make sure the logo is in a folder. Then right click the project and go to build path > configure build path. Then go to the libraries tab and either click on add class folder if the folder is in the project or add external class folder if the folder is somewhere else on your drive. Then navigate to the folder containing the logo and click ok. After you've done that try exporting again and see how it goes :)

How do I add a resources folder to my Java project in Eclipse

I want to have a place to store my image files to use in my Java project (a really simple class that just loads an image onto a panel). I have looked everywhere and cannot find how to do this. How do I do this?
I have tried adding a new folder to the project, adding a new class folder to the project, and adding a new source folder to the project. No matter what I do, I always get a IOException. The folders always say they are on the build path, so I'm not sure what to do.
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import javax.imageio.ImageIO;
import javax.swing.JFrame;
import javax.swing.JPanel;
public class PracticeFrame extends JFrame{
private static BufferedImage image;
Thread thread;
public PracticeFrame() {
super();
setPreferredSize(new Dimension(640,480));
setResizable(false);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
pack();
setVisible(true);
}
public static void main (String[] args) {
PracticeFrame pframe = new PracticeFrame();
try {
image = ImageIO.read(new File("/islands.png"));
} catch (IOException e) {
e.printStackTrace();
}
JPanel panel = new JPanel() {
#Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
g.drawImage(image,0,0,null);
}
};
panel.setBackground(Color.BLUE);
panel.repaint();
pframe.add(panel);
}
}
EDIT: Something that worked for me, and I have no idea why, was adding the main/res/ folder as a class folder and then removing it. I ran it while the /main/res/ was part of the build path as a class folder and it still didn't work. When i added it, i got a popup that told me something about excluded filters. But when i removed the folder from the libraries in the build path, and changed my file path to:
image = ImageIO.read(new File("src/main/res/islands.png"));
I at least stopped getting the IOException thrown. I must not be adding the image to the panel correctly, because it's not showing up, but at least it found the file (I think).
When at the "Add resource folder",
Build Path -> Configure Build Path -> Source (Tab) -> Add Folder -> Create new Folder
add "my-resource.txt" file inside the new folder.
Then in your code:
InputStream res =
Main.class.getResourceAsStream("/my-resource.txt");
BufferedReader reader =
new BufferedReader(new InputStreamReader(res));
String line = null;
while ((line = reader.readLine()) != null) {
System.out.println(line);
}
reader.close();
To answer your question posted in the title of this topic...
Step 1--> Right Click on Java Project, Select the option "Properties"
Step 2--> Select "Java Build Path" from the left side menu, make sure you are on "Source" tab, click "Add Folder"
Step 3--> Click the option "Create New Folder..." available at the bottom of the window
Step 4--> Enter the name of the new folder as "resources" and then click "Finish"
Step 5--> Now you'll be able to see the newly created folder "resources" under your java project, Click "Ok", again Click "Ok"
Final Step --> Now you should be able to see the new folder "resources" under your java project
After adding a resource folder try this :
ClassLoader classLoader = Thread.currentThread().getContextClassLoader();
InputStream input = classLoader.getResourceAsStream("test.png");
try {
image = ImageIO.read(input);
} catch (IOException e) {
e.printStackTrace();
}
Build Path -> Configure Build Path -> Libraries (Tab) -> Add Class Folder, then select your folder or create one.
Right click on project >> Click on properties >> Java Build Path >> Source >> Add Folder
If you have multiple sub-projects then you need to add the resources folder to each project's run configuration class path like so:
Ensure the new path is top of the entries and then the runtime will check that path first for any resources (before checking sub-paths)
Try To Give Full path for reading image.
Example
image = ImageIO.read(new File("D:/work1/Jan14Stackoverflow/src/Strawberry.jpg"));
your code is not producing any exception after giving the full path.
If you want to just read an image file in java code.
Refer the following - http://docs.oracle.com/javase/tutorial/2d/images/examples/LoadImageApp.java
If the object of your class is created at end your code works fine for me and displays the image
// PracticeFrame pframe = new PracticeFrame();//comment this
new PracticeFrame().add(panel);
If aim is to create a resources folder parallel to src/main/java, then do the following:
Right Click on your project > New > Source Folder
Provide Folder Name as src/main/resources
Finish

Image not showing in applet

I have a small JApplet that is supposed to simply import an image and display it on screen. However, I am having some trouble with it.
private Image logo1;
public void init() {
logo1 = getImage( getCodeBase(), "Penguins.jpg" );
}
#Override
public void paint( Graphics g ) {
g.drawImage( logo1, 0, 0, this );
}
That is essentially my entire program. Is there any problem with it? I am assuming one of the problems might be that the picture might have to be in a specific part of your computer or something like that...The address for this image is C:\Users\Public\Pictures\Sample Pictures
The reason that getCodeBase() is in the method call of getImage() is to get the codebase location.
The codebase is the folder that holds all of your source packages. It's most likely the folder above your src folder for your project. Here's the basic structure of a normal project (at least my projects):
-MyProject - This is the codebase
-src - All of your code is probably in this folder. All packages show up as folders here
-bin - When your code compiles, it ends up here
-data - This is where all of the resources are held (my preference)
-images - Pretty obvious, the image would go here
-Penguin.jpg - Your image
All this leads up to this answer: With the above structure, your call to getImage() should read:
getImage(getCodeBase(), 'data/images/Penguin.jpg');
Try including the image that you want to display in the folder of your java program. Sometimes if the image is in another folder, it's not displayed in the applet.
I too faced a similar problem. Just copy the image into your project folder.
public void init() {
Picture = getImage(getDocumentBase(),"image.gif");
}
I use this code. Do following steps to add your image:
Clean and Build the project
Add the image into build folder of your project.
Run the project.

Why is there no image when running from a .jar file?

I'm trying to make my panel show image as background. I already can do that in NetBeans, but when I build my jar and run it image doesn't show there. I know I have to access it differently. I have seen many tutorials but every one of them shows how to do it with ImageIcon, but I don't need that, I need just Image. Can anyone point out what piece of code do I need to do this? Thanks.
This is my code for backgrounded JPanel:
public class JPanelWB extends JPanel { // Creates JPanel with given image as background.
private Image backgroundImage;
public JPanelWB(String fileName){
try {
backgroundImage = ImageIO.read(new File(fileName));
} catch (IOException ex) {
new JDialog().add(new Label("Could not open image."+ex.getMessage()));
}
}
#Override
public void paintComponent(Graphics g) {
super.paintComponent(g);
// Draw the background image.
g.drawImage(backgroundImage, 0, 0, getWidth(),getHeight(),this);
}
}
Yeah, you're trying to read in the image as a file -- don't do that since files don't exist within a Jar file. Instead read it in as a resource.
Something like so:
public JPanelWB(String resourceName){
try {
// backgroundImage = ImageIO.read(new File(resourceName));
backgroundImage = ImageIO.read(getClass().getResource(resourceName));
} catch (IOException ex) {
new JDialog().add(new Label("Could not open image."+ex.getMessage()));
}
}
But note that resource path is different from file path. The resource path is relative to the location of your class files.
If you want to read new image and import it as background, people smarter than me already answered your question.
But, if your problem is similar to mine, then this migh help:
If you already have images to show, then the point is to call them from absolute path. Executable class form JAR will read drive created inside virtual machine, not the physical drive in your computer.
Put images in short-pathed folder like
C:\J\proj\img\
and call them with absolute path like
"C:\\J\\proj\\img\\your_image.png" // (Don't forget the double backslashes.)
(If you don't mind path lenght, leave them in image folder inside your project package, and call them from there.)
NetBeans will pack them into JAR with absolute path. On execution JRE will create JVM with that path in it, take the images from JAR and put them to that virtual path. Class will be able to find them, because it doesn't read path from physical drive, but from own virtual one newly created inside JVM.
In that case avoiding ImageIcon is just more clutter, not less.
You can add "blackBoard" as JLabel to be background to your JFrame, set its layout to null, something like this:
private JLabel blackBoard;
private JLabel noteToSelf;
//.....
blackBoard = new JLabel();
noteToSelf = new JLabel();
//.....
// putting JLabel "blackBoard" as background into JFrame
blackBoard.setIcon(new ImageIcon("c:\\Java\\images\\MarbleTable.png"));
getContentPane().add(blackBoard);
blackBoard.setBounds(1, 1, 400, 440);
blackBoard.setLayout(null);
and then add components into "blackBoard" instead of your JFrame, like this.
// putting JLabel "noteToSelf" onto background
noteToSelf.setIcon(new ImageIcon("c:\\Java\\images\\Sticker_a1.png"));
// or: noteToSelf.setText("Remind me at 6:30am...");
blackBoard.add(noteToSelf);
noteToSelf.setBounds(noteX, noteY, 64, 48);
Now your JFrame is table board and "blackBoard" is table sheet on it.
Hope this helps.

Unable to get image icon in runnable jar

I wrote a method in order to get icon for my swing:
public Icon getIcon(String iconName) {
Icon icon = null;
if(iconName.equals("NEXT")){
icon = new ImageIcon( getClass().getResource("resources/img/next.png" ) );
}
return icon;
}
but
icon = new ImageIcon( getClass().getResource("resources/img/next.png" ) );
goes in null pointer
I created a source folder "resources" and a folder "img" inside it with "next.png" icon
Where's the problem?
Thanks
For this to work, the resources folder should be in the same folder as the folder corresponding to the package of this.getClass(). To start from the root of the classpath, use getClass().getResource("/resources/img/next.png"). (with a leading /)
so, I found the right method:
public static ImageIcon getImageIcon(String iconName) {
ImageIcon imageIcon = null;
if(iconName.equals("DOWNLOAD")){
imageIcon = new ImageIcon(ImagesLocation.class.getResource("/img/download.png"));
}
return imageIcon;
}
with a "resources" source folder at the same level of the project and with an img folder inside (package styled)
ImagesLocation is a generic class containing this method
For those in need of help that have come across this page in Google - I wrote an answer in another StackOverflow question giving the best way to handle images in JAVA apps so that you can easily access the images for all image method types in Java:
This IS the best way to handle all images and icons in a JAR App.
Once you've zipped up all of your images and icons into its own JAR file - Configure your build path by adding the images JAR file into your libraries tab so that its now included in your classpath.
Then simply use the following 3x lines of code at the start of your constuctor to access any image you need for anything including a SystemTray image which doesn't accept the simple ImageIcon's as its main icon (weird I know). The 3x lines are:
URL iconUrl = this.getClass().getResource("/image-iconb.png");
Toolkit tk = this.getToolkit();
someimgicon = tk.getImage(iconUrl);
(someimgicon is just a constructor declared Image variable)
Now you can set a window icon as simply as:
setIconImage(someimgicon);
and at the same time use the same variable when setting the System TrayIcon by declaring:
trayIcon = new TrayIcon(someimgicon, "SystemTray Demo", popupMenu);
The above allows you to declare Images or ImageIcons easily and centrally without running the risk of not keeping image resources in the right place. It keeps it nice and tidy, with the JAR containing all your images automatically compiled at run time and distribution of your program.
As a bonus, once the JAR is registered in your classpath - you can keep adding any other images into the same JAR at any time without any fuss too - Everything just works and the added images are instantly available to your app.
Much better in my view.

Categories