简体   繁体   English

如何在JPanel中居中对齐背景图像

[英]How to center align background image in JPanel

I wanted to add background image to my JFrame . 我想将背景图片添加到我的JFrame
Background image means I can later add Components on the JFrame or JPanel 背景图像意味着我以后可以在JFrameJPanel上添加组件
Although I coudn't find how to add background image to a JFrame , 虽然我找不到如何将背景图像添加到JFrame
I found out how to add background image to a JPanel from here: 我从这里找到了如何将背景图像添加到JPanel
How to set background image in Java? 如何在Java中设置背景图像?

This solved my problem, but now since my JFrame is resizable I want to keep the image in center. 这解决了我的问题,但是现在因为我的JFrame可以调整大小,所以我希望将图像保持在中心位置。
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 . 任何人都可以说如何将图像对齐到JPanel中心。
As g.drawImage(img, 0, 0, null); as g.drawImage(img, 0, 0, null); provides x=0 and y=0 提供x = 0和y = 0
Also if there is a method to add background image to a JFrame then I would like to know. 此外,如果有一种方法将背景图像添加到JFrame我想知道。
Thanks. 谢谢。

Assuming a suitable image , you can center it like this: 假设一个合适的image ,你可以像这样对中:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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