背景图像JFrame与内容
我有一个带BorderLayout
的JFrame
,四面都有面板(北,东,……)。 在面板中主要有标签和按钮。
现在我希望框架有一个背景图像,一些研究告诉我,我必须更改框架的内容窗格。
但是当我尝试这个时,内容会被放入后台并且不可见。 另外,如果调整帧大小,我不知道如何调整图像大小。
是否有一个简单的解决方案或我将不得不重做我的大部分代码?
-
将带有背景图像的
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.
这些
JComponents
覆盖了JFrame
所有可用Rectangle
,然后Background Image
(从我的第一点开始)永远不会被显示出来,因为这些JComponents
是on_topJFrame
并且可以隐藏这个Image
, -
JPanel with Background Image
添加JPanel with Background Image
(从我的第一点开始),然后使用JPanel#setOpaque(false);
另一个JPanel(s)
JPanel#setOpaque(false);
,那么这个JPanel
将是透明的,请注意JPanel
默认使用FlowLayout
实现
frame.getContentPane().add(new JPanel() { public void paintComponent(Graphics g) { g.drawImage(img, 0, 0, this.getWidth(), this.getHeight()); } });
这个例子可以帮助你入门。 像任何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); } }
用法示例:
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);