[英]Background image JFrame with content
I have a JFrame
with BorderLayout
, there are panels on all sides (North, East ,...). 我有一个带有
BorderLayout
的JFrame
,四面都有面板(北,东,......)。 In the panels there are labels and buttons mostly. 在面板中主要有标签和按钮。
Now I want the frame to have a background image, some research told me that i had to change the content pane of my frame. 现在我希望框架有一个背景图像,一些研究告诉我,我必须更改框架的内容窗格。
When I try this however, the content gets put in the background and isn't visible. 但是,当我尝试这样做时,内容将被放入后台并且不可见。 Also, I don't know how to resize the image if the frame is resized.
另外,如果调整帧大小,我不知道如何调整图像大小。
Is there an easy fix for this or will I have to rework most of my code? 有没有一个简单的解决方案或我将不得不重做我的大部分代码?
put JPanel
(or JComponent
) with background Image to the BorderLayout.CENTER
, then this JPanel
fills whole JFrame
area, rest of yout JComponents
put to this JPanel
将带有背景图像的
JPanel
(或JComponent
)放到BorderLayout.CENTER
,然后这个JPanel
填充整个JFrame
区域,其余的JComponents
放到这个JPanel
there are Jpanels on all sides (North, East ,...). In the Jpanels there are Jlabels and Jbuttons mostly.
these JComponents
covered all available Rectangle
for JFrame
, then Background Image
(from my 1st point) never will be dispalyed, because these JComponents
are on_top JFrame
and could be hide this Image
as well, 这些
JComponents
覆盖了JFrame
所有可用Rectangle
,然后Background Image
(从我的第一点开始)永远不会被显示出来,因为这些JComponents
是on_top JFrame
并且可以隐藏这个Image
,
add JPanel with Background Image
(from my 1st point), then put there another JPanel(s)
with JPanel#setOpaque(false);
添加
JPanel with Background Image
(从我的第一点开始),然后将另一个JPanel(s)
到JPanel#setOpaque(false);
, then this JPanel
will be transparent, notice JPanel
has implemented by default FlowLayout
,那么这个
JPanel
将是透明的,请注意JPanel
默认使用FlowLayout
实现
frame.getContentPane().add(new JPanel() {
public void paintComponent(Graphics g) {
g.drawImage(img, 0, 0, this.getWidth(), this.getHeight());
}
});
This example will get you started. 这个例子可以帮助你入门。 Use it like any JPanel.
像任何JPanel一样使用它。
public class JPanelWithBackground extends JPanel {
Image imageOrg = null;
Image image = null;
{
addComponentListener(new ComponentAdapter() {
public void componentResized(ComponentEvent e) {
int w = JPanelWithBackground.this.getWidth();
int h = JPanelWithBackground.this.getHeight();
image = w>0&&h>0?imageOrg.getScaledInstance(w,h,
java.awt.Image.SCALE_SMOOTH):imageOrg;
JPanelWithBackground.this.repaint();
}
});
}
public JPanelWithBackground(Image i) {
imageOrg=i;
image=i;
setOpaque(false);
}
public void paint(Graphics g) {
if (image!=null) g.drawImage(image, 0, 0, null);
super.paint(g);
}
}
Usage Example: 用法示例:
Image image = your image
JFrame f = new JFrame("");
JPanel j = new JPanelWithBackground(image);
j.setLayout(new FlowLayout());
j.add(new JButton("YoYo"));
j.add(new JButton("MaMa"));
f.add(j);
f.setVisible(true);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.