Why does this simple code not work - java

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);

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"));

java.lang.NullPointerException when trying to display a ,gif file?

Well basically I tried to display a .gif using a url but it's given me a null pointer exception and I'm not really sure why since my url is correct and there's no other problems with my code(At least none that I can see).
import javax.swing.*;
import java.net.*;
public class image {
public image() {
}
public static void main(String[] args) {
URL url = image.class.getResource("<http://cdn.osxdaily.com/wp-content/uploads/2013/07/dancing-banana.gif>");
ImageIcon imageIcon = new ImageIcon(url);
JLabel label = new JLabel(imageIcon);
JFrame frame = new JFrame();
JPanel panel = new JPanel();
panel.add(label);
frame.add(panel);
frame.setTitle("Title");
frame.setSize(700,500);
frame.setResizable(false);
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
}
URL url = image.class.getResource("<http://cdn.osxdaily.com/wp-content/uploads/2013/07/dancing-banana.gif>");
is not how you reference an image from a web resources. You would use this method to load resources that are embedded within your application (within the context of the applications classpath)
URL url = new URL("http://cdn.osxdaily.com/wp-content/uploads/2013/07/dancing-banana.gif");
would probably work better...
Remember, that downloading and loading the image may take some time, you may want to use a MediaTracker to track the progress, this would allow you to provide feedback to the user and know when to update the screen with the image once it's available, for example.
Before anyone asks, I choose not to use ImageIO to load an animated gif, because that is just a lot more work (as demonstrated here - not for the faint hearted). In this case, the MediaTracker could be used to check for errors

How to open an image using Imageicon on a jframe

I am trying to simply draw an image on a jframe by using an Imageicon. However when I run it its just blank. Heres my code...
public final class PICS
{
public static final void main(String... aArgs)
{
JFrame frame = new JFrame("IMAGE");
frame.setVisible(true);
frame.setSize(500,500);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
ImageIcon image = new ImageIcon("image/pic1.jpg");
JLabel label = new JLabel("", image, JLabel.CENTER);
JPanel panel = new JPanel(new BorderLayout());
panel.add( label, BorderLayout.CENTER );
}
}
I am very new to everything java including this website, so I apologize if im missing something. Also im using Eclipse, and are there specific formats you can use for images, or is there a limit to size?
I am very new to everything java including this website
Then I would suggest you start by reading tutorials especially the Swing tutorial. Maybe the section on How to Use Icons would be a good place to start. The example code will show you how to use Icons as well as how to structure your program so that the GUI code is executed on the EDT. The tutorial on Concurrency will explain why the EDT is important.
Two things.
First, make setVisible the last call AFTER you have built your frame and it's contents...ie
JFrame frame = new JFrame("IMAGE");
frame.setSize(500,500);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
ImageIcon image = new ImageIcon("image/pic1.jpg");
JLabel label = new JLabel("", image, JLabel.CENTER);
JPanel panel = new JPanel(new BorderLayout());
panel.add( label, BorderLayout.CENTER );
// Make me last
frame.setVisible(true);
Two, make sure that the image/pic1.jpg exists and is the directory image under the current execution context.
If the image is a embedded resource (lives within the Jar or your application), then you need to supply a URL to the image instead of a String as ImageIcon treats String as a file name...
ImageIcon image = new ImageIcon(PICS.class.getResource("image/pic1.jpg"));
For example.
I would encourage you to use JFrame#pack over JFrame#setSize as it will resize the frame to the preferred size of your content...
I would also encourage you to take the time to read through Code Conventions for the Java Programming Language, Initial Threads.
I would also encourage you to use ImageIO over ImageIcon as it will, at least, throw an Exception if something goes wrong
Updated, testing image path
Try adding this to the constructor of your PICS class. This will, at least, tell you where the image isn't...
try {
ImageIO.read(PICS.class.getResource("image/pic1.jpg"));
} catch (IOException ex) {
System.out.println("Not in image/pic1.jpg");
}
try {
ImageIO.read(PICS.class.getResource("/image/pic1.jpg"));
} catch (IOException ex) {
System.out.println("Not in /image/pic1.jpg");
}
try {
ImageIO.read(PICS.class.getResource("resources/image/pic1.jpg"));
} catch (IOException ex) {
System.out.println("Not in resources/image/pic1.jpg");
}
try {
ImageIO.read(PICS.class.getResource("/resources/image/pic1.jpg"));
} catch (IOException ex) {
System.out.println("Not in /resources/image/pic1.jpg");
}

Image won't display in JLabel

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.

Using an ImageIcon and a JLabel

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.

Categories