2013-01-02 42 views
0

下面是一個簡單的Swing應用程序中,我嘗試了某些自定義techniques.The代碼如下: -在我的Swing應用程序清除一些疑問需要幫助

import java.awt.Dimension; 
import java.awt.FlowLayout; 
import java.awt.Graphics; 
import java.awt.image.BufferedImage; 
import java.io.File; 
import java.io.IOException; 

import javax.imageio.ImageIO; 
import javax.swing.Icon; 
import javax.swing.ImageIcon; 
import javax.swing.JFrame; 
import javax.swing.JLabel; 
import javax.swing.JPanel; 
import javax.swing.SwingUtilities; 


public class ThemeComponents extends JFrame{ 
    public static void main(String args[]) 
    { 
    SwingUtilities.invokeLater(new Runnable(){public void run(){new ThemeComponents();}}); 
    } 

    public ThemeComponents() 
    { 
    super("HACK 1:Creating Image Themed Components "); 
    setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); 
    setLayout(new FlowLayout()); 
    CustomPanel p1=new CustomPanel(); 
    p1.add(new CustomLabel()); 
    add(p1); 
    pack(); 
    setVisible(true); 
    } 
} 

class CustomPanel extends JPanel 
{ 
    BufferedImage img; 
    CustomPanel() 
    { 
    try 
    { 
     img=ImageIO.read(new File("src/background.jpg")); 
    } catch(IOException e){ 
     System.out.println("Error in loading background image "+e); 
    } 
    } 
    public void paintComponent(Graphics g) 
    { 
    g.drawImage(img,0,0,getWidth(),getHeight(),null); 
    } 
    public Dimension getPreferredSize() 
    { 
    return new Dimension(img.getWidth(),img.getHeight()); 
    } 
} 

class CustomLabel extends JLabel 
{ 
    ImageIcon img; 
    CustomLabel() 
    { 
    img=new ImageIcon("src/tornado.gif"); 


    setSize(img.getIconWidth(),getHeight()); 
    setIcon((Icon) img); 
    //setOpaque(false); 
    //setIconTextGap(0); 
    setLocation(10,10); 
    } 
} 

現在我以下的問題: -

1)當我設置佈局,我的主類爲null setLayout(null)ThemeComponents那麼爲什麼幀尺寸的縮小,只有標題欄爲空?我期望它採取的CustomPanel的大小,因爲我已經使用pack()的框架。(使用佈局,例如flowlayout,borderlayout可以產生正確的輸出)

2)正在使用getPreferredSize()更好地設置組件的大小而不是setPreferredSize()。實際上我沒有發現它們之間的任何區別。

回答

2
  1. 返回(0,0),因此你只會看到標題欄。 pack()驗證您的JFrame,然後設置JFrame的大小,內容窗格(即0,0)的首選大小,並添加所需的空間標題欄,菜單等......

  2. 最有可能您應該避免撥打setPreferredSize(),而不要撥打getPreferredSize()。調用setPreferredSize()會讓其他人修改該值的可能性。在這種情況下,這可能意味着首選尺寸不是組件的固有部分,因此您不需要撥打setPreferredSize()。雖然覆蓋getPreferredSize()可讓您完全控制,並將首選大小的結果作爲組件的固有部分。

  3. 您還應該在您的CustomPanel中調用super.paintComponent(g);

  4. 在你CustomLabel,它沒有任何意義,調用setLocation(父佈局將改變反正)

  5. 在你CustomLabel,這沒有任何意義之一:setSize(img.getIconWidth(),getHeight());因爲父佈局無論如何改變這些值(和順便說一句,getHeight()在這種情況下返回0)

0

的setLayout()用來設置你的窗口的佈局,對佈局click here 內容窗格使用BorderLayout的默認情況下,通過設置佈局爲空那裏只是 沒有佈局,所有你看到的是標題欄。

getPreferred()是用來獲取你給一個組件的首選大小,而集 用於設置首選大小:如果您使用null -layout,首選大小將p

+0

:是!但即使沒有佈局,面板應該在那裏,它必須給框架的大小 –