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);
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With