Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JPanel with image background

How to put image background on JPANEL?

JPanel pDraw = new JPanel(new GridLayout(ROWS,COLS,2,2)); 
pDraw.setPreferredSize(new Dimension(600,600)); //size of the JPanel
pDraw.setBackground(Color.RED); //How can I change the background from red color to image?
like image 387
Jessy Avatar asked Oct 29 '10 11:10

Jessy


1 Answers

It is probably easiest to load the Image into an ImageIcon and display it in a JLabel, however:
To directly 'draw' the image to the JPanel, override the JPanel's paintComponent(Graphics) method to something like the following:

public void paintComponent(Graphics page)
{
    super.paintComponent(page);
    page.drawImage(img, 0, 0, null);
}

where img is an Image (possibly loaded through the ImageIO.read() call).

Graphics#drawImage is a heavily overloaded command which will allow you to be highly specific in how, how much, and where you paint the image to the component.

You can also get 'fancy' and scale the image to your pleasing using the Image#getScaledInstance method. This will take a -1 for either the width or the height parameter in order to keep the aspect ratio of the image the same.

Putting it in a more fancy way:

public void paintComponent(Graphics page)
{
    super.paintComponent(page);

    int h = img.getHeight(null);
    int w = img.getWidth(null);

    // Scale Horizontally:
    if ( w > this.getWidth() )
    {
        img = img.getScaledInstance( getWidth(), -1, Image.SCALE_DEFAULT );
        h = img.getHeight(null);
    }

    // Scale Vertically:
    if ( h > this.getHeight() )
    {
        img = img.getScaledInstance( -1, getHeight(), Image.SCALE_DEFAULT );
    }

    // Center Images
    int x = (getWidth() - img.getWidth(null)) / 2;
    int y = (getHeight() - img.getHeight(null)) / 2;

    // Draw it
    page.drawImage( img, x, y, null );
}
like image 93
Reese Moore Avatar answered Sep 23 '22 14:09

Reese Moore