2017-06-05 49 views
-1

我一直試圖調整我的顯示器我​​想要的方式,但它似乎並沒有工作。我想用GridBagLayout的做出這樣的事情:在Java中的GridBagLayout不會工作

I want to sort panels like thisenter image description here

香港專業教育學院發現了一段代碼,和編輯它:

public class GBLPanel extends JPanel 
{ 
    private static final long serialVersionUID = 1L; 

    GridBagConstraints gbc = new GridBagConstraints(); 

    public GBLPanel(Dimension appdim) 
    { 
     GridBagConstraints c = new GridBagConstraints(); 

     setLayout(new GridBagLayout()); 
     add(gbcComponent(0,0,2,1,0,0), gbc);    
     add(gbcComponent(0,1,1,1,0,50), gbc);    
     add(gbcComponent(1,1,1,1,0,50), gbc); 

    } 

    private JPanel gbcComponent(int x, int y, int w, int h, int ipadyx, int ipadyy){ 

     gbc.gridx = x; 
     gbc.gridy = y; 
     gbc.gridwidth = w; 
     gbc.gridheight = h; 

     gbc.weightx = 1.0; 
     gbc.weighty = 1.0; 

     gbc.ipadx=ipadyx; 
     gbc.ipady=ipadyy; 

     gbc.fill = GridBagConstraints.BOTH; 
     JPanel panel = new JPanel(); 
     JTextField text = new JTextField("(" + w + ", " + h + ")"); 
     panel.setBorder(new TitledBorder("(" + x + ", " + y + ")"));   
     panel.add(text); 
     return panel; 

    } 

} 

but it looks like this enter image description here

,我不能圖瞭解如何根據需要塑造它,任何人都可以提供幫助?非常感謝 !

回答

2

A BorderLayout可能會更容易爲您做到這一點。

但是,如果你想/需要使用GridBagLayout,你目前遇到的問題是,你將每個面板的x和y都設置爲weight,意味着它們全部均勻分佈。

嘗試改變他們反映做這樣的事情

public GBLPanel(Dimension appdim) 
{ 
    GridBagConstraints c = new GridBagConstraints(); 

    setLayout(new GridBagLayout()); 
    // Pass in weights also 
    add(gbcComponent(0,0,2,1,0,0, 1, 0.25), gbc); // 100% x and 25% y 
    add(gbcComponent(0,1,1,1,0,50, 0.25, 0.75), gbc); // 25% x and 75% y 
    add(gbcComponent(1,1,1,1,0,50, 0.75, 0.75), gbc); // 75% x and 75% y 

} 

private JPanel gbcComponent(int x, int y, int w, int h, int ipadyx, int ipadyy, double wx, double wy) 
{ 
    gbc.gridx = x; 
    gbc.gridy = y; 
    gbc.gridwidth = w; 
    gbc.gridheight = h; 

    gbc.weightx = wx; // Set to passed in values here 
    gbc.weighty = wy; 

    gbc.ipadx=ipadyx; 
    gbc.ipady=ipadyy; 

    gbc.fill = GridBagConstraints.BOTH; 
    JPanel panel = new JPanel(); 
    JTextField text = new JTextField("(" + w + ", " + h + ")"); 
    panel.setBorder(new TitledBorder("(" + x + ", " + y + ")")); 
    panel.add(text); 
    return panel; 

} 
+0

你想要的值非常感謝您的回答,Java的魔鬼,你幫了我很多。我實際上使用BorderLayout來製作第一張照片,但我最近開始學習Java,並且我不知道如何製作調整大小處理程序。而且我也在某處看過GridBagLayout是最靈活的,所以我想試試它。 – Milan