0

Here is the code where I want to import pictures and I want to display them on Java GUI.

AddingImages(){
    setLayout(new FlowLayout());

    image1 = new ImageIcon(getClass().getResource("Capture1.PNG"));


    label1 = new JLabel("Image 1");
    add(label1);

    image2= new ImageIcon(getClass().getResource("Capture1.PNG"));


    label2 = new JLabel("Image 2");
    add(label2);
}

    public static void main(String[] args){
    AddingImages ai = new AddingImages();
    ai.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    ai.setVisible(true);
    ai.pack();
    ai.setTitle("Adding Images in GUI");
}
}
Andrew Thompson
  • 168,117
  • 40
  • 217
  • 433
Adil Khan
  • 1
  • 1
  • 3
  • *"and also explain the pack() property"* 1) You seem to have mistaken this Q&A site for a one-stop help-desk. If there are further questions, ask them on a separate question thread. 2) But first, consult the Java Docs for the method, that is what they are for. – Andrew Thompson Apr 01 '17 at 16:25
  • As to the problem with loading images: If we knew what package the code shown was in, as well as the location of the image relative to that package, we would be able to help you better. Surprising as it may seem, we cannot see that information over your shoulder via the spy cams we have installed in your home. – Andrew Thompson Apr 01 '17 at 16:27
  • @AndrewThompson the location of the image is the same where the package is and (i.e. bin folder) – Adil Khan Apr 01 '17 at 18:06
  • And it is named exactly `Capture1.PNG` not `Capture1.png` or `capture1.PNG` or..? – Andrew Thompson Apr 01 '17 at 18:36
  • @AndrewThompson yeah the name is exactly Capture1.PNG – Adil Khan Apr 02 '17 at 00:59
  • `image1` & `image2` never seem to be added to labels! 1) For better help sooner, post a [MCVE] or [Short, Self Contained, Correct Example](http://www.sscce.org/). 2) One way to get image(s) for an example is to **hot link** to images seen in [this Q&A](http://stackoverflow.com/q/19209650/418556). – Andrew Thompson Apr 02 '17 at 18:56

1 Answers1

1
image1 = new ImageIcon(getClass().getResource("Capture1.PNG"));
label1 = new JLabel("Image 1");
add(label1);

Where do you actually add the Icon to the JLabel?

The Code should be:

label1 = new JLabel("Image 1");
label1.setIcon( image1 );
camickr
  • 321,443
  • 19
  • 166
  • 288
  • still displaying blank GUI :( – Adil Khan Apr 02 '17 at 01:04
  • @AdilKhan, did you check the image? Does it have a width/height. That is did you successfully read the image. If you need more help then read the section from the Swing tutorial on [How to Use Icons](http://docs.oracle.com/javase/tutorial/uiswing/components/icon.html) for working examples. It is up to you to make sure you IDE is configured so the image is on the classpath. – camickr Apr 02 '17 at 01:12