简体   繁体   中英

Set Coordinates using GridBagLayout

I've a problem with coordinates x and y. I use GridBagLayout gridx=0,gridy=0, but all components are aligned full center. I need to set align top-left 0,0 but my solution with use GridBagLayout doesn't work.

Now I show code and picture. Need align left. Default have center align, but need set top-left align for components, because I need paint two picture bottom JFrame.

import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.Insets;
import javax.swing.*;
public class Zobrazenie extends JPanel {
private static final long serialVersionUID = 1L;
    JButton b1,b2,b3,b4,b5;
    GridBagConstraints gbc = new GridBagConstraints();
    Zobrazenie()
    {
        setLayout(new GridBagLayout());
        gbc.insets=new Insets(10,10,10,10);

        gbc.gridx=0;
        gbc.gridy=0;
        gbc.anchor=GridBagConstraints.WEST;
        b1=new JButton("Button 1");
        add(b1,gbc);

        gbc.gridx=0;
        gbc.gridy=1;
        b2=new JButton("Button 2");
        add(b2,gbc);

        gbc.gridx=0;
        gbc.gridy=2;
        b3=new JButton("Button 3");
        add(b3,gbc);

        gbc.gridx=0;
        gbc.gridy=3;
        b4=new JButton("Button 4");
        add(b4,gbc);

        gbc.gridx=0;
        gbc.gridy=4;
        b5=new JButton("Button 5");
        add(b5,gbc);
    }
public static void main(String[] args)
{
    JFrame jf = new JFrame();
    Zobrazenie zb = new Zobrazenie();
    jf.setSize(400,300);
    jf.setTitle("Okno");
    jf.setLocationRelativeTo(null);
    jf.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    jf.add(zb);
    jf.setVisible(true);
}
}

And the picture: http://img14.imageshack.us/img14/7243/oknouw.jpg

anchor and fill only work if you specify weighx and/or weighty with a value greater than 0.

Now the question is how do you want extra space to be distributed.

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