简体   繁体   中英

How to center align background image in JPanel

I wanted to add background image to my JFrame .
Background image means I can later add Components on the JFrame or JPanel
Although I coudn't find how to add background image to a JFrame ,
I found out how to add background image to a JPanel from here:
How to set background image in Java?

This solved my problem, but now since my JFrame is resizable I want to keep the image in center.
The code I found uses this method

public void paintComponent(Graphics g) { //Draw the previously loaded image to Component.  
    g.drawImage(img, 0, 0, null);   //Draw image
}  

Can anyone say how to align the image to center of the JPanel .
As g.drawImage(img, 0, 0, null); provides x=0 and y=0
Also if there is a method to add background image to a JFrame then I would like to know.
Thanks.

Assuming a suitable image , you can center it like this:

@Override
public void paintComponent(Graphics g) {
    super.paintComponent(g);
    Graphics2D g2d = (Graphics2D) g;
    int x = (this.getWidth() - image.getWidth(null)) / 2;
    int y = (this.getHeight() - image.getHeight(null)) / 2;
    g2d.drawImage(image, x, y, null);
}

If you want the other components to move with the background, you can alter the graphics context's affine transform to keep the image centered, as shown in this more complete example that includes rotation.

@Override
public void paintComponent(Graphics g) {
    super.paintComponent(g);
    Graphics2D g2d = (Graphics2D) g;
    g2d.translate(this.getWidth() / 2, this.getHeight() / 2);
    g2d.translate(-image.getWidth(null) / 2, -image.getHeight(null) / 2);
    g2d.drawImage(image, 0, 0, null);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM