GridBag约束仅通过类的构造函数添加,但不添加方法

时间:2016-01-11 04:50:08

标签: java swing gridbaglayout

好的,我有3种方法可以添加2个面板和1个按钮,同时还有它的网格约束。但是,当我在类的构造函数中调用3个方法时,它不会应用任何约束。

如果我将约束代码放在构造函数中而不是方法调用中,它能够添加组件并应用约束。我不知道为什么。是不是可以使用方法添加组件和约束并将其放在构造函数中?

这不起作用(不会按x和y排列组件):

package HomeTab;

import java.awt.Color;
import java.awt.Dimension;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import javax.swing.BorderFactory;
import javax.swing.JButton;
import javax.swing.JPanel;
import javax.swing.border.Border;

public class HomeTopPanel extends JPanel {

private final JButton myAccountButton = new JButton("My Account");
private final JPanel leftPanel = new JPanel(new GridBagLayout());
private final JPanel rightPanel = new JPanel(new GridBagLayout());
private final Border leftPanelLineBorder = BorderFactory.createLineBorder(Color.BLACK, 2);
private final Border rightPanelLineBorder = BorderFactory.createLineBorder(Color.BLACK, 2);
GridBagConstraints gbc = new GridBagConstraints();

//CONSTRUCTOR
public HomeTopPanel(){
    //METHOD CALLS
    constructMyAccountButton();
    constructPanels();
    setLeftRightPanelBorders();
    setLayout(new GridBagLayout());   
}

public final void constructMyAccountButton(){
    gbc.gridx = 1; gbc.gridy = 0; 
        this.add(myAccountButton,gbc);
}

public final void constructPanels(){
    leftPanel.setPreferredSize(new Dimension(250, 300));
    gbc.gridx = 0; gbc.gridy = 0; 
        this.add(leftPanel,gbc);

    rightPanel.setPreferredSize(new Dimension(300, 500));    
    gbc.gridx = 2; gbc.gridy = 0; 
        this.add(rightPanel,gbc);
}

private void setLeftRightPanelBorders(){
    leftPanel.setBorder(leftPanelLineBorder);
    rightPanel.setBorder(rightPanelLineBorder);
    this.setBorder(leftPanelLineBorder);
}
}

但是如果我在构造函数中放置组件的gridx和gridy位置,那就可以了。我想使用方法来完成它,而不是将约束放在构造函数中。

限制不适用的输出:

enter image description here

这是有效的:

public HomeTopPanel(){
    //METHOD CALLS
    setLeftRightPanelBorders();
    setLayout(new GridBagLayout());

    gbc.gridx = 1; gbc.gridy = 0; 
        this.add(myAccountButton,gbc);
    leftPanel.setPreferredSize(new Dimension(250, 300));
    gbc.gridx = 0; gbc.gridy = 0; 
        this.add(leftPanel,gbc);
    rightPanel.setPreferredSize(new Dimension(300, 500));    
    gbc.gridx = 2; gbc.gridy = 0; 
        this.add(rightPanel,gbc);
}

所需输出/正确输出:

enter image description here

先谢谢了。基本上,我的问题是如何在构造函数中使用方法/方法调用来应用约束并添加面板和按钮。

1 个答案:

答案 0 :(得分:2)

在尝试添加组件之前调用setLayout(new GridBagLayout());。默认布局管理器FlowLayout

忽略了约束
public HomeTopPanel(){
    //METHOD CALLS
    setLayout(new GridBagLayout());   
    constructMyAccountButton();
    constructPanels();
    setLeftRightPanelBorders();
}