Reputation: 51
This is my code:
import java.awt.BorderLayout;
import javax.swing.ImageIcon;
import javax.swing.JFrame;
import javax.swing.JLabel;
public class SenzuView extends JFrame {
JLabel label;
public SenzuView(){
ImageIcon image = new ImageIcon("C:\\senzu.jpg");
label = new JLabel("", image, JLabel.CENTER);
this.add(label);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setLocationRelativeTo(null);
setExtendedState(JFrame.MAXIMIZED_BOTH);
this.setVisible(true);
}
public static void main(String[] args) {
new SenzuView();
}
}
The problem is that the Frame opens but its empty and the image never appears Thanks in advance
Upvotes: 2
Views: 865
Reputation: 824
I suggest you use the getClass.getResource
because that way if you later wants to compile the project into a .jar file the images will come with the project or else they wont appear if you go along with the solution path you were originally starting on.
Initialize the image icon like this:
ImageIcon image = new ImageIcon(getClass().getResource("res/senzu.jpg"))
The following is an example of how I suggest you should have your SenzuView
coded:
public SenzuView(){
setLayout(new BorderLayout());
ImageIcon image = new ImageIcon(getClass().getResource("res/senzu.jpg"));
label = new JLabel(image);
this.add(label, BorderLayout.CENTER);
setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
setLocationRelativeTo(null);
setExtendedState(JFrame.MAXIMIZED_BOTH);
setVisible(true)
}
I hope this solved it and gave you some other useful tips.
Upvotes: 1
Reputation: 351
I suggest you to create a folder in your project directory named images. Then give the path as this:
ImageIcon image = new ImageIcon("images/senzu.jpg");
This will work.
If you need an absolute path then use
C:/Program Files/workspace/Senzu/images/senzu.jpg
Hope it solved your issue.
Upvotes: 0