0

I'm a student working on a side project. However, I've hit a wall.

For some reason the image I'm trying to output is not being displayed on my JFrame . It displays blank.

Is it because of my file location? I have stored the .jpg in the same place as my src code.

JFrame frame = new JFrame();
  ImageIcon icon = new ImageIcon("pixPortrait.jpg");
  JLabel label = new JLabel(icon);
  frame.add(label);
  frame.setDefaultCloseOperation;
      (JFrame.EXIT_ON_CLOSE);
  frame.pack();
  frame.setVisible(true);
nircraft
  • 8,242
  • 5
  • 30
  • 46
  • Seems like it's a duplicate of [https://stackoverflow.com/questions/1614772/how-to-change-jframe-icon](https://stackoverflow.com/questions/1614772/how-to-change-jframe-icon) Otherwise check path to your jpeg – Naya Jan 21 '19 at 15:08

1 Answers1

0

This is used to add background image to frame.Now if you want to add button or textfield then add the button in textfield above the label. Means I have used f.add(l) this will add image to frame. Now if you want button on frame with background image then use as b=JButton("Name"); and now l.add(b); this will add button on top of image.

import java.awt.*;
import javax.swing.*;
import javax.swing.ImageIcon;
class ImgIcn
{
    JFrame f;
    JPanel p;
    public ImgIcn()
    {
        f=new JFrame("Exam System");
        f.setSize(600,400);
        //p=new JPanel();
        //p.setLayout(null);
        ImageIcon img= new ImageIcon(new ImageIcon("united.png").getImage().getScaledInstance(600, 400, Image.SCALE_DEFAULT));
        JLabel l=new JLabel();
        l.setIcon(img);
        //f.add(p);
        f.add(l);
        f.setVisible(true);
        f.setDefaultCloseOperation(2);
    }
    public static void main(String argss[])
    {
        new ImgIcn();
    }
}
Frakcool
  • 10,915
  • 9
  • 50
  • 89
Mohd Talha
  • 17
  • 4
  • 1
    Please add some explanation to your answer – sh.seo May 03 '19 at 16:46
  • This is used to add background image to frame.Now if you want to add button or textfield then add the button ir textfield above the label.Means I have used f.add(l) this will add image to frame.Now if uou want button on frame with background image then use as b=JButton("Name"); and now l.add(b); this will add button on top of image. – Mohd Talha May 03 '19 at 17:27