简体   繁体   中英

Positioning with GridBagLayout

I've a positioning problem with the GridBagLayout : I try to place in center (at the top) a label but with my code (for a reason which I didn't see), I've this : 在此处输入图片说明

I want that the label Test are at the top of my window and in center. Someone can explain me the reason of this bad positionnement ?

My program :

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

This won't help:

home.setLayout(new GridLayout());

You probably want:

home.setLayout(new GridBagLayout());

Also, these changes should work:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM