Domanda

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 enter image description here

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

}
È stato utile?

Soluzione

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

Altri suggerimenti

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"

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top