import java.awt.*;
import java.io.*;
import java.net.*;
import javax.imageio.ImageIO;
import javax.imageio.stream.FileImageInputStream;
import javax.swing.*;
public class TestBackgroundImg
{
public static void main(String[] args)
{
JFrame f = new JFrame();
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
ImageContentPane contentPane = new ImageContentPane();
f.getContentPane().add(new JScrollPane(contentPane));
addComponents(contentPane);
f.setSize(400,400);
f.setLocation(200,200);
f.setVisible(true);
}
private static void addComponents(Container cp)
{
GridBagLayout gridbag = new GridBagLayout();
cp.setLayout(gridbag);
GridBagConstraints gbc = new GridBagConstraints();
gbc.insets = new Insets(5,5,5,5);
gbc.weightx = 1.0;
gbc.weighty = 1.0;
cp.add(new JButton("button 1"), gbc);
gbc.gridwidth = gbc.RELATIVE;
cp.add(new JButton("button 2"), gbc);
gbc.gridwidth = gbc.REMAINDER;
CustomComponent owl = new CustomComponent("Bird.gif");
owl.setLayout(gridbag);
owl.add(new JButton("button 5"), gbc);
owl.add(new JButton("button 6"), gbc);
cp.add(owl, gbc);
gbc.gridwidth = 1;
cp.add(new JButton("button 3"), gbc);
gbc.gridwidth = gbc.RELATIVE;
cp.add(new JButton("button 4"), gbc);
gbc.gridwidth = gbc.REMAINDER;
cp.add(new CustomComponent("duke_hips.png"), gbc);
}
}
class ImageContentPane extends JPanel
{
Image image;
public ImageContentPane()
{
loadImage();
setBackground(Color.white);
setOpaque(true); // just in case...
}
protected void paintComponent(Graphics g)
{
super.paintComponent(g);
int w = getWidth();
int h = getHeight();
int imageWidth = image.getWidth(this);
int imageHeight = image.getHeight(this);
int x = (w - imageWidth)/2;
int y = (h - imageHeight)/2;
g.drawImage(image, x, y, this);
}
private void loadImage()
{
String fileName = "background.gif";
try
{
URL url = getClass().getResource(fileName);
File file = new File(url.getFile());
FileImageInputStream fiis = new FileImageInputStream(file);
image = ImageIO.read(fiis);
}
catch(MalformedURLException mue)
{
System.out.println("url: " + mue.getMessage());
}
catch(IOException ioe)
{
System.out.println("read: " + ioe.getMessage());
}
}
}
class CustomComponent extends JPanel
{
Image image;
public CustomComponent(String fileName)
{
loadImage(fileName);
}
protected void paintComponent(Graphics g)
{
super.paintComponent(g);
g.drawImage(image, 0, 0, this);
}
public Dimension getPreferredSize()
{
return new Dimension(image.getWidth(this), image.getHeight(this));
}
private void loadImage(String fileName)
{
try
{
URL url = getClass().getResource(fileName);
File file = new File(url.getFile());
FileImageInputStream fiis = new FileImageInputStream(file);
image = ImageIO.read(fiis);
}
catch(MalformedURLException mue)
{
System.out.println("url: " + mue.getMessage());
}
catch(IOException ioe)
{
System.out.println("read: " + ioe.getMessage());
}
}
}