简体   繁体   中英

Java : JPanel GridBagLayout issue

I'm making a program in which JPanel has two components JTextField and JLabel .And that JPanel using GridBadLayout in it.And i make a method for GridBagConstraints which add components in it.But that method does not Work with JPanel instance.But Working With JFrame .I want to fix this method with JPanel but don't know how to do it.
Code:

public class A extends JFrame {

    private final GridBagLayout layout;

    private final GridBagConstraints gbc;

    private JPanel p;
    private JLabel label1;
    private JTextField field1;

    public A() {

        super("Frame");

        layout = new GridBagLayout();
        gbc = new GridBagConstraints();
        p = new JPanel();
        p.setLayout(layout);
        gbc.gridy = 0;
        label1 = new JLabel("Enter Name");
        p.addConstraints(label1);

        gbc.gridx = 1;
        field1 = new JTextField(15);

        setSize(300, 200);
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        setLocationRelativeTo(null);
        setVisible(true);
    }

    // Method for GridBag Component Constraints
    private void addConstraints(Component com) {

        layout.setConstraints(com, gbc);
        add(com);

    }

Main Method

public class MainMethod {

    public static void main(String[] args) {

        A frame = new A();

    }
   }

add(com); adds the component to 'this', which is the JFrame, not the JPanel. Also, there's already an addConstraints method provided in Java, add(Component comp, Object constraints) .

Instead of using your addConstraints method, you could try this:

p.add(label1, gbc);

Next to that I'm missing a this.add(p); .

Edit:

If you want to just call addConstraints(Component comp) update the method to this:

// Method for GridBag Component Constraints
private void addConstraints(Component com) {
    p.add(com, gbc);
}

This way, the constructor can look like the following:

public A() {
    super("Frame");

    p = new JPanel();
    this.add(p);
    p.setLayout(new GridBagLayout());
    gbc = new GridBagConstraints();

    gbc.gridy = 0;
    label1 = new JLabel("Enter Name");
    addConstraints(label1);

    gbc.gridx = 1;
    field1 = new JTextField(15);
    addConstraints(field1);

    setSize(300, 200);
    setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    setLocationRelativeTo(null);
    setVisible(true);
}

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