No background image in JFrame

I don't know what to do. I've read in the forum but nothing works!
I have a JFrame with JButtons (absolute positioning) and want an image as a background.
When you click a button, a new JFrame is opened.
public class MyProg extends JFrame {
public MyProg() {
setBounds(25,25,700,500);
Container contentPane.....
contentPane.setLayout(null);
JButton 1Button = new JButton(aString);
1Button.setActionCommand(aString);
1Button.setBounds(30,30,100,30);
contentPane.add(1Button);
class RadioListener implements ActionListener {
public void actionPerformed(Action Event e) {
frame2 = new JFrame(e.getActionCommand());
public static void main (String s[]) {
frame = new JFrame("Blabla");

1. MediaTracker - no, ImageIO - s�!
2. One technique for giving any container (like a frame's content pane) a background image, is to use a Border to do it.
import java.awt.*;
import java.awt.geom.*;
import java.awt.image.*;
import javax.swing.border.*;
public class CentredBackgroundBorder implements Border {
    private final BufferedImage image;
    public CentredBackgroundBorder(BufferedImage image) {
        this.image = image;
    public void paintBorder(Component c, Graphics g, int x, int y, int width, int height) {
        x += (width-image.getWidth())/2;
        y += (height-image.getHeight())/2;
        ((Graphics2D) g).drawRenderedImage(image, AffineTransform.getTranslateInstance(x,y));
    public Insets getBorderInsets(Component c) {
        return new Insets(0,0,0,0);
    public boolean isBorderOpaque() {
        return true;
import java.awt.*;
import java.io.*;
import java.net.URL;
import javax.imageio.*;
import javax.swing.*;
public class BackgroundBorderExample {
    public static void main(String[] args) throws IOException {
        final JFrame f = new JFrame("BackgroundBorderExample");
        f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        JTextArea area = new JTextArea(24,80);
        area.setForeground(Color.WHITE);
        area.setOpaque(false);
        area.read(new FileReader("BackgroundBorderExample.java"), null);
        JScrollPane sp = new JScrollPane(area);
        sp.getViewport().setOpaque(false);
        f.getContentPane().add(sp);
        String url = "http://today.java.net/jag/bio/JagHeadshot.jpg";
        sp.setViewportBorder(new CentredBackgroundBorder(ImageIO.read(new URL(url))));
        f.setSize(600,400);
        SwingUtilities.invokeLater(new Runnable() {
            public void run() {
                f.setLocationRelativeTo(null);
                f.setVisible(true);
}

Similar Messages

  • Can anyone suggest me a simple way to add a background image to JFrame ?

    I want to add a background image to JFrame in a simple way rather than overiding the paint method or paintComponent method. Just like adding an image to JButton or JLabel using two or three lines of code. Is it possible ? r there any methods for this purpose ? if so pls give the code.

    JFrame as such does not provide an option to set a background image.
    Extending JPanel, over-riding its paintComponent() and setting it as the contentPane of JFrame is one way of doing it. Though you have to do the overriding, it is not very complex though.

  • Problem with Background image and JFrame

    Hi there!
    I've the following problem:
    I created a JFrame with an integrated JPanel. In this JFrame I display a background image. Therefore I've used my own contentPane:
    public class MContentPane extends JComponent{
    private Image backgroundImage = null;
    public MContentPane() {
    super();
    * Returns the background image
    * @return Background image
    public Image getBackgroundImage() {
    return backgroundImage;
    * Sets the background image
    * @param backgroundImage Background image
    public void setBackgroundImage(Image backgroundImage) {
    this.backgroundImage = backgroundImage;
    * Overrides the painting to display a background image
    protected void paintComponent(Graphics g) {
    if (isOpaque()) {
    g.setColor(getBackground());
    g.fillRect(0, 0, getWidth(), getHeight());
    if (backgroundImage != null) {
    g.drawImage(backgroundImage,0,0,this);
    super.paintComponent(g);
    Now the background image displays correct. But as soon as I click on some combobox that is placed within the integrated JPanel I see fractals of the opened combobox on the background. When I minimize
    the Frame they disappear. Sometimes though I get also some fractals when resizing the JFrame.
    It seems there is some problem with the redrawing of the background e.g. it doesn't get redrawn as often as it should be!?
    Could anyone give me some hint, on how to achieve a clear background after clicking some combobox?
    Thx in advance

    I still prefer using a border to draw a background image:
    import java.awt.*;
    import java.awt.image.*;
    import javax.swing.border.*;
    public class CentredBackgroundBorder implements Border {
        private final BufferedImage image;
        public CentredBackgroundBorder(BufferedImage image) {
            this.image = image;
        public void paintBorder(Component c, Graphics g, int x, int y, int width, int height) {
            int x0 = x + (width-image.getWidth())/2;
            int y0 = y + (height-image.getHeight())/2;
            g. drawImage(image, x0, y0, null);
        public Insets getBorderInsets(Component c) {
            return new Insets(0,0,0,0);
        public boolean isBorderOpaque() {
            return true;
    }And here is a demo where I load the background image asynchronously, so that I can launch the GUI before the image is done loading. Warning: you may find the image disturbing...
    import java.awt.*;
    import java.io.*;
    import java.net.URL;
    import javax.imageio.*;
    import javax.swing.*;
    import javax.swing.border.*;
    public class BackgroundBorderExample {
        public static void main(String[] args) throws IOException {
            JFrame.setDefaultLookAndFeelDecorated(true);
            JFrame f = new JFrame("BackgroundBorderExample");
            f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            JTextArea area = new JTextArea(24,80);
            area.setForeground(Color.WHITE);
            area.setOpaque(false);
            area.read(new FileReader(new File("BackgroundBorderExample.java")), null);
            final JScrollPane sp = new JScrollPane(area);
            sp.setBackground(Color.BLACK);
            sp.getViewport().setOpaque(false);
            f.getContentPane().add(sp);
            f.setSize(600,400);
            f.setLocationRelativeTo(null);
            f.setVisible(true);
            String url = "http://today.java.net/jag/bio/JagHeadshot.jpg";
            final Border bkgrnd = new CentredBackgroundBorder(ImageIO.read(new URL(url)));
            Runnable r = new Runnable() {
                public void run() {
                    sp.setViewportBorder(bkgrnd);
                    sp.repaint();
            SwingUtilities.invokeLater(r);
    }

  • Setting background image in JFrame

    Witam,
    Jak mozna ustawic tlo w postaci grafiki (png, jpg, ...) dla jFrame? Znalalem juz kilka sposobow ale one uzywaja jPanel, ktorego ja NIE moge uzyc ... niestety. Jesli nie ma takiej mozliwosci dla jFrame to moze tez byc dla jScrollPane, JComponent, Scene albo LayerWidget;)
    Hi,
    Is it possoble to use image as a background for jFrame? I know that it is possible to use jPanel and ser background image for jPanel, but in my project I cannot use it. Instead I can use jFrame, jScrollPane, Scene or LayerWidget.:)

    In the future, Swing related questions should be posted in the Swing forum.
    But there is already no need to post in the Swing forum because you already know the answer:
    I know that it is possible to use jPanel and ser background image for jPanel,
    If you need further help then you need to create a "Short, Self Contained, Compilable and Executable, Example Program (SSCCE)", that demonstrates the incorrect behaviour.
    http://homepage1.nifty.com/algafield/sscce.html
    Don't forget to use the "Code Formatting Tags", so the posted code retains its original formatting.
    http://forum.java.sun.com/help.jspa?sec=formatting

  • Inserting a background image on JFrame

    I am developing an interactive system for the london 2012 olympics (Not a real one, just a project :-)) I am starting by creating my GUI layout. This is where i have started.
    import java.awt.*;        
    import java.awt.event.*;
    import javax.swing.*;
    import javax.swing.border.*;
    import java.util.*;
    import java.awt.event.KeyListener;
    import java.io.*;
    import java.text.*;
    public class Assignment extends JFrame  
       private JLabel londOnJLabel;
    public Assignment()
              ImageIcon image = new ImageIcon("???.jpg");
              JLabel background = new JLabel(image);
              background.setBounds(0, 0, image.getIconWidth(), image.getIconHeight());
              getLayeredPane().add(background, new Integer(Integer.MIN_VALUE));
    private void createUserInterface()
              Container contentPane = getContentPane();
              contentPane.setLayout( null );
              londOnJLabel = new JLabel();
              londOnJLabel.setBounds( 19, 19, 875, 28 );
              londOnJLabel.setText( "LONDON 2012" );
              londOnJLabel.setFont(new Font( "Default", Font.BOLD, 36 ) );
              londOnJLabel.setHorizontalAlignment(JLabel.CENTER );
              contentPane.add( londOnJLabel );
              setTitle( "LONDON 2012" );
              setSize( 1000, 750 );         
              setVisible( true );         
    public static void main( String[] args )
          Assignment application = new Assignment();
          application.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE );
    }So at the moment this Just displays LONDON 2012 on my application. Now what i would like to try and do is insert a background image of the olympic rings. How would i go about doing this?
    cheers

    THFC wrote:
    sorry, when u say dont subclass JFrame, are you referring to this?
    public Assignment() ....
    No I meant don't do this: public class Assignment extends JFrameBut rather do this: do this: public class Assignment extends JPanelFor example:
    import java.awt.BorderLayout;
    import java.awt.Color;
    import java.awt.Dimension;
    import java.awt.Font;
    import java.awt.Graphics;
    import java.awt.image.BufferedImage;
    import java.io.IOException;
    import java.net.URL;
    import javax.imageio.ImageIO;
    import javax.swing.JFrame;
    import javax.swing.JLabel;
    import javax.swing.JPanel;
    public class Assignment2 extends JPanel
      private static final String FILE_PATH = "myImageFile.jpg"; // !! change this
      private static final String NET_URL_PATH = "http://upload.wikimedia.org/wikipedia/commons/thumb/8/82/Mooring_bollard_at_sunset%2C_Lyme_Regis.jpg/800px-Mooring_bollard_at_sunset%2C_Lyme_Regis.jpg";
      // Photo by Michael Maggs, Wikimedia Commons: http://commons.wikimedia.org/wiki/Image:Mooring_bollard_at_sunset%2C_Lyme_Regis.jpg
      private BufferedImage image = null;
      public Assignment2()
        try
          // first load the image
          //image = ImageIO.read(new File(FILE_PATH));
          image = ImageIO.read(new URL(NET_URL_PATH));
        catch (IOException e)
          e.printStackTrace();
        // then set up the JPanel.  Try to avoid using the "null" layout
        JLabel titleLabel = new JLabel("My Title Goes Here");
        titleLabel.setFont(titleLabel.getFont().deriveFont(Font.BOLD, 36));
        titleLabel.setForeground(Color.lightGray);
        JPanel titlePanel = new JPanel();
        titlePanel.setOpaque(false);
        titlePanel.add(titleLabel);
        setPreferredSize(new Dimension(800, 590));
        setLayout(new BorderLayout());
        add(titlePanel, BorderLayout.NORTH);
      @Override  // here's where I paint my background:
      protected void paintComponent(Graphics g)
        super.paintComponent(g);
        if (image != null)
          g.drawImage(image, 0, 0, this);
      private static void createAndShowUI()
        // Then I only create my JFrame when I need it.  I don't override it.
        // This way, I can use this same code in a JApplet, or a JDialog, or whatever
        JFrame frame = new JFrame("Assignment2");
        frame.getContentPane().add(new Assignment2()); // and add the JPanel to the JFrame here
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.pack();
        frame.setLocationRelativeTo(null);
        frame.setVisible(true);
      public static void main(String[] args)
        java.awt.EventQueue.invokeLater(new Runnable()
          public void run()
            createAndShowUI();
    }Edited by: Encephalopathic on May 26, 2008 4:11 PM

  • Adding background image to JFrame

    This is the code I have now. I want to add a background image to the JFrame, and it needs to be where i type the file name of the image into the program code and it loads it from my computer.
    import javax.swing.*;
    import java.awt.*;
    import java.awt.event.*;
    class GUIFrame extends JFrame implements ActionListener, KeyListener
         Display myDisplay;
         Button guess;
         Button solve;
         TextField input;
         JTextArea guessedLetters;
         MenuBar myBar;
         Menu fileMenu;
         MenuItem fileNewGame;
         MenuItem fileQuit;
         * constructor sets title of GUI window
         GUIFrame()
              super("Hangman");
              setSize(1000,600);
              guess = new Button("Guess");     
              guess.setFocusable(false);
              solve = new Button("Solve");     
              solve.setFocusable(false);
              input = new TextField(20);
              guessedLetters=new JTextArea(10,10);
              guessedLetters.setEditable(false);
              myBar=new MenuBar();
              fileMenu=new Menu("File");
              fileNewGame=new MenuItem("New Game");
              fileQuit=new MenuItem("Quit");
              myDisplay = new Display();     //make an instance of the window
              setLayout(new FlowLayout());     //How things are added to our Frame
              add(myDisplay);
              add(guess);
              add(solve);
              add(input);
              add(guessedLetters);
              setMenuBar(myBar);
              myBar.add(fileMenu);
              fileMenu.add(fileNewGame);
              fileMenu.add(fileQuit);
              addKeyListener(this);
              guess.addActionListener(this);
              solve.addActionListener(this);
              setVisible(true);     //make the frame visible
         * exectues when user presses a button.
         public void actionPerformed(ActionEvent e)
         public void keyPressed(KeyEvent e)
         public void keyReleased(KeyEvent e)
         public void keyTyped(KeyEvent e)
    }

    Look in the API under JFileChooser and Scanner to see how to get the file name. One you have it, you can load the file easily using several different methods...
    This is even easier, you can paint and image onto anything you like with this method:
    g.drawImage(image, 0, 0, null); //where g is the graphics context from the object you want to paint.
    Simple as that.
    The biggest problem you'll have with painting images onto other objects is making sure the image is loaded before you try to draw it; use ImageIO to load or add your image to a MediaTrakker after your load statement like this:
    Image im = (Image)ImageIO.read(new File("c:/myImages/myImage.jgp"));
    or
    BufferedImage bi = ImageIO.read(new File("c:/myImages/myImage.jgp"));
    or
    Image image = Toolkit.getDefaultToolkit().getImage("c:/myImages/myImage.jgp");
    MediaTracker mediaTracker = new MediaTracker(jf);
    mediaTracker.addImage(image, 0);
    mediaTracker.waitForID(0);
    BTW: what this means it that you can paint right onto the graphics content of the JFrame and not have to worry about any other containers if you want.
    If you expect the image to last more than just a flash, then you also need to override your paintComponents(Grahics) method to paint your graphics to your screen.

  • Loading background image

    Hey all i'm having a little difficulty loading an image as a background. This is the code currently used to create several panels and add to a main container:
    import java.awt.*;
    import java.awt.event.*;
    import java.util.Random;
    import java.awt.image.BufferedImage;
    import java.io.File;
    import java.io.IOException;
    import javax.imageio.ImageIO;
    import javax.swing.*;
    import java.io.*;
    public class MainPanel extends JFrame implements ActionListener {
         private JMenuItem newGame, endGame, exitApplication; // File menu items
         private JRadioButtonMenuItem easyLevel, mediumLevel, hardLevel; // Level menu items
         DiePanel diePanel;
         QuestionPanel questionPanel;
         PicturePanel board;
         public MainPanel (){
              // Call & set up DiePanel
              diePanel = new DiePanel();
              diePanel.setBorder (BorderFactory.createEtchedBorder());
              diePanel.setPreferredSize(new Dimension(254,86));
              diePanel.setVisible(true);
              // Call & set up QuestionPanel
              questionPanel = new QuestionPanel();
              questionPanel.setBorder (BorderFactory.createEtchedBorder());
              questionPanel.setPreferredSize(new Dimension(304,86));
              questionPanel.setVisible(true);
              // Call & set up BoardPanel
              board = new PicturePanel(diePanel, questionPanel);
              board.setPreferredSize(new Dimension(622,622));
              board.setVisible(true);
              diePanel.setBoard(board);
              // Add panels to container
              Container c = getContentPane();
             c.setLayout (new FlowLayout());
             c.add(diePanel);
             c.add(Box.createHorizontalStrut(20));
             c.add(questionPanel);
             c.add(board);And i create the main JFrame with this:
    import javax.swing.JFrame;
    import javax.swing.SwingUtilities;
    public class Main {
         public static void main(String [] args) {
             SwingUtilities.invokeLater(new Runnable() {
                  public void run() {
                       JFrame MainPanel = new MainPanel();
                       MainPanel.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
                       MainPanel.setSize(800, 800);
                       MainPanel.setVisible(true);
                       MainPanel.setTitle("Math's Mayhem");
    }I've tried numerous ways to try and load an image but to no avail! Do i need to use layered panes or is there a more simple way?

    Anand_EKM wrote:
    Also meanwhile you can visit the link [Setting Background Image on JFrame|http://javaallinone.blogspot.com/2008/03/setting-background-image-on-jframe.html]
    The code presented in the link above (probably) works, but should NOT be copied verbatim! It has several problems:
    1. That code loads and creates the image each time the JPanel's paintComponent() method is called, which is terribly inefficient. It should be modified so that the image is loaded once (when the JFrame or JPanel is first created) and cached. paintComponent() should then simply call g.drawImage().
    2. You should also create the Image via ImageIO.read() rather than new ImageIcon(...).getImage() as done in that example, to avoid unnecessarily creating an ImageIcon. It's not a huge deal, but your code will be cleaner and more readable.
    3. I'm not sure why this example wants to do things such as setting the preferred/minimum/maximum sizes and layout used in the paintComponent() body.
    Edited by: BoBear2681 on Apr 2, 2008 12:48 PM

  • How to get Internal frames as well as a background image in a JFrame?

    Hi All,
    Here's my problem. I have a JFrame with a background image that I got by overridding the paintComponent() method of a JPanel and setting as the contentPane of a JFrame. Works great.
    Now what I want is to use internal frames with this Frame a la JInternalFrame classes. But you need to create a JDesktopPane object and set this as the contentPane of the JFrame to get internal frames to work, right? Is there a way for me to have my cake and eat it so I get both internal frames and a background image? Thanks!

    Hmmm,
    so simple, why didn't I think of that? Damn Mondays!
    thanks very much!

  • JFrame background image

    Hi all , i need to put a background image into a JFrame, currently i am seeting a label with an icon and adding it to the jframe but it pusshes all my other components across. how do i get it to be displayed behind the other components?
    final JFrame frame = new JFrame("Bank Accounts");
             frame.setSize(425,203);
             final Container container = frame.getContentPane();
         a = new javax.swing.JLabel();
         a.setIcon(new javax.swing.ImageIcon("spacePic.jpg"));
      frame.add(a);
    a.setOpaque(true);
             GridBagLayout gblMain = new GridBagLayout(); // Create the layout
             container.setLayout(gblMain);// Set layout on container
              GridBagLayout gblRight = new GridBagLayout();
                  JPanel aPanel2 = new JPanel(gblRight);

    sorry here is a better display if the code
    final JFrame frame = new JFrame("Bank Accounts");
             frame.setSize(425,203);
             final Container container = frame.getContentPane();
         a = new javax.swing.JLabel();
         a.setIcon(new javax.swing.ImageIcon("spacePic.jpg"));
            frame.add(a);
           a.setOpaque(true);
             GridBagLayout gblMain = new GridBagLayout(); // Create the layout
             container.setLayout(gblMain);// Set layout on container
         GridBagLayout gblRight = new GridBagLayout();
             JPanel aPanel2 = new JPanel(gblRight);

  • Setting the background image in a JFrame

    Hi all,
    I have a .gif that I want to display as the background image in a JFrame. How do I do that?
    regards,
    Mat

    Check out this thread:
    http://forum.java.sun.com/thread.jsp?forum=31&thread=288769

  • Image as a background for a JFrame

    Hi all,
    Is it possible to have an image as a background for a JFrame?
    How do you do it?
    plz help

    i personally inherit a panel...
      class ImagePanel extends JPanel {
          Image image;
          public ImagePanel(Image image) {
              this.image = image;
          public void paintComponent(Graphics g) {
              super.paintComponent(g); //paint background
              //Draw image at its natural size first.
              g.drawImage(image, 0, 0, this); //85x62 image
      } and call it with
      private Image icLogo =
    Toolkit.getDefaultToolkit().getImage(getClass().getResource("icLogo.gif"));
      private JPanel imgPanel = new ImagePanel(icLogo);Well, this should work with frames, too. In case it doesn't, you can simply add this panel to the frame.
    greets
    Jochen

  • Display image in JFrame

    I am looking for a way to display an image in a jframe. I want to avoid wrapping it into a container..such as a JPanel, JLabel..ect. Does anyone know a way? I seen in the API there is a Graphics function drawImage but I can not get it to work, and tried using the paintIcon function from the ImageIcon class but that doesnt work either. Any one that can help I would much appreciate it. Thanks
    import javax.swing.*;
    import java.awt.*;
    class displayImage extends JFrame{
    // user's screen width
    private int screenWidth;
    // user's screen height
    private int screenHeight;
    ImageIcon im;
    Image image;
    public displayImage (){
    im = new ImageIcon( "<filename>" );
    image = Toolkit.getDefaultToolkit().getImage("<filename>"");
    screenWidth = (int)Toolkit.getDefaultToolkit().getScreenSize().getWidth();
    screenHeight = (int)Toolkit.getDefaultToolkit().getScreenSize().getHeight();
    resizeGUI ();
    setVisible(true);
    validate();
    public void paint(Graphics g) {
    im.paintIcon(this,g,180,0);
    g.drawImage(image,0,120,this);
    private void resizeGUI()
    // set window size
    if (screenWidth >= 1280)
    setSize(1024, 768);
    else if (screenWidth >= 1024)
    setSize(800, 600);
    else if (screenWidth >= 800)
    setSize(640, 480);
    // maximize window
    setExtendedState(this.getExtendedState() | this.MAXIMIZED_BOTH);
    public void update(Graphics g) {
    paint(g);
    }

    1) Use the [url http://forum.java.sun.com/help.jspa?sec=formatting]Code Formatting Tags when posting code, so the code is readable. There is also a "Preview" button as well you should be using.
    2) There is no need to override paint() or update() in a Swing application. Thats old code for AWT.
    I am looking for a way to display an image in a jframe. I want to avoid
    wrapping it into a container..such as a JPanel, JLabel..ect.Well thats the way its done in Swing. Read the Swing tutorial on [url http://java.sun.com/docs/books/tutorial/uiswing/14painting/concepts.html]Custom Painting for more information on how painting is done in Swing and you will understand why.
    There actually is a solution in the forum somewhere that allows you to specify a Border, where the Border is actually a image that get painted in the background. Don't remember the posting though. Search the forum using "background image" and you might find it.

  • Problem in setting background Image to TabedPane.

    Hi Pals,
    I created a JFrame which consist of some components. The structure of the added components are given below.
    1) I added a JPanel (MainPanel) with background image in a JFrame.
    2) I added a JTabbedPane with 7 tabs in the previous JPanel (MainPanel).
    3) Each tabs in the JTabbedPane having JPanel with Background Image.
    This is my Frame Structure. but i haven't problem to run in JDK1.6,1.5. It is working perfect. But when am run in lower version like 1.3 or 1.4. The design is looking bad. The JTabbedPane overlap the (MainPanel). The background image of the (MainPanel) was hided. I set setOpaque(false) for the JTabbedPane. But it also not working. How can i solve this problem.
    By,
    Mohan

    Your problems appear to stem from your choice of layout manager(s). To get better help sooner, post a [_Short, Self Contained, Compilable and Executable, Example Program (SSCCE)_|http://mindprod.com/jgloss/sscce.html] that clearly demonstrates your problem.
    To post code, use the code tags -- [code]Your Code[/code] will display asYour CodeOr use the code button above the editing area and paste your code between the {code}{code} tags it generates.
    db

  • How to add an image to JFrame....

    Hello evryone,
    Here i'm posting my code..and in this i would like to add a .jpg file as background..I hav tried for imageicon and Bufferdimage...
    Help me out...
    import java.awt.event.*;
    import java.awt.*;
    import java.applet.*;
    import javax.swing.*;
    import java.lang.*;
    import java.awt.image.*;
    import java.awt.Container.*;
    import java.io.FileInputStream.*;
    import java.io.*;
    import javax.imageio.*;
    public class Kbc extends JFrame implements ActionListener
    Container c;
    JButton b1,b2,b3;
    JLabel l;
    public Kbc()
    c = getContentPane() ;
    c.setLayout(null) ;
    l=new JLabel("--:WeLcoMe :--");
    Font f = new Font("Dialog", Font.PLAIN, 24);
    l.setFont(f);
    l.setBounds(300,30,1100,20);
    c.add(l);
    b1=new JButton("START");
    b1.setFont(f);
    b1.setPreferredSize( new Dimension(200,100) ) ;
    b1.setSize( b1.getPreferredSize() ) ;
    b1.setLocation(350,100) ;
    b1.addActionListener(this) ;
    c.add(b1) ;
    b2=new JButton("QUIT");
    b2.setFont(f);
    b2.setPreferredSize( new Dimension(200,100) ) ;
    b2.setSize( b2.getPreferredSize() ) ;
    b2.setLocation(350,210) ;
    b2.addActionListener(this) ;
    c.add(b2) ;
    b3=new JButton("HELP");
    b3.setFont(f);
    b3.setPreferredSize( new Dimension(200,100) ) ;
    b3.setSize( b3.getPreferredSize() ) ;
    b3.setLocation(350,320) ;
    b3.addActionListener(this) ;
    c.add(b3) ;
    setSize(1100,700);
    setVisible(true);
    public void actionPerformed(ActionEvent e)
    if(e.getSource()==b1)
    new Start1();
    this.hide();
    else
    if(e.getSource()==b2)
    System.exit(0);
    if(e.getSource()==b3)
    JOptionPane.showMessageDialog(c,"RuLes"");
    public static void main(String args[])
    Kbc k=new Kbc();
    /*<applet code="Kbc" height=500 width=900>
    </applet>*/
    {code}{code}

    Hi,
    extends JFrame is application.
    If applet extends JApplet.
    Here is an example of the application.
    Please run this way java Kbc test.jpg
    test.jpg is the background image. Please change file name.
    public class Kbc extends JPanel implements ActionListener {
    private JButton b1, b2 , b3 ;
    private JLabel l ;
    static private String filename ;
    private Image image ;
    private JLayeredPane layeredPane ;
    public Kbc() {
         layeredPane = new JLayeredPane() ;
         layeredPane.setPreferredSize( new Dimension(1100,700) ) ;
    l=new JLabel(":Wellcome :");
    Font f = new Font("Dialog", Font.PLAIN, 24);
    l.setFont(f);
    l.setBounds(300,30,1100,20);
    layeredPane.add(l, new Integer( 3 ) );
    b1=new JButton("START");
    b1.setFont(f);
    b1.setPreferredSize( new Dimension(200,100) ) ;
    b1.setSize( b1.getPreferredSize() ) ;
    b1.setLocation(350,100) ;
    b1.addActionListener(this) ;
    layeredPane.add(b1,new Integer( 1 ) ) ;
    b2=new JButton("QUIT");
    b2.setFont(f);
    b2.setPreferredSize( new Dimension(200,100) ) ;
    b2.setSize( b2.getPreferredSize() ) ;
    b2.setLocation(350,210) ;
    b2.addActionListener(this) ;
    layeredPane.add(b2, new Integer( 2 ) ) ;
    b3=new JButton("HELP");
    b3.setFont(f);
    b3.setPreferredSize( new Dimension(200,100) ) ;
    b3.setSize( b3.getPreferredSize() ) ;
    b3.setLocation(350,320) ;
    b3.addActionListener(this) ;
    layeredPane.add(b3, new Integer( 5 )) ;
    add( layeredPane);
    public void paintComponent (Graphics g) {
              super.paintComponent(g);
    try {
    File f = new File(filename);
    BufferedImage image = ImageIO.read(f);
    g.drawImage(image, 0, 0, this);
    } catch (Exception ex) {
    ex.printStackTrace();
    public void actionPerformed(ActionEvent e) {
    if (e.getSource()==b1)
    // new Start1();
    this.setVisible(false) ;
    else if (e.getSource()==b2) {
    System.exit(0);
    } else if (e.getSource()==b3) {
    JOptionPane.showMessageDialog(this,"RuLes");
    public static void main(String args[]) {
    filename = args[0] ;
    SwingUtilities.invokeLater(new Runnable() {
    public void run() {
    createAndShowGUI();
    private static void createAndShowGUI() {
    System.out.println("Created GUI on EDT? "+
    SwingUtilities.isEventDispatchThread());
         Kbc k=new Kbc();
    JFrame frame = new JFrame("Kbc");
         frame.add(k);
    frame.pack();
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    frame.setPreferredSize(new Dimension(1100, 700 ) );
    frame.setVisible(true);
    }

  • Background image for a JApplet

    Hi everybody.
    I have a app with some textfields, buttons and some JLabels.
    I want to put a image as background.
    How can I do that?
    Thanks in advance.

    JApplet (and JFrame and any root container) has a Container that it uses to hold everything else, its contentPane. I would create a JPanel and make it my applet's contentPane and then add everything to this contentPane. To show an image on the contentPane/JPanel, I'd simply Google Background image jpanel. I'd get and then read this: [http://faq.javaranch.com/java/BackgroundImageOnJPanel]
    (I've actually bookmarked this page as it gets asked here so often).

Maybe you are looking for