2012-12-01 95 views
2

我的目標是根據我的GridBagConstraints調整組件的大小,但由於某種原因,當我的小應用程序運行時,組件會顯示,但不會像我預期的那樣填充整個小應用程序。這裏是我的代碼:組件不會在小應用程序中調整大小

ServerPanel:

public class ServerPanel extends JPanel{ 
    public ServerPanel(){ 
    setLayout(new GridBagLayout()); //use gridbag layout 
    GridBagConstraints gbc = new GridBagConstraints(); 

    JButton reverse = new JButton("Reverse text"); 
    JButton send = new JButton("Send text"); 
    JButton clear = new JButton("Clear text"); 
    JTextField text = new JTextField("Test"); 
    JScrollPane scrollPane = new JScrollPane(text, ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS, ScrollPaneConstants.HORIZONTAL_SCROLLBAR_AS_NEEDED); 

    //Reverse button 
    gbc.gridx = 0; 
    gbc.gridy = 0; 
    gbc.fill = gbc.HORIZONTAL; 
    add(reverse, gbc); 

    //send button 
    gbc.gridy = 1; 
    add(send, gbc); 

    //clear button 
    gbc.gridy = 2; 
    add(clear,gbc); 

    //text field 
    gbc.gridy = 3; 
    gbc.ipadx = 20; 
    gbc.ipady = 20; 
    gbc.fill = gbc.BOTH; 
    add(scrollPane, gbc); 
    } 

} 

從ServerApplet相關代碼延伸JApplet的:

public void init(){ 
     //dim = getSize(); 
     //create the GUI in the EDT 
     SwingUtilities.invokeLater(new Runnable(){ 
     @Override 
     public void run(){ 
      //System.out.println(dim); 
      setLayout(new BorderLayout()); 
      add(new ServerPanel(), BorderLayout.CENTER); 

     } 
    }); 
} 

什麼情況是,合適的組件生成,並且面板在中心小程序,但它不會擴展以填充整個小程序。任何幫助表示讚賞。謝謝!

回答

3

當我看到這一點:

但由於某些原因,在運行小程序我時,組件出現,但像我預想的不填滿整個小程序....

與GridBagLayout一起使用時,我會查看GridBagConstraints上是否設置了weightx和weighty字段,因爲它們的缺省值爲0的症狀是這些組件都聚集在中心。

解決方案:在需要的地方和時間設置這些字段。如果一個組件應該在x方向上展開,那麼給它一個+ weightx,大概是1.0,同樣對於重量來說。

相關問題