griddbaglayout位置组件到中心



我使用griddbaglayout面板,我有一个标签调用show_date_info,我想把它放在第3行(gridy=2)的中间,但它出现在最左边。或者我必须通过设置标签的gridx来实现。谢谢。

    setLayout(new GridBagLayout());
    c.anchor = GridBagConstraints.NORTHEAST;
    c.weighty = 0;
    c.weightx = 1;
    c.insets = new Insets(10,0,0,0);  
    c.gridx = 5;      
    c.gridy = 0;   
    c.gridwidth = 1;        
    add(Logoutbtn, c);
    c = new GridBagConstraints();
    c.weighty = 1;
    c.weightx = 0.1;
    c.insets = new Insets(80,180,0,0);  
    c.gridx = 1;   
    c.gridy = 1;        
    c.gridwidth = 1;        
    add(startdatelabel, c);
    c = new GridBagConstraints();
    c.fill = GridBagConstraints.HORIZONTAL;
    c.weighty = 1;
    c.weightx = 1;
    c.insets = new Insets(80,0,0,80);  
    c.gridx = 2;   
    c.gridy = 1;        
    c.gridwidth = 1;        
    add(picker1, c);
    c = new GridBagConstraints();
    c.weighty = 1;
    c.weightx = 0.1;
    c.insets = new Insets(80,80,0,0);  
    c.gridx = 4;   
    c.gridy = 1;        
    c.gridwidth = 1;        
    add(enddatelabel, c);
    c.fill = GridBagConstraints.HORIZONTAL;
    c.weighty = 1;
    c.weightx = 1;
    c.insets = new Insets(80,0,0,180);  
    c.gridx = 5;   
    c.gridy = 1;        
    c.gridwidth = 1;        
    add(picker2, c);
    c = new GridBagConstraints();
    c.anchor = GridBagConstraints.CENTER;
    c.fill = GridBagConstraints.REMAINDER;
    c.insets = new Insets(-80,0,0,0);   
    c.gridy = 2;        
    //c.gridwidth = 1;        
    add(show_date_info, c);
    c = new GridBagConstraints();
    c.fill = GridBagConstraints.HORIZONTAL;
    c.weighty = 1;
    c.weightx = 1;
    c.insets = new Insets(0,20,0,20);  
    c.gridx = 0;   
    c.gridy = 3;        
    c.gridwidth = 7;         
    add(sp,c);
    c.fill = GridBagConstraints.NONE;
    c.insets = new Insets(-100,10,0,10);  
    c.gridx = 5;   
    c.gridy = 4;        
    c.gridwidth = 1;         
    add(confirmbtn,c);

不需要重新创建GridBagConstraints的对象。只需创建一个对象并使用它。

Make sure

c.fill = GridBagConstraints.HORIZONTAL;
c.weightx = 1; // 100%
c.gridy = 2 // 3rd row
c.gridwidth = max_number_of_columns;

使用JLabel(text,horizontalAlignement)

例如

new JLabel("In center",SwingConstants.CENTER) // to keep label in center

最新更新