user3883840
user3883840

Reputation: 17

gridbaglayout position component to centre

I am using GridBagLayout for a panel, I have a label call show_date_info, i want to place it to the middle of row 3(gridy=2), but it appear in leftmost side. Or I have to achieve this by setting gridx of the label . Thanks.

    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);

Upvotes: 0

Views: 89

Answers (1)

Braj
Braj

Reputation: 46841

There is no need to create different object of GridBagConstraints. Just create single object and use it.

Make sure

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

Use JLabel(text,horizontalAlignement)

For example

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

Upvotes: 1

Related Questions