image/icon use a relative path - java

I don't really get how to properly use a relative path in Eclipse. I created a res folder next to the src folder with a image folder in it.
This is my current code:
public class ToolbarView extends JToolBar {
JButton addButton = new JButton("\\images\\button.png");

Try doing this
JButton addButton = new JButton(new ImageIcon(getClass().getResource("images\button.png")));

You can create an icon using getClass().getResource(...) like this :
Icon icon = new ImageIcon(getClass().getResource("/images/button.png"));
JButton b = new JButton(icon);

Based on the forum instead of writing down /res/image.png you just have to write /image.png .It worked for me. (The image was in the src/main/resources folder by the way)

you could write it like this instead.
JButton addButton = new JButton(new ImageIcon("images/button.png"));

Related

Why this GUI app does not show me the image?

I'm trying yo write a java app with a JFrame object that must show three label objects, with text and image, my text "North" and "South" shows up on execution, but my image does not, even I put the image file into src folder.
package deitel9;
import java.awt.BorderLayout;
import javax.swing.ImageIcon;
import javax.swing.JLabel;
import javax.swing.JFrame;
public class LabelDemo {
public static void main(String[] args)
{
//crate a label with a plain text
JLabel northLabel = new JLabel("North");
//crate an icon from an image so we can put it on a JLabel
ImageIcon labelIcon = new ImageIcon("maldive.jpg");
//crate a label with an Icon instead of text
JLabel centerLabel = new JLabel(labelIcon);
//create another label with an Icon
JLabel southLabel = new JLabel(labelIcon);
//set the label to display text (as well as an icon)
southLabel.setText("South");
//create a frame to hold the labels
JFrame application = new JFrame();
application.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
//add the labels to the frame; the second argument specifies
//where on the frame to add the label
application.add(northLabel,BorderLayout.NORTH);
application.add(centerLabel,BorderLayout.CENTER);
application.add(southLabel,BorderLayout.SOUTH);
application.setSize(300,300);
application.setVisible(true);
}//end main
}//end class LabelDemo
Since your image stored in same package where LabelDemo is stored, try this,
ImageIcon labelIcon = new ImageIcon(LabelDemo.class.getResource("/deitel9/maldive.jpg").getFile());
or
private String getImage() {
return getClass().getResource("/deitel9/maldive.jpg").getFile();
}
ImageIcon labelIcon = new ImageIcon(new LabelDemo().getImage());
To figure out what you did wrong in a situation like this, you can simply call
File file = new File ("maldive.jpg");
System.out.println(file.getAbsolutePath());
This will print out the absolute path it is looking at for your file, which might give you an indication about what you did wrong.
Of course if you know how to use the debugger, you don't need the second line (and technically not even the first one, but that's a bit trickier ;))
According to the documentation, the ImageIcon constructor you chose expects a file name or file path, thus the image needs to be on file system rather than on the class path.
Creates an ImageIcon from the specified file. [...] The specified String can be a file name or a file path.
Given your description, when your project layout looks like this
\---src
\---deitel9
LabelDemo.java
maldive.jpg
then you should be able to retrieve the image as resource located on the class path like this:
ImageIcon labelIcon = new ImageIcon(LabelDemo.class.getResource("maldive.jpg"));

Image doesn't show in image button

I have create an image button but it didn’t show the image. The file is on src\MyPackage folder. How can I map it?
There is my code:
jpAnnotation=new JPanel();
jpAnnotation.setLayout(new FlowLayout(FlowLayout.LEADING));
JButton btnUnderline =new JButton(new ImageIcon ("UnderlineIcon.gif"));
btnUnderline.setSize(50, 260);
btnUnderline.setAlignmentX(JButton.LEFT_ALIGNMENT);
btnUnderline.setHorizontalAlignment(JButton.LEFT);
btnUnderline.addActionListener(new ActionListener(){
#Override
public void actionPerformed(ActionEvent arg0){
ActionEvent ae = new ActionEvent(bean, 0, "Underline");
bean.actionPerformed(ae);
}
});
jpAnnotation.add(btnUnderline);
Just a little code snippet:
btnUnderline.setIcon(
new ImageIcon(getClass().getResource("/path/to/UnderlineIcon.gif")));
Brief explanation
Using this statement for loading your image, you don't have to care about the right URL to your file, because you automatically get the correct URL.
This is based on loading the resource from the class path and not from the filesystem path!
Try this:
btnUnderline.setIcon( new ImageIcon( "C:\\YourFolder\src\MyPackage\UnderlineIcon.gif" ) );
If of course you're using Windows. Alternatively you can move the gif to the same directory as where you're executing your code from.

