首页 文章

在GridBagLayout中展开JButton

提问于
浏览
0

如何在 GridBagLayout 中展开 JButton

我尝试将 GridBagConstraints 的权重设置为非零值:

gbc.weightx = gbc.weighty = 1.0;

但它只是扩展了按钮的宽度,我希望按钮也可以垂直扩展 .

这是我在网格中添加按钮的代码:

private void initGui(){
    setTitle("Calculator");
    setSize(400,500);
    var grid = new GridBagLayout();
    setLayout(grid);
    GridBagConstraints gridCon = new GridBagConstraints();
    gridCon.weightx = gridCon.weighty = 1.0;

    gridCon.gridy = 0;
    gridCon.gridx = 0;
    gridCon.gridwidth = 4;
    gridCon.fill = gridCon.HORIZONTAL;
    add(text,gridCon);

    gridCon.gridwidth = 1 ;

    String names[] = {"+","-","/","*","="};
    for(int i = 0;i < 5; i++){
        opeButtons[i] = new JButton(names[i]);
    }

    gridCon.gridx = 3;
    for( int y = 1; y < 6; y++ ){
        gridCon.gridy = y;
        add(opeButtons[y-1],gridCon);
    }

    for(int y = 2, i = 1; y < 5; y++ ){
        for(int x = 0 ; x < 3; x++,i++) {
            gridCon.gridx = x;
            gridCon.gridy = y;
            numButtons[i] = new JButton(Integer.toString(i));
            add(numButtons[i],gridCon);
        }
    }

    gridCon.gridx = 0;
    gridCon.gridy = 1;
    add(lb,gridCon);
    gridCon.gridx = 1;
    add(rb,gridCon);
    gridCon.gridx = 2;
    add(cb,gridCon);

    numButtons[0] = new JButton("0");
    gridCon.gridx = 0;
    gridCon.gridy = 5;
    gridCon.gridwidth = 2;
    add(numButtons[0],gridCon);

    gridCon.gridwidth = 1;
    gridCon.gridx = 2;
    add(decb,gridCon);
}

1 回答

  • 0

    更换

    gridCon.fill = gridCon.HORIZONTAL;
    

    gridCon.fill = GridBagConstraints.BOTH;
    

相关问题