3

I have a JFrame with BorderLayout, there are panels on all sides (North, East ,...). In the panels there are labels and buttons mostly.

Now I want the frame to have a background image, some research told me that i had to change the content pane of my frame.

When I try this however, the content gets put in the background and isn't visible. Also, I don't know how to resize the image if the frame is resized.

Is there an easy fix for this or will I have to rework most of my code?

Andrew Thompson
  • 168,117
  • 40
  • 217
  • 433
Petr Safar
  • 107
  • 2
  • 11

3 Answers3

4
  1. put JPanel (or JComponent) with background Image to the BorderLayout.CENTER, then this JPanel fills whole JFrame area, rest of yout JComponents put to this JPanel

  2. there are Jpanels on all sides (North, East ,...). In the Jpanels there are Jlabels and Jbuttons mostly.

    these JComponents covered all available Rectangle for JFrame, then Background Image (from my 1st point) never will be dispalyed, because these JComponents are on_top JFrame and could be hide this Image as well,

  3. add JPanel with Background Image (from my 1st point), then put there another JPanel(s) with JPanel#setOpaque(false);, then this JPanel will be transparent, notice JPanel has implemented by default FlowLayout

Community
  • 1
  • 1
mKorbel
  • 109,525
  • 20
  • 134
  • 319
1
frame.getContentPane().add(new JPanel() {

      public void paintComponent(Graphics g) {
            g.drawImage(img, 0, 0, this.getWidth(), this.getHeight());
      }
});
kleopatra
  • 51,061
  • 28
  • 99
  • 211
Mr rain
  • 983
  • 5
  • 13
  • 27
  • beware: a) this is a valid overrided only if the image is not transparent anywhere. b) adding to the contentPane does not fulfil the requirement of being below everything added :-) – kleopatra Mar 22 '12 at 11:58
0

This example will get you started. Use it like any JPanel.

public class JPanelWithBackground extends JPanel {
Image imageOrg = null;
Image image = null;
{
    addComponentListener(new ComponentAdapter() {
        public void componentResized(ComponentEvent e) {
            int w = JPanelWithBackground.this.getWidth();
            int h = JPanelWithBackground.this.getHeight();
            image = w>0&&h>0?imageOrg.getScaledInstance(w,h, 
                    java.awt.Image.SCALE_SMOOTH):imageOrg;
            JPanelWithBackground.this.repaint();
        }
    });
}
public JPanelWithBackground(Image i) {
    imageOrg=i;
    image=i;
    setOpaque(false);
}
public void paint(Graphics g) {
    if (image!=null) g.drawImage(image, 0, 0, null);
    super.paint(g);
}
}

Usage Example:

    Image image = your image
    JFrame f = new JFrame("");
    JPanel j = new JPanelWithBackground(image);
    j.setLayout(new FlowLayout());
    j.add(new JButton("YoYo"));
    j.add(new JButton("MaMa"));
    f.add(j);
    f.setVisible(true);
Java42
  • 7,628
  • 1
  • 32
  • 50