Try to add this:
//4. Size the frame.
this.pack();
//5. Show it.
this.setVisible(true);
Taken from here.
npinti
2010-06-02 18:20:43
Like this?
Addendum: "Normally you would invoke super.paintComponent(g)
first, but since the image will cover the entire background there is no need to do this."—camickr
import java.awt.Dimension;
import java.awt.EventQueue;
import java.awt.Graphics;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import javax.imageio.ImageIO;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
public class Imager {
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
@Override
public void run() {
JFrame frame = new JFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add(new ImagePanel("image.jpg"));
frame.pack();
frame.setVisible(true);
}
});
}
private static class ImagePanel extends JPanel {
BufferedImage img;
ImagePanel(String name) {
super(true);
this.setToolTipText(name);
this.add(new JLabel(name));
try {
img = ImageIO.read(new File(name));
this.setPreferredSize(new Dimension(
img.getWidth(), img.getHeight()));
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
@Override
protected void paintComponent(Graphics g) {
g.drawImage(img, 0, 0, this.getWidth(), this.getHeight(), null);
}
}
}
Possible duplicate of.....
http://stackoverflow.com/questions/2141020/jpanel-with-background-image-with-other-panels-overlayed http://stackoverflow.com/questions/1064977/setting-background-images-in-jframe http://stackoverflow.com/questions/2645452/background-image-in-a-jframe http://stackoverflow.com/questions/2706054/background-image-in-java http://stackoverflow.com/questions/2937403/jpanel-background-image http://stackoverflow.com/questions/2227423/java-swing-background-image