Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
216 views
in Technique[技术] by (71.8m points)

java - 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?
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...