删除gridBagLayout中组件之间的间隙

时间:2014-05-23 06:11:18

标签: java swing gridbaglayout

这是我的班级:

public class Main extends JFrame{
private Container container;
private GridBagConstraints cons;
private JPanel panelDisplay;
private int curX = 0, curY = 0;

public Main() {
    initComp();
}

public static void main(String[] args) {

    SwingUtilities.invokeLater(new Runnable() {
        @Override
        public void run() {
            Main ex = new Main();
            ex.setVisible(true);
        }
    });
}

private void initComp()
{
    container = this.getContentPane();
    container.setLayout(new GridBagLayout());
    cons = new GridBagConstraints();

    cons.gridx = 0;
    cons.gridy = 0;
    container.add(new PanelNot(), cons);


    panelDisplay = new JPanel();
    panelDisplay.setBackground(Color.blue);
    panelDisplay.setPreferredSize(new Dimension(600, 400));
    panelDisplay.setLayout(new GridBagLayout());
    cons.gridx = 1;
    cons.gridy = 0;
    container.add(panelDisplay, cons);

    for (int i = 0; i < 15; i++) // display 15 components
    {            
        displayNot(); 
    }    


    this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); //setting the default close operation of JFrame
    this.pack();        
    this.setResizable(false);
    this.setLocationRelativeTo(null);
    this.setVisible(true);

}

private void displayNot()
{
    setLocGrid();
    panelDisplay.add(new Not1(), cons);
}

private void setLocGrid()
{
    if(curX==11) // maximum component to be display in 1 row is 11
    {
        curY += 1;
        curX = 0;
    }

    cons.gridx = curX;
    cons.gridy = curY;
    cons.anchor = GridBagConstraints.FIRST_LINE_START;
    cons.weightx = 1.0;
    cons.weighty = 1.0;

    curX += 1;
}

}

这是输出:enter image description here

忽略左侧面板。我的问题出现在右侧面板中,即一个组件(组件:Not1)与另一个组件之间存在间隙。我已经将每个组件的首选大小设置为x = 20和y = 30,正如您在每个组件的背景中所看到的那样,颜色为灰色。所以我的问题是,如何让差距消失?

更新:我的期望: enter image description here

1 个答案:

答案 0 :(得分:2)

首先摆脱cons.weightxcons.weightx

private void setLocGrid() {
    if (curX == 11) // maximum component to be display in 1 row is 11
    {
        curY += 1;
        curX = 0;
    }

    cons.gridx = curX;
    cons.gridy = curY;
    cons.anchor = GridBagConstraints.FIRST_LINE_START;
    //cons.weightx = 1.0;
    //cons.weighty = 1.0;

    curX += 1;
}

这会让你感觉像......

Example 01

现在,你需要一种可以将组件推到顶部/左侧位置的填充物,例如......

for (int i = 0; i < 15; i++) // display 15 components
{
    displayNot();
}

cons.gridy++;
cons.gridx = 12; // Based on you conditions in setLocGrid
cons.weightx = 1;
cons.weighty = 1;
JPanel filler = new JPanel();
filler.setOpaque(false);
panelDisplay.add(filler, cons);

这会给你类似......

Example 2

相关问题