2012-03-22 229 views
3

我有一個JFrameBorderLayout,有面板(北,東,...)。在面板中大多數都有標籤和按鈕。背景圖片JFrame內容

現在我想要框架有一個背景圖像,一些研究告訴我,我不得不改變我的框架的內容窗格。

但是,當我嘗試這個,但內容被放在後臺,不可見。此外,我不知道如何調整圖像的大小,如果框架的大小。

有沒有一個簡單的解決方案,或將我不得不重新我的大部分代碼?

回答

4
  1. JPanel(或JComponent)與背景圖像的BorderLayout.CENTER,那麼這JPanel填滿整個JFrame區,YOUT JComponents放的休息,這JPanel

  2. there are Jpanels on all sides (North, East ,...). In the Jpanels there are Jlabels and Jbuttons mostly.

    這些JComponents覆蓋所有可用RectangleJFrame,然後Background Image(從我的第一點)永遠不會顯示,因爲這些JComponents是on_top JFrame和可能隱藏這個Image爲好,

  3. 添加JPanel with Background Image(從我的第一個點),然後把有另一種JPanel(s)JPanel#setOpaque(false);,那麼這JPanel將是透明的,通知JPanel已經默認FlowLayout實施

+1

'的GridLayout()'和'的CENTER''BorderLayout'工作非常類似。 – trashgod 2012-03-22 05:10:47

1
frame.getContentPane().add(new JPanel() { 

     public void paintComponent(Graphics g) { 
      g.drawImage(img, 0, 0, this.getWidth(), this.getHeight()); 
     } 
}); 
+0

要小心:a)只有圖像在任何地方都不透明時,這是有效的覆蓋。 b)添加到contentPane不符合添加下面所有內容的要求:-) – kleopatra 2012-03-22 11:58:59

0

這個例子將讓你開始。像任何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); 
+3

-1用於覆蓋paint(而不是paintComponent) – kleopatra 2012-03-22 11:55:16