SunSpree
SunSpree

Reputation: 1

How do I import images using ImageIcon?

Here's my code, and I've got two problems evidently:

package test;

import javax.swing.ImageIcon;
import javax.swing.JPanel;
import java.awt.Component;

public class something {
public static void main(String[] args) {
    ImageIcon icon = new ImageIcon("src/icon.png",("What a great image"));

    JPanel window = new JPanel();
    window.setLocation(100,100);
    window.setSize(300, 500);
    window.setVisible(true);

}

So I don't know why the JPanel won't reveal itself, and am I importing the image right? I've already created the icon and placed it in the SRC folder. If I'm not importing it right, how do I import it then? This question also applies for the Graphics Swing since I'm interested in learning that soon.

Upvotes: 0

Views: 1282

Answers (2)

MadProgrammer
MadProgrammer

Reputation: 347234

So I don't know why the JPanel won't reveal itself

You've not added it to anything that can be displayed. A JPanel is just a plain container which will allow you to add other components onto it.

You need some kind of Window to actually display this container, for example...

JPanel window = new JPanel();

JFrame frame = new JFrame("Testing");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLayout(new BorderLayout());
frame.add(window);
frame.setSize(200, 200);
frame.setLocationRelativeTo(null);
frame.setVisible(true);

Have a read through How to Make Frames (Main Windows) for more details

I've already created the icon and placed it in the SRC folder. If I'm not importing it right, how do I import it then?

That's a complicated question, because you've added the image to the src directory, it changes the context of how the image can be loaded. Essentially, it becomes an embedded resource.

So instead of using...

 ImageIcon icon = new ImageIcon("src/icon.png",("What a great image"));

You would need to use something more like...

 ImageIcon icon = new ImageIcon(something.getClass().getResource("icon.png"),("What a great image"));

instead

You may find reading through How to Use Labels, Creating a GUI With JFC/Swing, Initial Threads, Laying Out Components Within a Container, Reading/Loading an Image helpful

Upvotes: 1

DMP
DMP

Reputation: 1053

A JPanel can only be placed on a heavyweight component like a JFrame, if you look up some basic Swing tutorials you can get the basic layout of a GUI. Alternatively you can use a GUI creator like the one provided with the NetBeans IDE. To add an image you would need to do something like

BufferedImage myPicture = ImageIO.read(new File("path-to-file"));
JLabel picLabel = new JLabel(new ImageIcon(myPicture));
add(picLabel);

Upvotes: 0

Related Questions