I want to add a image in JLabel that can display after building the project too in eclipse.
I have this code..
jLabel1.setIcon(new ImageIcon(getClass().getResource("/student/information/system/images/bk4.jpg")));
Goodness, why are you trying to read an image file in one line?
First, make sure that your resources folder is defined for your project and is on the build path.
Here's an example from one of my Java projects.
Next, code a method to read image files from the resources folder.
private Image getImage(String filename) {
try {
return ImageIO.read(getClass().getResourceAsStream(
"/" + filename));
} catch (IOException e) {
e.printStackTrace();
return null;
}
}
Read the image file once, saving the result in a class variable ImageIcon.
imageIcon = new ImageIcon(getImage("image.png"));
Finally, reference the ImageIcon in your Swing code.
jLabel1.setIcon(imageIcon);
I have a project to hand in by tomorrow and been working all day to fix a problem.
My icon for the Jframe is set but when i run netbeans to build JAR it is not able to get the Icon I have set. When just running it on netbeans it works fine. When running jar Image is not able to show.
My code is as follows for Access Class:
public class LigacaoBD {
public ImageIcon icone;
protected BufferedImage imgicone;
public LigacaoBD() {
try {
imgicone = ImageIO.read(new File("build/classes/Img/logo.png"));
icone = new ImageIcon(imgicone);
} catch (IOException ioe) {
JOptionPane.showMessageDialog(null, "Erro no carregamento da imagem icone", jftitulo,
JOptionPane.WARNING_MESSAGE, icone);
}
}
}
My code is as follows for the Jframe i want to set the icon for:
setIconImage(ligaDB.imgicone);
I am after it been able to load the icon when running the JAR.
Thanks in advance.
The image must be in the src folder, then I usually load it like this:
ImageIcon icon = new ImageIcon(getClass().getClassLoader().getResource("img_folder/icon.png"));
p.s: img_folder is inside src
This question already has answers here:
Load image from jar and outside it in eclipse
(2 answers)
Closed 6 years ago.
I exported a runnable jar file from the Eclipse IDE. In Eclipse the program works fine, but when exported the program refuses to open. To clarify, the images are in a source folder and loaded via URL through a resource loader class. I used JD-GUI to show the contents of my jar file and the images are packaged properly into the file (Picture of this included). Why is the jar file not running properly?
The problem
Here is my code for the URL Loader
public class MainPanel extends JPanel{
BufferedImage img1, img2;
URL url1 = ResourceLoader.class.getResource("1.jpg");
URL url2 = ResourceLoader.class.getResource("2.jpg");
MainPanel(){
try {
img1 = ImageIO.read(url1);
img2 = ImageIO.read(url2);
} catch (IOException e) {
e.printStackTrace();
}
}
public void paintComponent(Graphics g){
super.paintComponent(g);
g.drawImage(img1, 1, 0, null);
g.drawImage(img2, img1.getWidth(), 0, null);
if(g instanceof Graphics2D){
Graphics2D g2d = (Graphics2D)g;
}
}
}
Here is the resource loader class
final public class ResourceLoader {
public static InputStream load(String path){
InputStream input = ResourceLoader.class.getResourceAsStream(path);
if (input == null) {
input = ResourceLoader.class.getResourceAsStream("/"+path);
}
return input;
}
}
Edit:://
Here is the command prompt read-out for the error that is happening
enter image description here
While exporting the jar select the class that contains main method in "Launch Configuration. It should work fine. If you still face problem then run jar from command line using "java -jar jarfilename" command to see the exact error message.
I've done a lot of reading around SO and Google links.
I have yet to figure out how to correctly add an image into an eclipse gui project is such a way that the system will recognize find it. I know there's some mumbojumbo about CLASSPATH but it probably shouldn't be this difficult to do.
Let me start by describing what I'm doing...(If someone could correct me, it'd be appreciated.)
Here is my method.
I add the image using the "import wizard" (right click, "import", "general", "file") into an "import directory" I called "/resources"
Eclipse automatically creates a folder called "resources" in the eclipse package explorer's tree view. Right under the entry for "Referenced Libraries".
Note, "resources" isn't under "Referenced Libraries", it's at the same level in the tree.
I then use the following code:
ClassLoader classLoader = Thread.currentThread().getContextClassLoader();
InputStream input = classLoader.getResourceAsStream("/resources/image.jpg");
Image logo = ImageIO.read(input);
And at this point, I run the test program and get this error:
Exception in thread "main" java.lang.IllegalArgumentException: input == null!
at javax.imageio.ImageIO.read(Unknown Source)
at Test.main(Test.java:17)
Thanks for any help in advance!
Place the image in a source folder, not a regular folder. That is: right-click on project -> New -> Source Folder. Place the image in that source folder. Then:
InputStream input = classLoader.getResourceAsStream("image.jpg");
Note that the path is omitted. That's because the image is directly in the root of the path. You can add folders under your source folder to break it down further if you like. Or you can put the image under your existing source folder (usually called src).
You can resave the image and literally find the src file of your project and add it to that when you save. For me I had to go to netbeans and found my project and when that comes up it had 3 files src was the last. Don't click on any of them just save your pic there. That should work. Now resizing it may be a different issue and one I'm working on now lol
If you still have problems with Eclipse finding your files, you might try the following:
Verify that the file exists according to the current execution environment by using the java.io.File class to get a canonical path format and verify that (a) the file exists and (b) what the canonical path is.
Verify the default working directory by printing the following in your main:
System.out.println("Working dir: " + System.getProperty("user.dir"));
For (1) above, I put the following debugging code around the specific file I was trying to access:
File imageFile = new File(source);
System.out.println("Canonical path of target image: " + imageFile.getCanonicalPath());
if (!imageFile.exists()) {
System.out.println("file " + imageFile + " does not exist");
}
image = ImageIO.read(imageFile);
For whatever reason, I ended up ignoring most of the other posts telling me to put the image files in "src" or some other variant, as I verified that the system was looking at the root of the Eclipse project directory hierarchy (e.g., $HOME/workspace/myProject).
Having the images in src/ (which is automatically copied to bin/) didn't do the trick on Eclipse Luna.
It is very simple to adding an image into project and view the image.
First create a folder into in your project which can contain any type of images.
Then Right click on Project ->>Go to Build Path ->> configure Build Path ->> add Class folder ->> choose your folder (which you just created for store the images) under the project name.
class Surface extends JPanel {
private BufferedImage slate;
private BufferedImage java;
private BufferedImage pane;
private TexturePaint slatetp;
private TexturePaint javatp;
private TexturePaint panetp;
public Surface() {
loadImages();
}
private void loadImages() {
try {
slate = ImageIO.read(new File("images\\slate.png"));
java = ImageIO.read(new File("images\\java.png"));
pane = ImageIO.read(new File("images\\pane.png"));
} catch (IOException ex) {
Logger.`enter code here`getLogger(Surface.class.getName()).log(
Level.SEVERE, null, ex);
}
}
private void doDrawing(Graphics g) {
Graphics2D g2d = (Graphics2D) g.create();
slatetp = new TexturePaint(slate, new Rectangle(0, 0, 90, 60));
javatp = new TexturePaint(java, new Rectangle(0, 0, 90, 60));
panetp = new TexturePaint(pane, new Rectangle(0, 0, 90, 60));
g2d.setPaint(slatetp);
g2d.fillRect(10, 15, 90, 60);
g2d.setPaint(javatp);
g2d.fillRect(130, 15, 90, 60);
g2d.setPaint(panetp);
g2d.fillRect(250, 15, 90, 60);
g2d.dispose();
}
#Override
public void paintComponent(Graphics g) {
super.paintComponent(g);
doDrawing(g);
}
}
public class TexturesEx extends JFrame {
public TexturesEx() {
initUI();
}
private void initUI() {
add(new Surface());
setTitle("Textures");
setSize(360, 120);
setLocationRelativeTo(null);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
TexturesEx ex = new TexturesEx();
ex.setVisible(true);
}
});
}
}
If you are doing it in eclipse, there are a few quick notes that if you are hovering your mouse over a class in your script, it will show a focus dialogue that says hit f2 for focus.
for computer apps, use ImageIcon. and for the path say,
ImageIcon thisImage = new ImageIcon("images/youpic.png");
specify the folder( images) then seperate with / and add the name of the pic file.
I hope this is helpful. If someone else posted it, I didn't read through. So...yea.. thought reinforcement.
When I try to run an applet in applet viewer it is not able to find resources (Image).
I try to load resource like this:
String cb= this.getCodeBase().toString();
String imgPath = cb+"com/blah/Images/a.png";
System.out.println("imgPath:"+imgPath);
java.net.URL imgURL = Applet.class.getResource(path);
but when i run it in appet viewer path is like this:
imgPath:file:D:/Work/app/build/classes/com/blah/Images/a.png
though image is there in this path,
is prefix file: causing problem, how can i test this code?
Will this code work when deployed in server and codebase returns a server URL?
Is your applet supposed to load images after it is loaded? Or would you be better served bundling necessary image resources in the jar with your applet?
I work daily on an applet-based application with plenty of graphics in the GUI.
They are bundled in the jar-file.
This si what we do:
// get the class of an object instance - any object.
// We just defined an empty one, and did everything as static.
class EmptyClass{}
Class loadClass = new EmptyClass().getClass();
// load the image and put it directly into an ImageIcon if it suits you
ImageIcon ii = new ImageIcon(loadClass.getResource("/com/blah/Images/a.png"));
// and add the ImageIcon to your JComponent or JPanel in a JLabel
aComponent.add(new JLabel(ii));
Make sure your image is actuallly in the jar where you think it is.
Use:
jar -tf <archive_file_name>
... to get a listing.
Just use /com/blah/Images/a.png as the path. getResource() is clever enough to find it.
The context classloader should work with jars.
ClassLoader cl = Thread.getContextClassLoader();
ImageIcon icon = new ImageIcon(cl.getResource("something.png"), "description");
Try this code it's only 2 methods out of the class I use to load images but it works fine for loading when using an applet.
private URL getURL(String filename) {
URL url = null;
try
{
url = this.getClass().getResource("" + extention + filename); //extention isn't needed if you are loading from the jar file normally. but I have it for loading from files deeper within my jar file like say. gameAssets/Images/
}
//catch (MalformedURLException e) { e.printStackTrace(); }
catch (Exception e) { }
return url;
}
//observerwin in this case would be an applet. Simply have the class have something like this: Applet observerwin
public void load(String filename) {
Toolkit tk = Toolkit.getDefaultToolkit();
image = tk.getImage(getURL(filename));
while(getImage().getWidth(observerwin) <= 0){loaded = false;}
double x = observerwin.getSize().width/2 - width()/2;
double y = observerwin.getSize().height/2 - height()/2;
at = AffineTransform.getTranslateInstance(x, y);
loaded = true;
}
I can post the rest of the class I use if needed