views:

95

answers:

1

Can someone tell me the best way to use Grid layout to set the buttons of my Calculator

+1  A: 

This is almost too general a question to answer, you don't even make it clear what programming language you're talking about (JavaScript? Java? X.net?).

Let me give you an example using Java. The basic idea would be that you create one javax.swing.JButton (assuming that you're using Swing) for each button, then you think about the layout you'd like to achieve (obviously a grid), and add the buttons to the parent component. For instance, to mimick the layout of the GNOME calculator:

import java.awt.*;
import javax.swing.*;

/**
 * +----+----+----+----+
 * |Bksp| CE | Clr| +- |
 * +----+----+----+----+
 * | 7  | 8  | 9  | /  |
 * +----+----+----+----+
 * | 4  | 5  | 6  | *  |
 * +----+----+----+----+
 * | 1  | 2  | 3  | -  |
 * +----+----+----+----+
 * | 0  | .  | =  | +  |
 * +----+----+----+----+
 */
public class Calculator extends JPanel {
    public Calculator() {
        JButton bksp      = new JButton("Bksp");
        JButton ce        = new JButton("CE");
        JButton clr       = new JButton("Clr");
        JButton plusminus = new JButton("+-");
        JButton div       = new JButton("/");
        JButton mult      = new JButton("*");
        JButton minus     = new JButton("-");
        JButton plus      = new JButton("+");
        JButton equals    = new JButton("=");
        JButton dot       = new JButton(".");
        JButton[] digits = new JButton[10];
        for (int i = 0; i < digits.length; i++) {
            digits[i] = new JButton(String.valueOf(i));
        }

        /* do the layout */
        setLayout(new GridLayout(5, 4, 5, 5));
        add(bksp);
        add(ce);
        add(clr);
        add(plusminus);
        add(digits[7]);
        add(digits[8]);
        add(digits[9]);
        add(div);
        add(digits[4]);
        add(digits[5]);
        add(digits[6]);
        add(mult);
        add(digits[1]);
        add(digits[2]);
        add(digits[3]);
        add(minus);
        add(digits[0]);
        add(dot);
        add(equals);
        add(plus);
    }

    public static void main(String[] args) {
        Calculator calc = new Calculator();

        JFrame frame = new JFrame();
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.getContentPane().add(calc);

        frame.setSize(300, 300);
        frame.setVisible(true);
    }
}

With new GridLayout(5, 4, 5, 5) you're defining a 5x4 grid (5 rows, 4 columns) and an inter-cell spacing of 5 pixels, both horizontally and vertically. After that you just add the buttons in the correct order (left-to-right, top-to-bottom).

Thomas
In the question itself I have written it javascript being used.
Ravia