Cutter Cutter - 3 months ago 6
Java Question

Trying to add an image to a label but won't work?

I'm trying to add the image "Pic.png" to this JLabel "label1" and display it on the JPanel "panel1" on a JFrame "window1". But it when I hit run it doesn't display my image. Anyone help? (I read about adding it to the source file or something but I'm not really sure what I'm doing because I'm new to Java. Will it not be able to access the picture without the image being in the source?)

public class UIForIshidaQuery {

public static void main(String[] args) {
System.out.println("Running...");

JFrame window1 = new JFrame();
window1.setVisible(true);
window1.setSize(1080, 720);
window1.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JPanel panel1 = (JPanel) window1.getContentPane();
JLabel label1 = new JLabel();
panel1.setLayout(null);
ImageIcon image = new ImageIcon("C:\\Users\\BC03\\Pictures\\Saved Pictures\\Other\\Pic.png");
label1.setIcon(image);
label1.setBounds(500, 500, 500, 500);
panel1.add(label1);
}
}

Answer

The window should be set visible as the last call. Don't use null layouts1. This works.

import java.net.*;
import javax.swing.*;

public class UIForIshidaQuery {

    public static String url = "http://i.stack.imgur.com/gJmeJ.png";

    public static void main(String[] args) throws MalformedURLException {
        System.out.println("Running...");

        JFrame window1 = new JFrame();
        window1.setSize(1080, 720);
        window1.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        JPanel panel1 = (JPanel) window1.getContentPane();
        JLabel label1 = new JLabel();
        //panel1.setLayout(null);
        ImageIcon image = new ImageIcon(new URL(url));
        label1.setIcon(image);
        //label1.setBounds(500, 500, 500, 500);
        panel1.add(label1);
        window1.setVisible(true);
    }
}
  1. Java GUIs have to work on different OS', screen size, screen resolution etc. using different PLAFs in different locales. As such, they are not conducive to pixel perfect layout. Instead use layout managers, or combinations of them along with layout padding and borders for white space.