如何将所有内容对齐框架的中心?在我的示例代码中,JLabel不占用与按钮相同的空间百分比,它大约有10%的标签和90%的按钮。我如何才能使它们都具有相同的空间?这是我的代码:

class Animation extends JPanel {
    JLabel lab = new JLabel("A");
    JButton but = new JButton("BUTTTTTTTOOOOOOOOOOOOON");
    GridBagConstraints c = new GridBagConstraints();
    public Animation(){
        setLayout(new GridBagLayout());
        c.gridx = 0 ;
        c.gridy = 0;
        add(lab,c);
        c.gridx = 1;
        add(but, c);


    }

    public static void main(String[] args) {
        JFrame fram = new JFrame();
        fram.add(new Animation());
        fram.pack();
        fram.setVisible(true);

    }
}

最佳答案

将它们中的两个放到2x1 GridLayout中-在每个单元上强制使用相同的尺寸。

public Animation()
{
    setLayout(new GridLayout());
    add(lab);
    add(but);
}

07-25 23:57
查看更多