How to center background image alignment in JPanel

I wanted to add a background image to my JFrame.
A background image means that I can later add Components to JFrameor JPanel
Although I cannot find how to add a background image to JFrame,
I learned how to add a background image from JPanelhere:
How to set a background image in Java?

This solved my problem, but now, as my JFrameresize, I want to keep the image in the 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 tell how to align the image in the center JPanel.
Since it g.drawImage(img, 0, 0, null);provides x = 0 and y = 0
Also, if there is a way to add a background image to JFrame, then I would like to know.
Thank.

+5
source share
1 answer

Assuming a suitable one image, you can focus 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 other components to move with the background, you can modify the affine transformation of the graphics context to support centering the image, as shown in this more complete example . which includes a twist.

@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);
}
+10
source

All Articles