Background image on JPanel

Posted by on May 18, 2011 in Java | 1 comment

Background image on JPanel

User interfaces often look boring or lifeless. Most of them feature an arbitrary amount of buttons, text input boxes, select boxes and other form elements that need to be filled out by the user. The acceptance of windows containing such forms often depends on how esthetic a user finds them.

This tutorial will show you how easy it is to add a background image to a JPanel and thereby making your application look prettier and probably more exciting to use!

How will it look like?

The following shows an example of an otherwise pretty dull user interface which got enriched by a background image making the application more exciting and fun to use.

The image from the screenshot was taken from www.theblackparade.de (the site does no longer exist).

How it is done

We create an ordinary JPanel and override its paintComponent(Graphics g) method. Within this method we paint the background image:

public class JBackgroundPanel extends JPanel {
  private BufferedImage img;

  public JBackgroundPanel() {
    // load the background image
    try {
      img = ImageIO.read(new File("./back.jpg"));
    } catch(IOException e) {
      e.printStackTrace();
    }
  }

  @Override
  protected void paintComponent(Graphics g) {
    super.paintComponent(g);
    // paint the background image and scale it to fill the entire space
    g.drawImage(img, 0, 0, getWidth(), getHeight(), this);
  }
}

As usual we can now add any kind of component to our JPanel. Finally, we add our background image panel to a JFrame.

// create the panel with the background image
JBackgroundPanel bgPanel = new JBackgroundPanel();

// add some elements...
bgPanel.add(new JLabel("Applications don't have to look boring!"));
bgPanel.add(new JComboBox(new String[] {"Background 1", "Background 2"}));
bgPanel.add(new JButton("True"));

// create a window
JFrame f = new JFrame("JPanel with background image");
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.setSize(500, 250);
f.setLocationRelativeTo(null);

// add the panel with the background image
f.add(bgPanel);

// show the window
f.setVisible(true);

Of course you could set the image path in the constructor of the JBackgroundPanel class and thereby making its usage much more flexible.

That’s it. With the use of this simple trick you will be able to design attractive windows that will make the user of your app enjoy working with it. Just make sure not to use too many image or images that distract the user!

One Comment

  1. THANKS YOU !!!!

Leave a Reply

Your email address will not be published. Required fields are marked *

*

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>