Why this GUI app does not show me the image? - java

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

Related

.png icon not loading in a JFrame window

import java.awt.*;
import javax.swing.*;
public class Program {
public static JButton button;
public static void main(String args[]){
JFrame win=new JFrame("title");
win.setVisible(true);
win.setSize(500,500);
win.setLayout(new FlowLayout());
win.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
ImageIcon i=new ImageIcon("icon.png");
button=new JButton("hello",i);
win.add(button);
button.setToolTipText("click me");
}
}
When I run the file , I just get the text "hello" on the button but no image.
(This image was downloaded from http://icons.iconarchive.com/icons/iynque/flat-ios7-style-documents/512/png-icon.png)
The image is stored in the project src file.
Image shouldn't be in src but in main application directory, usually level above. So move your icon or change code to:
ImageIcon i=new ImageIcon("src/icon.png");
You should consider adding it to your resources (so it will be placed in jar) and opening via getResource(). Next problem in example is that it won't be displayed until window is refreshed by resize or other action. Add this line at the end:
win.pack();
Or other method that will refresh window content.
try this:
ImageIcon i=new ImageIcon("src/icon.png");
getClass().getResource("icon.png")
will do it, if your image file is under the same dir of the Program.java, and when compiled, it indeed is packed into the same dir where the Program.class is.

adding an image on java frame

I have this problem in practice, the frame does not display the image I have in the folder image, someone can tell me why? i add the hierarchy of the project
package frame;
import javax.swing.ImageIcon;
import javax.swing.JFrame;
import javax.swing.JLabel;
public class Frame {
Frame() {
final JFrame login = new JFrame();
login.setTitle("Title");
login.setLayout(null);
login.add(new JLabel(new ImageIcon("Images/images.png")));
login.setVisible(true);
login.setSize(500, 400);
login.setLocationRelativeTo(null);
}
public static void main(String[] args) {
new Frame();
}
}
Avoid setLayout (null), if you do not have sound reason for it. Remove the below code. Image will get displayed.
If you still have to use a null layout, you have to set the width and height of the component, along with its its x and y position.
login.setLayout(null);
For getting resources from project use URL instead of String path. For example:
URL resource = Frame.class.getResource("/Images/images.png");
ImageIcon icon = new ImageIcon(resource);
JLabel lbl = new JLabel(icon);
Also read that.
Also don't use null LayoutManager, in that case you need to specify bounds of component with help of setBounds() method.
Don't use a package for resources. Instead, create a non-source folder called "images", and move it there.
After that, use that path "images/images.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);

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