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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/4533526/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-30 06:48:11  来源:igfitidea点击:

How to center align background image in JPanel

javaswingjframejpanelbackground-image

提问by Jaguar

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

我想将背景图片添加到我的JFrame.
背景图像意味着我以后可以在JFrame或上添加组件JPanel
虽然我找不到如何将背景图像添加到JFrame,但
JPanel从这里找到了如何将背景图像添加到:
如何在 Java 中设置背景图像?

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

这解决了我的问题,但现在由于我JFrame的可调整大小,我想将图像保持在中心。
我找到的代码使用这种方法

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 JFramethen I would like to know.
Thanks.

谁能说一下如何将图像与JPanel.
由于g.drawImage(img, 0, 0, null);提供 x=0 和 y=0
另外,如果有一种方法可以将背景图像添加到 aJFrame那么我想知道。
谢谢。

回答by trashgod

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