我如何在 java gui 中调整背景图像的大小?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/10107752/
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
How do i have a background image resize in a java gui?
提问by PulsePanda
So im making a gui, and i have a background image for it. i dont know how to make it set as the background, so any help with that would be good. an explination would also be good. also, after we get that image as a background, how do we get the image resize to the size of the window. such as image.setSize(frame.getHeight(), frame.getWidth());
but i dont know if that would work. the image name is ABC0001.jpg and the frame name is frame. thanks!
所以我正在制作一个gui,我有一个背景图片。我不知道如何将其设置为背景,因此对此有任何帮助都会很好。一个解释也很好。此外,在我们将该图像作为背景后,我们如何将图像调整为窗口大小。例如,image.setSize(frame.getHeight(), frame.getWidth());
但我不知道这是否可行。图像名称为 ABC0001.jpg,框架名称为 frame。谢谢!
回答by ControlAltDel
To get the image to resize, you can either use
要调整图像大小,您可以使用
public void paintComponent(Graphics g) {
g.drawImage(img, 0, 0, getWidth(), getHeight(), this); // draw the image
}
or you can use a componentlistener, implemented like:
或者您可以使用组件侦听器,实现如下:
final Image img = ...;
ComponentListener cl = new ComponentAdapter() {
public void componentResized(ComponentEvent ce) {
Component c = ce.getComponent();
img = im1.getScaledInstance(c.getWidth(), c.getHeight(), Image.SCALE_SMOOTH);
}
};
Image quality will degrade over time with the second solution, so it is recommended that you keep the original and the copy separate.
使用第二种解决方案,图像质量会随着时间的推移而降低,因此建议您将原件和副本分开。
回答by John Snow
Create a class the extends JPanel. Have that class load the image by overriding paintComponent
创建一个扩展 JPanel 的类。让该类通过覆盖paintComponent加载图像
class BackgroundPanel extends JPanel
{
Image img;
public BackgroundPanel()
{
// Read the image and place it in the variable img so it can be used in paintComponent
img = Toolkit.getDefaultToolkit().createImage("ABC0001.jpg");
}
public void paintComponent(Graphics g)
{
g.drawImage(img, 0, 0, null); // draw the image
}
}
Now that you have this class, simply add this to your JFrame (or whereever you want the background).
现在您有了这个类,只需将它添加到您的 JFrame(或任何您想要背景的地方)。
//create refrence if you want to add stuff ontop of the panel
private BackgroundPanel backGroundPanel;
//constructor
add(backGroundPanel, BorderLayout.CENTER);
The size of the background will fill the entire frame so no need to scale it unless you want it smaller
背景的大小将填满整个框架,因此除非您希望它更小,否则无需缩放它