2013-01-08 45 views
1

的寬度,請看看下面的代碼的JPanel:無法獲取的JPanel

import java.awt.*; 
import java.awt.event.*; 
import javax.swing.*; 

public class TestForm extends JFrame 
{ 
    private JLabel firstLabel, secondLabel; 

    private JTextField firstTxt, secondTxt; 

    private GridBagLayout mainLayout = new GridBagLayout(); 
    private GridBagConstraints mainCons = new GridBagConstraints(); 
    private JPanel centerPanel; 

     public TestForm() 
     { 
      this.setLayout(mainLayout); 
     //Declaring instance variables 
     firstLabel = new JLabel("First: "); 
     secondLabel = new JLabel("Second: "); 

     firstTxt = new JTextField(7); 
     secondTxt = new JTextField(7); 


     mainCons.anchor = GridBagConstraints.WEST; 
     mainCons.weightx = 1; 
     mainCons.gridy = 2; 
     mainCons.gridx = 1; 
     mainCons.insets = new Insets(15, 0, 0, 0); 
     this.add(createCenterPanel(), mainCons); 

     System.out.println("Center Panel Width: "+centerPanel.getWidth());   
     this.setTitle("The Test Form"); 
     this.pack(); 
     this.setLocationRelativeTo(null); 
     this.setVisible(true); 
     this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); 


    } 

    private JPanel createCenterPanel() 
    { 
     centerPanel = new JPanel(); 

     GridBagLayout gbl = new GridBagLayout(); 
     GridBagConstraints gbc = new GridBagConstraints(); 

     centerPanel.setLayout(gbl); 

     gbc.gridx = 1; 
     gbc.gridy = 1; 
     gbc.fill = GridBagConstraints.BOTH; 
     gbc.insets = new Insets(15,0,0,0); 
     centerPanel.add(firstLabel,gbc); 

     gbc.gridx = 2; 
     gbc.gridy = 1; 
     gbc.fill = GridBagConstraints.BOTH; 
     gbc.insets = new Insets(15,0,0,0); 
     centerPanel.add(firstTxt,gbc); 

     gbc.gridx = 3; 
     gbc.gridy = 1; 
     gbc.fill = GridBagConstraints.BOTH; 
     gbc.insets = new Insets(15,10,0,0); 
     centerPanel.add(secondLabel,gbc); 

     gbc.gridx = 4; 
     gbc.gridy = 1; 
     gbc.fill = GridBagConstraints.BOTH; 
     gbc.insets = new Insets(15,-10,0,0); 
     centerPanel.add(secondTxt,gbc); 


     centerPanel.setBorder(BorderFactory.createTitledBorder("The Testing Form")); 
     centerPanel.setPreferredSize(centerPanel.getPreferredSize()); 
     centerPanel.validate(); 

     System.out.println("Width is: "+centerPanel.getWidth()); 
     System.out.println("Width is: "+centerPanel.getHeight()); 

     return centerPanel; 

    } 


    public static void main(String[]args) 
    { 
     try 
     { 
      UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName()); 
      new TestForm(); 
     } 
     catch(Exception e) 
     { 
      e.printStackTrace(); 
     } 
    } 
} 

我試圖讓centerPanel的寬度在兩個地方。但在這兩種情況下,我都會得到0作爲答案!我必須以某種方式獲得寬度和高度,因爲southPanel(不包括在這裏)將使用這些值,有些降低到高度。請幫忙!

+0

中有什麼'southPanel',使它可以設置相對於其他一些隨機組件的大小(除了更少的高度)? –

回答

4

在調用pack()setSize()之前,寬度爲0。你可以得到的寬度和使用它後pack()呼叫

定義自己的LayoutManager其使用寬度爲另一個佈局部分的高度(southPanel)

+0

+1,但是第二。選項是 - 或者一次在屏幕上可見 – mKorbel

+0

非常感謝您的幫助!對此,我真的非常感激 :) –