开发者

JPanel with image background

开发者 https://www.devze.com 2023-01-22 18:44 出处:网络
How to put image background on JPANEL? JPanel pDraw = new JPanel(new GridLayout(ROWS,COLS,2,2)开发者_如何学Go);

How to put image background on JPANEL?

JPanel pDraw = new JPanel(new GridLayout(ROWS,COLS,2,2)开发者_如何学Go); 
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?


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 );
}


Here's an explanation.

0

精彩评论

暂无评论...
验证码 换一张
取 消