Java Icon not working - java

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.

Related

Swing ImageIcon causing error and not making image appear

I am having a problem with my java project. I am trying to make a JFrame with a background image, but when I use javax.swing.ImageIcon to set the icon of the background JLabel it shows an exception error in the console when I run the program and the image doesn't work, only showing a blank JFrame. Here is my code:
#SuppressWarnings("serial")
public class MainUI extends JFrame {
public static void main(String[] args) {
new MainUI().build(); // Calls build method
}
private void build() {
// Builds JFrame
JFrame frame = new JFrame();
JPanel base = new JPanel();
JLabel background = new JLabel();
frame.setVisible(true);
frame.setTitle("Space Age");
frame.setSize(640,480);
frame.setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
frame.setAutoRequestFocus(false);
frame.setCursor(new java.awt.Cursor(java.awt.Cursor.DEFAULT_CURSOR));
frame.setLocationRelativeTo(null);
base.setSize(640,480);
base.setAlignmentX(0.0F);
base.setAlignmentY(0.0F);
base.setBackground(new java.awt.Color(255,255,255));
background.setSize(640,480);
background.setAlignmentX(0.0F);
background.setAlignmentY(0.0F);
background.setIcon(new ImageIcon(getClass().getResource("spaceage.images.starfield.png")));
frame.add(base);
frame.add(background);
}
}
This is what the error message looks like:
Exception in thread "main" java.lang.NullPointerException
at javax.swing.ImageIcon.<init>(Unknown Source)
at spaceage.src.MainUI.build(MainUI.java:36)
at spaceage.src.MainUI.main(MainUI.java:15)
Can someone tell me what I did wrong and how to to make the image display properly?
Thanks in advance,
Santiago
I figured out what I did wrong. This:
background.setIcon(new ImageIcon(getClass().getResource("spaceage.images.starfield.png")));
needed to be changed to this:
background.setIcon(new ImageIcon(getClass().getResource("/spaceage/images/starfield.png")));
I got a NullPointerException because I entered the path to my image incorrectly, so getResource() couldn't find the image and returned null.
Also this will help you. You can link it with your requirement.
you can use this-
ImageIcon iid = new ImageIcon("C:\\Users\\ranig\\My\\spaceinvaders\\ball.png");
Note: C:\Users\ranig\My\spaceinvaders\ball.png is the whole path of ball.png image.
instead of this:
ImageIcon iid = new ImageIcon(this.getClass().getResource("ball.png"));

Refreshing my JFrame

I want to display an image on a application and when I want to open another one, I want that the new one overwrite the old.
I've looking everywhere to find a solution like use invalidate(), repaint(), etc.. but still not working and I can't figured out why the windows doesn't refresh, can someone help me?
Here the code :
public void actionPerformed(ActionEvent e)
{
System.out.println(e.getActionCommand());
if (e.getActionCommand().contains("Open"))
{
filename_ = new String();
filename_ = JOptionPane.showInputDialog("File to open ?");
ImagePanel test = new ImagePanel(new File(filename_));
test.setPreferredSize(new Dimension(test.getWidth(), test.getHeight()));
test.setMinimumSize(new Dimension(test.getWidth(), test.getHeight()));
test.repaint();
JScrollPane tmp = new JScrollPane();
tmp.getViewport().add(test);
tmp.getViewport().repaint();
mainPanel_.add(tmp, BorderLayout.NORTH);
mainPanel_.repaint();
curim_ = test;
test.memento_ = new Memento(test);
test.caretaker_.add(test.memento_);
curim_ = test;
curmodindex_ = curim_.caretaker_.getIndex();
this.setContentPane(mainPanel_);
System.out.println(curmodindex_);
if (curmodindex_ != 0)
{
button1.setEnabled(true);
button2.setEnabled(true);
}
}
Don't create new components. Just update the data of existing components. Maybe something like:
scrollPane.setViewportView( imagePanel );
Or even easier just use a JLabel to display your image. Then when the image changes you can use:
label.setIcon( new ImageIcon(...) );
Without a proper SSCCE its hard to guess what you are doing wrong. For example I see:
tmp.getViewport().add(test);
...
test.memento_ = new Memento(test);
Without knowing what your code does it looks like you are trying to add the same component to two different components which is not allowed.

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.

JTabbedPane shows itself randomly

the problem I encountered is weird for me, because I was doing everything step by step, correctly (in my opinion) and finally when I could say I finished one part of my program it appeared to make a fun of me. The actual problem is that in GUI I created I used a JPanel, then I've put it into a JTabbedPane which I've finally put into a JFrame. Everything is fine and works apart from times when it doesn't. I know it sounds strange, but after running program once I get what I wanted (Frame with tabbed pane containing panel with some stuff in it) and then when I run it again it either show the correct thing again or just empty frame. The worst thing is that it's so random, I haven't got a clue what can be wrong, I don't even know what exactly should I google to find it out. The code is:
import java.awt.Dimension;
import java.awt.Toolkit;
import javax.swing.*;
public class GUI extends JFrame {
JFrame frame = new JFrame("WakeOnLan script generator");
JPanel panel1 = new JPanel(null);
JTextArea text; //= new JTextArea("test");
JScrollPane scroll = new JScrollPane();
JButton but = new JButton("test");
JTabbedPane tab = new JTabbedPane();
public GUI() {
Dimension dim = Toolkit.getDefaultToolkit().getScreenSize();
int w = frame.getSize().width;
int h = frame.getSize().height;
int x = (dim.width-w)/3;
int y = (dim.height-h)/4;
frame.setSize(500,500);
frame.setLocation(x,y);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
frame.setLayout(null);
createTab1();
tab.addTab("Tab 1", panel1);
tab.setVisible(true);
tab.setBounds(0, 0, 500, 500);
frame.add(tab);
}
public void createTab1(){
text = new JTextArea("test");
text.setVisible(true);
scroll.setViewportView(text);
scroll.setBounds(10,10,465,300);
panel1.setLayout(null);
panel1.add(scroll);
panel1.setVisible(true);
panel1.setSize(500,500);
//panel.setBackground(Color.blue);
}
}
And then I just run it in the main method in other class:
public class GUIStarter {
public static void main(String[] args) {
GUI start = new GUI();
}
}
So could anyone give me an answer or just a hint?
Thank you.
You should call frame.setVisible(true) after adding all your components to your JFrame. So try moving it to the end of your constructor.
Alternatively, you can call frame.validate() after all the components have been added.

Categories