[英]Display an image with transparent background over the content of the JFrame
[英]Background image JFrame with content
我有一個帶有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_top JFrame
並且可以隱藏這個Image
,
添加JPanel with Background Image
(從我的第一點開始),然后將另一個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);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.