The best way to load an image is through the ImageIO
API
BufferedImage img = ImageIO.read(new File("/path/to/some/image"));
There are a number of ways you can render an image to the screen.
You could use a JLabel
. This is the simplest method if you don't want to modify the image in anyway...
JLabel background = new JLabel(new ImageIcon(img));
Then simply add it to your window as you see fit. If you need to add components to it, then you can simply set the label's layout manager to whatever you need and add your components.
If, however, you need something more sophisticated, need to change the image somehow or want to apply additional effects, you may need to use custom painting.
First cavert: Don't ever paint directly to a top level container (like JFrame
). Top level containers aren't double buffered, so you may end up with some flashing between repaints, other objects live on the window, so changing it's paint process is troublesome and can cause other issues and frames have borders which are rendered inside the viewable area of the window...
Instead, create a custom component, extending from something like JPanel
. Override it's paintComponent
method and render your output to it, for example...
protected void paintComponent(Graphics g) {
super.paintComponent(g);
g.drawImage(img, 0, 0, this);
}
Take a look at Performing Custom Painting and 2D Graphics for more details