A Calculator with Panels

Here's the source code that produces a calculator applet, using only a GridLayout and nested panels.

import java.applet.*;
import java.awt.*;


public class Calculator extends Applet {

  private TextField screen;

  public void init () {
 
    this.setLayout(new GridLayout(3, 1, 3, 3));
    Panel A1 = new Panel();
    this.add(A1);
    Panel A2 = new Panel();
    this.add(A2);
    Panel A3 = new Panel();
    this.add(A3);
    A1.setLayout(new GridLayout(2, 1));
    screen = new TextField(12);
    A1.add(screen);
    Panel B1 = new Panel();
    B1.setLayout(new GridLayout(1, 4, 3, 3));
    B1.add(new Button("C"));
    B1.add(new Button("="));
    B1.add(new Button("/"));
    B1.add(new Button("*"));
    A1.add(B1);
    A2.setLayout(new GridLayout(2, 4, 3, 3));
    A2.add(new Button("7"));
    A2.add(new Button("8"));
    A2.add(new Button("9"));
    A2.add(new Button("-"));
    A2.add(new Button("4"));
    A2.add(new Button("5"));
    A2.add(new Button("6"));
    A2.add(new Button("+"));
    A3.setLayout(new GridLayout(1, 2, 3, 3));
    // 1, 2 and 0
    Panel B2 = new Panel();
    B2.setLayout(new GridLayout(2, 1, 3, 3));
    // 1 and 2
    Panel C1 = new Panel();
    C1.setLayout(new GridLayout(1, 2, 3, 3));
    C1.add(new Button("1"));
    C1.add(new Button("2"));
    B2.add(C1);
    B2.add(new Button("0"));
    // 3, . and =
    Panel B3 = new Panel();
    B3.setLayout(new GridLayout(1, 2, 3, 3));
    // 3 and .
    Panel C2 = new Panel();
    C2.setLayout(new GridLayout(2, 1, 3, 3));
    C2.add(new Button("3"));
    C2.add(new Button("."));
    B3.add(C2);
    B3.add(new Button("="));
    A3.add(B2);
    A3.add(B3);

  }

  public Insets getInsets() {
    return new Insets(5, 5, 5, 5);
  }

}

Previous | Next | Top | Cafe au Lait

Copyright 1997, 2002 Elliotte Rusty Harold
elharo@metalab.unc.edu
Last Modified November 1, 2002