2013-03-10 50 views
4

爲什麼jPanel在啓動時會返回0的高度和寬度,以及如何在啓動時獲得正確的值。零寬度高度jPanel開始

import javax.swing.JPanel; 

class ZeroJPanel extends JPanel { 

    /** 
    * Creates new form ZeroJPanel 
    */ 
    ZeroJPanel() { 
     initComponents(); 

     System.out.println(this.getHeight()); 
    } 


    public static void main(String Args[]) { 
     new ZeroJPanel(); 
    } 

    /** 
    * This method is called from within the constructor to initialize the form. 
    * WARNING: Do NOT modify this code. The content of this method is always 
    * regenerated by the Form Editor. 
    */ 
    @SuppressWarnings("unchecked") 
    // <editor-fold defaultstate="collapsed" desc="Generated Code"> 
    private void initComponents() { 

     org.jdesktop.layout.GroupLayout layout = new org.jdesktop.layout.GroupLayout(this); 
     this.setLayout(layout); 
     layout.setHorizontalGroup(
      layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING) 
      .add(0, 400, Short.MAX_VALUE) 
     ); 
     layout.setVerticalGroup(
      layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING) 
      .add(0, 300, Short.MAX_VALUE) 
     ); 
    }// </editor-fold> 
    // Variables declaration - do not modify 
    // End of variables declaration 
} 
+2

面板在框架實現之前不會有大小,這意味着它已被打包或可見。你爲什麼在乎?讓佈局經理完成工作。 – camickr 2013-03-10 01:03:43

+0

因爲我概括了這個問題。 – BAR 2013-03-10 01:05:30

+1

您可以將「AncestorListener」添加到面板。然後當面板變得可見時,你可以得到它的實際尺寸。 – camickr 2013-03-10 01:10:56

回答

3

面板返回0, 0,因爲很簡單,這是默認值。

當您將面板添加到一個框架,並在框架上調用pack(),這將計算出正確的(首選)大小並進行設置。在此之前,您將無法找到尺寸,因爲它尚未計算。

爲什麼你需要這些值?如果您可以用更廣泛的術語解釋問題,我們可以幫助您。