Link to home
Start Free TrialLog in
Avatar of Ranjith
Ranjith

asked on

Background for a frame

I would like to add an image as a background of a frame but still be able to add things on top of it. I mean the image frame should act like a normal frame with the background image, but still i should be able to add label or whaterver like a normal frame. Thank You
Avatar of CEHJ
CEHJ
Flag of United Kingdom of Great Britain and Northern Ireland image

import java.awt.event.*;import javax.swing.*;import java.awt.*;public class TestBackground extends JFrame{     ImageIcon img;     public TestBackground()     {          img = new ImageIcon("????.jpg");          JPanel panel = new JPanel()          {               public void paintComponent(Graphics g)               {                    g.drawImage(img.getImage(), 0, 0, null);                    super.paintComponent(g);               }          };          panel.setOpaque(false);          panel.add( new JButton( "Hello" ) );          setContentPane( panel );     }     public static void main(String [] args)     {          TestBackground frame = new TestBackground();          frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);          frame.setSize(300, 300);          frame.setVisible(true);     }}
What a mess!
No offense.
Ugh, sorry about that formatting! This is better:

import java.awt.event.*;
import javax.swing.*;
import java.awt.*;

public class TestBackground extends JFrame{
  ImageIcon img;

  public TestBackground(){
    img = new ImageIcon("ex-eng.gif");
    JPanel panel = new JPanel(){
      public void paintComponent(Graphics g){
        g.drawImage(img.getImage(), 0, 0, null);
        super.paintComponent(g);
      }
    };
    panel.setOpaque(false);
    panel.add( new JButton( "Hello" ) );
    setContentPane( panel );
  }

  public static void main(String [] args) {
    TestBackground frame = new TestBackground();
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    frame.setSize(300, 300);
    frame.setVisible(true);
  }
}
Avatar of Ranjith
Ranjith

ASKER

Thanks a lot man. It works!!
Avatar of Ranjith

ASKER

Thanks a lot man. It works!!
ASKER CERTIFIED SOLUTION
Avatar of CEHJ
CEHJ
Flag of United Kingdom of Great Britain and Northern Ireland image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial