Hi, evry1.. i need yur help.. i want to place an image as my background.. how am i supposed to do it..?? i have tried this setBackground("C:\\image\\background.jpg");i also tired this Icon m1 = new ImageIcon("C:\\New folder (5)\\background.jpg");lb1.setIcon(m1); But none of this is working.. what shuld i do???

You create a subclass of JPanel and override its paintComponent method to draw your image when the panel is repainted. Then add your components to the panel to display then in front of the image.
Sounds complicated, but the code is quite simple. Here's a decent example

Edited 2 Years Ago by JamesCherrill

JPanel is compulsory?? coz i haven't used JPanel in my program.. This there any other alternative??

JPanel is very standard stuff. Just add all your controls to the JPanel, then add the JPanel to your JFrame. Later on you will discover all kinds of reasons why you want to do it like that.

could u gve me some examples?? coz i didnt get the concept of JPanel...

I think you need to give us some examples. What do you mean by "background?" Are you creating a GUI swing app? If so, then the assumption to use JPanel (or JFrame) makes sense. But you can create a GUI app with JavaFX if you are being more modern and you could use the java.awt package if you took some book out of the library from 1998.

Hi!

If you want to set image as your background on your Container (JFrame,Jpanel,etc..,), set an JLable 1st then place the image as an icon onthe JLable, fille the lable with your container.., Thats all..,

Have A Happy Day..,

Raj:
How do you intend to keep the other components in front of the image JLabel?
Which layout manager would you use to place components overlapping the image JLabel?

Mr.James!

i have changed the Layout

import javax.swing.JOptionPane;

/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */

/**
 *
 * @author Android_Raj
 */
public class BackGroundTest extends javax.swing.JFrame {

    /**
     * Creates new form BackGroundTest
     */
    public BackGroundTest() {
        initComponents();
    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">                          
    private void initComponents() {

        jButton1 = new javax.swing.JButton();
        jLabel1 = new javax.swing.JLabel();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
        getContentPane().setLayout(new org.netbeans.lib.awtextra.AbsoluteLayout());

        jButton1.setText("On JLabl");
        jButton1.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton1ActionPerformed(evt);
            }
        });
        getContentPane().add(jButton1, new org.netbeans.lib.awtextra.AbsoluteConstraints(110, 490, 170, -1));

        jLabel1.setIcon(new javax.swing.ImageIcon(getClass().getResource("/srts.png"))); // NOI18N
        jLabel1.setText("jLabel1");
        getContentPane().add(jLabel1, new org.netbeans.lib.awtextra.AbsoluteConstraints(0, 0, 450, 520));

        pack();
    }// </editor-fold>                        

    private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {                                         
        // TODO add your handling code here:
        JOptionPane.showMessageDialog(rootPane, "Hi!  I am on JLabel..,");
    }                                        

    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        /* Set the Nimbus look and feel */
        //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
        /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
         * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html 
         */
        try {
            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                if ("Nimbus".equals(info.getName())) {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
        } catch (ClassNotFoundException ex) {
            java.util.logging.Logger.getLogger(BackGroundTest.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(BackGroundTest.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(BackGroundTest.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(BackGroundTest.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        //</editor-fold>

        /* Create and display the form */
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                new BackGroundTest().setVisible(true);
            }
        });
    }

    // Variables declaration - do not modify                     
    private javax.swing.JButton jButton1;
    private javax.swing.JLabel jLabel1;
    // End of variables declaration                   
}

The out put will be
bfa74c5eac6800879894873028700d2f

is the solution right or wrong, Can you replay me..,
if it is wrong i can correct myself..,

You have used absolute coordinates to place your labels, which is OK if you will never run this on any device with a different screen resolution. In particular, run it on a "retina" Mac your controls will be too small by 50% to display the text. This is why you should always prefer a layout manager to pixel coordinates.
You added two labels to the frame's content pane. These will both be in the same layer, so there are zero guarantees as to which will be painted on top of which. One day you will resieze the window, or un-minimise it or something and the background label will be in front of the button.

If you want to use an image JLabel for a background you need to use a JLayeredPane to control the z-order, and a proper layout manager to handle screen differences. Then it works very well.

The alternative is to subclass JPanel and override its paintComponent to draw the background. This also works very well.

The choice is yours!

This article has been dead for over six months. Start a new discussion instead.