Failed to get my image loaded [duplicate]

This question already has answers here:
Displaying an ImageIcon
(2 answers)
Add a picture to a JFrame
(3 answers)
Closed 9 years ago.
I am trying to add a picture of a cow and eclipse is failing me. It won't allow any images, I think I may be doing my path wrong, but I am getting it straight from the properties that eclipse supplies upon right-clicking the image. So if anyone has any idea why my picture fails to load please tell me. NO ERROR MESSAGE!
package odin;
import java.awt.event.*;
import javax.swing.*;
public class Main extends JFrame implements ActionListener{
JPanel mypanel;
JButton mybutton;
JLabel mylabel;
int Counter = 0;
public Main(){
mypanel = new JPanel();
mybutton = new JButton("OK");
mybutton.addActionListener(this);
mylabel = new JLabel();
JLabel imgLabel = new JLabel(new ImageIcon("/GuiTest/src/odin/COW.png"));
mypanel.add(mybutton);
mypanel.add(mylabel);
mypanel.add(imgLabel);
this.add(mypanel);
}
public static void main(String[] args){
Main first = new Main();
first.setTitle("First Attempt");
first.setSize(800,600);
first.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
first.setVisible(true);
first.setResizable(false);
first.setLocationRelativeTo(null);
}
#Override
public void actionPerformed(ActionEvent e) {
if(e.getSource()==mybutton)
{
Counter = Counter + 1;
mylabel.setText("My Clicks " + Counter);
}
}
}
The problem is the path to the image...
JLabel imgLabel = new JLabel(new ImageIcon("/GuiTest/src/odin/COW.png"));
Basically, ImageIcon(String) expects that the String represents a file. This means, that Java is look for the image starting from the root of the current drive...which probably isn't what you really want...
You should also not store resources within the src directory in Eclipse, as I understand it, Eclipse requires you to place these resources within the "resources" directory within the project. These will be included within the project when you build it...
Once you've move the image to this location, you should be able to access it as an embedded resource using something like...
JLabel imgLabel = new JLabel(new ImageIcon(getClass().getResource("/odin/COW.png")));

NullPointerException when trying to display image?

