2015-04-20 110 views
0

當我使用下面的代碼,使使用GridBagLayout的一個JFrame,這是輸出: OutputGridBagLayout的網格寬度

我想前三排所有的按鈕具有相等的寬度,但他們都沒有。 我也希望第四行按鈕都具有相同的寬度。 我該怎麼做?
下面是代碼:

public Test() { 
    setTitle("Calculator"); 
    setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); 

    JMenuBar menu = new JMenuBar(); 
    setJMenuBar(menu); 

    setLayout(new GridBagLayout()); 
    GridBagConstraints c = new GridBagConstraints(); 
    field = new JTextField(20); 
    field.setFont(new Font("Cambria Math", Font.PLAIN, 32)); 
    field.setEditable(false); 
    updateDisplay(); 
    c.fill = GridBagConstraints.HORIZONTAL; 
    //c.insets = new Insets(9,9,9,9); 
    c.gridx = 0; 
    c.gridy = 0; 
    c.gridwidth = 24; 
    c.gridheight = 2; 
    add(field, c); 


    // sin, cos, tan 
    c.weightx = 0; 
    c.gridwidth = 4; 
    c.gridheight = 1; 
    c.gridx = 0; 
    c.weightx = 0; 
    c.gridy = 2; 
    add(createButton("sin"), c); 
    c.gridx = 4; 
    add(createButton("cos"), c); 
    c.gridx = 8; 
    add(createButton("tan"), c); 
    // cot, sec, csc 
    c.gridx = 0; 
    c.gridy = 3; 
    add(createButton("cot"), c); 
    c.gridx = 4; 
    add(createButton("sec"), c); 
    c.gridx = 8; 
    add(createButton("csc"), c); 

    // asin, acos, atan 
    c.gridx = 0; 
    c.gridy = 4; 
    add(createButton("asin"), c); 
    c.gridx = 4; 
    add(createButton("acos"), c); 
    c.gridx = 8; 
    add(createButton("atan"), c); 

    // atan2, acot, asec, acsc 
    c.gridy = 5; 
    c.gridwidth = 3; 
    c.weightx = 0; 
    c.gridx = 0; 
    add(createButton("atan2"), c); 
    c.gridx = 3; 
    add(createButton("acot"), c); 
    c.gridx = 6; 
    add(createButton("asec"), c); 
    c.gridx = 9; 
    add(createButton("acsc"), c); 

    pack(); 
    setVisible(true); 
} 
public JButton createButton(String name) { 
    JButton button = new JButton(name); 
    button.setActionCommand(name); 
    button.addActionListener(this); 
    button.setFont(new Font("Dialog", Font.PLAIN, 25)); 
    return button; 
} 

回答

2

我不認爲你可以使用GridBagLayout的這一點。

改爲使用GridLayout(0,1)創建主面板;

然後使用GridLayout(1,0)爲前3個按鈕創建第二個面板,並將此面板添加到第一個面板。

重複其他三行。