My goal is to have an imageIcon and add it so a JLabel so it will appear on my GUI. So far my code is:
package classes;
import javax.swing.*;
public class Picture extends JFrame {
private ImageIcon _image1;
private JLabel _mainLabel;
public Picture(){
_image1 = new ImageIcon("picture1.jpg");
_mainLabel = new JLabel(_image1);
add(_mainLabel);
setVisible(true);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
}
package classes;
public class Driver {
public static void main(String[] args) {
Picture p = new Picture();
}
}
The problem is the picture does not appear on my GUI. If anyone has any suggestions please let me know thanks!
Are you sure that Java is looking in the right location for your picture1.jpg file? Is this file located in the current working directory?
Put this code somewhere in your program so that it gets called when the program is run:
// show the current working directory
System.out.println("current working directory is: " + System.getProperty("user.dir"));
The String returned will tell you where Java is looking, where your current working directory is located. You can then use that information to adjust your path or you could always just use the full path to the image file.
Edit:
Also, don't forget to pack your JFrame so that it will layout the components and size itself accordingly:
public Picture() {
_image1 = new ImageIcon(IMAGE);
_mainLabel = new JLabel(_image1);
add(_mainLabel);
pack(); // to tell the layout managers to set up the GUI
setLocationRelativeTo(null); // center things
setVisible(true);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
For setting image to jlabel simple put one line code in your program :
yourlabel.setIcon(new javax.swing.ImageIcon(getClass().getResource("your image location here")));
we can set Jlabel with image and text also.
Related
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"));
So i have this code
import javax.swing.*;
public class pictest {
public static void main(String[] args) {
JFrame frame = new JFrame("Label Example");
ImageIcon mine = new ImageIcon("C:/Users/Eric/Desktop/mine.jpg");
JLabel pic = new JLabel(mine);
frame.add(pic);
frame.setSize(300,250);
frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
frame.setVisible(true);
JFrame framee = new JFrame("Label Example");
ImageIcon minee = new ImageIcon("C:/Users/Eric/Desktop/mine.jpg");
JLabel pice = new JLabel(minee);
framee.add(pice);
framee.setSize(300,250);
framee.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
framee.setVisible(true);
}
}
So when i run the code i get this:
http://imgur.com/a/YF9zt
(the left pic is the code from the top part, the right is the code from the bottom part)
As far as i can tell the code is exactly the same(except for variable names) and i can not figure out why the picture will not show up on the one on the left, is this a problem where i need to reinstall stuff, or is there something in the code that i am just getting wrong.
(also if someone could reformat this post to look right i would appreciate that, sorry i dont use stack overflow much but i was getting frustrated.)
When I try to save your code, I get the following error:
The image shows on the top frame only when I copy
ImageIcon minee = new ImageIcon("C:/Users/Eric/Desktop/mine.jpg");
and paste and edit it to
ImageIcon mine = new ImageIcon("C:/Users/Eric/Desktop/mine.jpg");
I guess you are using some un-recognized charactes in that line.
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")));
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);
I've gone through every post I could find on this site and the Java tutorials and I still can't figure out why my code isn't working. Even when I copy/paste other peoples' code, it still doesn't work.
I've made a dummy program just to test this out and the code looks like so:
import java.awt.EventQueue;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.border.EmptyBorder;
import javax.swing.JLabel;
import javax.swing.ImageIcon;
public class gui extends JFrame {
private JPanel contentPane;
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
gui frame = new gui();
frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the frame.
*/
public gui() {
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(100, 100, 900, 700);
contentPane = new JPanel();
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
setContentPane(contentPane);
contentPane.setLayout(null);
JLabel lblNewLabel = new JLabel(new ImageIcon("bg.png"));
contentPane.add(lblNewLabel);
}
}
The background image I'm trying to display, bg.png, is located in the project's root folder. I tried multiple formats for the path string with no success. What am I doing wrong?
What you're doing wrong is that when you call new ImageIcon("bg.png"), you try loading the bg.png file from the current directory. The current directory is the directory from which java is executed. And the current directory is probably not the directory you believe when you execute java from your IDE.
Use the following code to display the current directory:
File dir1 = new File (".");
System.out.println("current directory: " + dir1.getAbsolutePath());
You should probably load the png file from the classpath, using Class.getResource("/images/bg.png"). Create an images folder in your source directory, and put the file in this directory. Your IDE will copy it to the target folder, along with the .class files. If you're not using an IDE, then you'll have to copy it yourself.
EDIT:
After more investigations, it appeared that the root cause of the problem was the use of the null layout. The above still stands, though, because loading a file from the current directory is not a good idea.
You're looking for the image as a file. When you do that the searches are all done in a path relative to the user directory which you can get via
// code not tested
System.out.println(System.getProperty("user.dir"));
So you will likely have to adjust your image's path to get it as a file. The other option is to get it as a resource as noted by Siva Charan in which case the path is relative to the location of your class files.
Oh and once you study and use the layout managers, they become intuitive, and creating and especially maintaing your GUI's become much easier.
Try this way:-
ImageIcon icon = createImageIcon("bg.png", "image description");
protected ImageIcon createImageIcon(String path, String description) {
java.net.URL imgURL = getClass().getResource(path);
if (imgURL != null) {
return new ImageIcon(imgURL, description);
} else {
System.err.println("Couldn't find file:" +path);
return null;
}
}
Just simply put your bg.png, alongside your gui.class file. That will do, if you write this code
private ImageIcon getImage(String path)
{
URL url = getClass().getResource(path);
System.out.println(url);
if (url != null)
return (new ImageIcon(url));
return null;
}
More information can be found on Access to Resources
Here path = "bg.png"; or if it's inside some folder than path = "someFolder/bg.png";
So you be writing something like this :
JLabel lblNewLabel = new JLabel(getImage("bg.png"));
lblNewLabel.setBounds(30, 30, 100, 100);
Hope that might help.
Regards
You might need to debug it and check if the image file is loaded correctly. And then you need to check if the JLabel Component gets its size because adding the image to the JLabel wouldn't expand the JLabel.
First you should try to see the image handler has its width and height.