This applet is a simple about the developer page in a website i'm creating for a class project. I'm trying to display an image and a bio for each different JButton.
I'm having an Issue with compiling, I keep getting a NullPointerException error
on this line
danPic = new ImageIcon(getClass().getResource("pics/danSkaggs.jpg"));
Which i'm assuming it goes null because it can't find the image based on the directory i'm giving it. However I can't understand what I can do different, I can't see any problems with how the directory is written. The directory is pics/filename.jpg and the folder is in the same package as the Java code.
Here is the full source code.
import java.util.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.*;
public class Developers extends JApplet{
private JButton danButton = new JButton("Dan Skaggs");
private JButton brandonButton = new JButton("Brandon Shaw");
private JButton jamesButton = new JButton("James Simpson");
private JLabel bioLabel = new JLabel("Please click one of the buttons on the left.");
JPanel centerPanel = new JPanel(new GridLayout(1, 2));
JPanel mainPanel = new JPanel(new BorderLayout());
JPanel westPanel = new JPanel(new GridLayout(1, 3));
private ImageIcon danPic;
private ImageIcon brandonPic;
private ImageIcon jamesPic;
private JLabel dLabel;
private JLabel bLabel;
private JLabel sLabel;
//This array carries the Bios of the group project members
String[] bio = new String[]{"Insert Bio",
"Insert Bio",
"Insert Bio"};
public Developers(){
mainPanel.add(westPanel, BorderLayout.WEST);
westPanel.add(danButton);
westPanel.add(brandonButton);
westPanel.add(jamesButton);
centerPanel.add(bioLabel);
mainPanel.add(centerPanel, BorderLayout.CENTER);
danButton.addActionListener(new Handler());
brandonButton.addActionListener(new Handler());
jamesButton.addActionListener(new Handler());
danPic = new ImageIcon(getClass().getResource("pics/danSkaggs.jpg"));
brandonPic = new ImageIcon(getClass().getResource("pics/brandonShaw.jpg"));
jamesPic = new ImageIcon(getClass().getResource("pics/jamesSimpson.jpg"));
dLabel = new JLabel (danPic);
bLabel = new JLabel (brandonPic);
sLabel = new JLabel (jamesPic);
centerPanel.add(dLabel);
add(mainPanel);
}
private class Handler implements ActionListener{
public void actionPerformed(ActionEvent event){
if(event.getSource()== danButton){
bioLabel.setText(bio[0]);
centerPanel.add(dLabel);
}
else if(event.getSource()== brandonButton){
bioLabel.setText(bio[1]);
centerPanel.add(bLabel);
}
else if(event.getSource()== jamesButton){
bioLabel.setText(bio[2]);
centerPanel.add(bLabel);
}
}
}//end Handler class
}//end Developer class
Use ImageIO instead, it will give the exception you can caught and process accordingly.
Or
danPic = new ImageIcon(getClass().getResource("pics/danSkaggs.jpg"));
You are missing the / as pics is package name, must use / to make url other wise pics will embed to the parent dir name to make mistake.So use (poor way)
danPic = new ImageIcon(getClass().getResource("/pics/danSkaggs.jpg"));
The Exception is on the first one because it is executed first also change other two statements that are getting the image.
I just tested that it is working fine.
So getResource is returning null: your path to the picture is wrong. Note that these are relative paths (relative to the class you fetched with getClass) so you are probably missing the initial slash which would make it an absolute path.
This should be:
danPic = new ImageIcon(getClass().getClassLoader().getResourceAsStream("danSkaggs.jpg"));
This will load the image from the class path assuming pics directory is on the class path.
getClass().getResource("pics/danSkaggs.jpg") is a relative path. If your class is at a package com.mydomain it expects to find the image in /com/mydomain/pics/danSkaggs.jpg
If the class and the image are in the same package just use getResource("danSkaggs.jpg"). For more details check this comment sample code that demonstrates loading resources using either a class or even better its classloader.

Why does this simple code not work

I am having trouble with this simple example code from the book. It is supposed to represent the same image 2 times in one window (north and south labels), one above the other. When I run it, it displays this instead of this (I am sorry for not cutting the images or resizing them) Below is my code. I am running Eclipse Juno on Ubuntu 13.04.
package gui;
import java.awt.BorderLayout;
import javax.swing.*;
public class Gui {
public static void main(String[] args) {
JLabel northLabel = new JLabel ( "North" );
ImageIcon labelIcon = new ImageIcon ("GUItip.gif");
JLabel centerLabel = new JLabel (labelIcon);
JLabel southLabel = new JLabel (labelIcon);
southLabel.setText("South");
JFrame application = new JFrame();
application.setDefaultCloseOperation (JFrame.EXIT_ON_CLOSE);
application.add(northLabel, BorderLayout.NORTH);
application.add(centerLabel, BorderLayout.CENTER);
application.add(southLabel, BorderLayout.SOUTH);
application.setSize(300, 300);
application.setVisible(true);
}
}
You need to concentrate on the following statement:
ImageIcon labelIcon = new ImageIcon ("GUItip.gif");
When initiating new ImageIcon.. it searches the provided address in execution folder by default i.e. in this case "GUItip.gif" shall be searched within workspace/user directory.
One solution is to make available GUItip.gif image in you workspace (program execution) folder.
Another solution would be to provide absolute path.. eg.
C:\USER\Workspace\project_name\GUItip.gif
Though a better approach would be to create a specific folder where you save all images used in your project. Create a final static String variable with absolute path to your folder. Now it would be easy for any programmer in that project to know where to look for images.
There are good approaches to use this mapping.. through XML to be loaded in the beginning.. through resourcebundle etc but that is a different topic altogether.
The image probably isn't loading properly. Try using a try/catch block to see if that's the case.
Ex:
Image img;
File f = new File(//image url);
try {
img = ImageIO.read(f);
} catch (IOException e) {
String curr_dir = System.getProperty("user.dir");
throw new IllegalArgumentException("Image could not be found from " + curr_dir);
}
ImageIcon labelIcon = new ImageIcon(img);

Categories