Search code examples
javaswingcalculator

Having hard time making equals button to occupy 2 rows in 1 column


JButton btnEq = new JButton("=");
btnEq.setBackground(babyBlue); //to set color of equals btn

my code so far is just adding the button for equal I tried using getcontentpane still not working or I just don't know how to properly use it.enter image description here


Solution

  • You are using GridLayout to arrange your buttons. GridLayout does not support stretching one component over several rows (or columns). You can

    • use a LayoutManager that supports stretching components over multiple rows/columns restructure
    • your component hierarchy to use multiple containers with different layout managers

    to achieve the desired result.

    One solution using the JDK's GridBagLayout might be

        JPanel p2 = new JPanel(new GridBagLayout());
        ... // background, border, etc.
    
        GridBagConstraints gbc = new GridBagConstraints();
        gbc.anchor = GridBagConstraints.CENTER;
        gbc.fill = GridBagConstraints.BOTH;
        gbc.weightx = 1;
        gbc.weighty = 1;
    
        gbc.gridx = 0;
        gbc.gridy = 0;
        p2.add(pOnOff, gbc);
        ++gbc.gridx;
        p2.add(btnClr, gbc);
        ++gbc.gridx;
        p2.add(btnDel, gbc);
        ++gbc.gridx;
        p2.add(btnDiv, gbc);
    
        gbc.gridx = 0;
        ++gbc.gridy;
        p2.add(btnSqrt, gbc);
        ++gbc.gridx;
        p2.add(btnSq, gbc);
        ++gbc.gridx;
        p2.add(btnInv, gbc);
        ++gbc.gridx;
        p2.add(btnSub, gbc);
    
        gbc.gridx = 0;
        ++gbc.gridy;
        p2.add(btn7, gbc);
        ++gbc.gridx;
        p2.add(btn8, gbc);
        ++gbc.gridx;
        p2.add(btn9, gbc);
        ++gbc.gridx;
        p2.add(btnMul, gbc);
    
        gbc.gridx = 0;
        ++gbc.gridy;
        p2.add(btn4, gbc);
        ++gbc.gridx;
        p2.add(btn5, gbc);
        ++gbc.gridx;
        p2.add(btn6, gbc);
        ++gbc.gridx;
        p2.add(btnAdd, gbc);
    
        gbc.gridx = 0;
        ++gbc.gridy;
        p2.add(btn1, gbc);
        ++gbc.gridx;
        p2.add(btn2, gbc);
        ++gbc.gridx;
        p2.add(btn3, gbc);
        ++gbc.gridx;
        gbc.gridheight = 2; // <- stretch over two rows
        p2.add(btnEq, gbc);
    
        gbc.gridx = 0;
        ++gbc.gridy;
        gbc.gridheight = 1; // <- reset vertical stretch
        p2.add(btn0, gbc);
        ++gbc.gridx;
        p2.add(btndash, gbc);
        ++gbc.gridx;
        p2.add(btndot, gbc);
    

    Disclaimer: GridBagLayout is not well-liked and most people prefer third-party layout managers like MigLayout. This sample code uses GridBagLayout because it comes with the JDK and does not require additional libraries.