Posted By:
Craig_Wood
Posted On:
Wednesday, March 3, 2004 04:05 PM
If you override the paint method in JFrame you are calling the paint method from the Container api (see down in the section Methods inherited from class java.awt.Container in the JFrame api) which is called to paint all components in the Container. So it will paint over any components. Try restricting the area of painting to a smaller area to see how it works.
Another way to do this is to create a JPanel and use it as the content pane in the JFrame.
import java.awt.*;
import java.io.*;
import java.net.*;
import javax.imageio.ImageIO;
import javax.swing.*;
public class FrameDecoration
{
public static void main(String[] args)
{
JFrame f = new JFrame();
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.setContentPane(new BackgroundPanel());
f.setSize(400,300);
f.setLocation(200,200);
f.setVisible(true);
}
}
class BackgroundPanel extends JPanel
{
Image image;
public BackgroundPanel()
{
loadImage();
setBackground(Color.yellow);
}
public void paintComponent(Graphics g)
{
super.paintComponent(g);
int width = getWidth();
int height = getHeight();
int imageWidth = image.getWidth(this);
int imageHeight = image.getHeight(this);
int x = (width - imageWidth)/2;
int y = (height - imageHeight)/2;
g.drawImage(image, x, y, this);
}
private void loadImage()
{
String fileName = "images/bclynx.jpg";
try
{
URL url = getClass().getResource(fileName);
image = ImageIO.read(url);
}
catch(MalformedURLException mue)
{
System.out.println(mue.getMessage());
}
catch(IOException ioe)
{
System.out.println(ioe.getMessage());
}
}
}