A Calculator with Panels

Here's the source code that produces a calculator applet, using only a GridLayout and nested panels. Whether this is easier or harder than using a GridBagLayout is a personal preference.

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


public class Calculator extends Applet {

  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 insets() {
  
    return new Insets(5, 5, 5, 5);
  
  }

  /* Use 1.0 event handling since I need to run this
     inside today's web browsers. */
  public boolean action(Event e, Object arg) {
    if (e.target instanceof Button) {
      screen.setText((String) arg);
      return true;
    }
    return false;
  
  }

}

Previous | Next | Top
Last Modified November 11, 1997
Copyright 1997 Elliotte Rusty Harold
elharo@metalab.unc.edu