2013-04-18 49 views
1

我对GridBagLayout发生了定位问题: 我尝试在中间(顶部)放置一个标签,但使用我的代码(出于我没有看到的原因),我已经: enter image description here使用GridBagLayout定位

我想标签测试是在我的窗口顶部和中心。有人能向我解释这种糟糕的定位原因吗?

我的程序:

public class Accueil extends JFrame { 

    private JPanel home = new JPanel(); 
    private GridBagConstraints grille = new GridBagConstraints(); 
    private JLabel title = new JLabel("Test"); 

    public Accueil() { 
     home.setLayout(new GridLayout()); 
     init_grille(); 
     init_title(); 

     this.add(home); 
     this.setSize(600,600); 
     this.setTitle("Test One"); 
     this.setLocationRelativeTo(null); 
     this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); 
     this.setVisible(true); 

    } 

    private void init_grille() { 
     grille.fill = GridBagConstraints.BOTH; 
     grille.weightx = 2; 
     grille.weighty = 5; 
     grille.ipady=grille.anchor=GridBagConstraints.CENTER;; 

    } 

    private void init_title() { 
     grille.fill = GridBagConstraints.HORIZONTAL; 
     grille.gridx = 0; 
     grille.gridy = 0; 
     home.add(title,grille); 
    } 

    public static void main(String [] args) { 
     new Accueil(); 
    } 
} 
+5

您没有使用GridBagLayout,而是使用GridLayout。 –

+0

如果你想使用GridLayout,你需要改变你的标签 –

回答

1

这不会帮助:

home.setLayout(new GridLayout()); 

你可能想:

home.setLayout(new GridBagLayout()); 

而且,这些变化应该工作:

private void init_title() { 
     grille.fill = GridBagConstraints.NONE; 
     grille.gridx = 0; 
     grille.gridy = 0; 
     grille.anchor = GridBagConstraints.NORTH; 
     home.add(title,grille); 
    } 
+0

GridBagLayout和GridLayout之间,哪个是最好的?我的意思是“最好的”在不同的角色的安置意义上 – afk

+1

没有最好的。当你需要一个简单的网格时,GridLayout最适合并且更易于使用。当你需要更复杂的东西时,GridLayout无法做到,而GridBagLayout可以做到,但代价更高。 –

+0

+1给JB。由于我们不知道最终目标是什么组件或您希望放置哪些组件,因此建议首选的LayoutManager只是猜测。 – splungebob