FileDocCategorySizeDatePackage
Calculator.javaAPI DocExample2638Mon May 01 14:41:58 BST 2000None

Calculator

public class Calculator extends JPanel implements ActionListener

Fields Summary
GridBagConstraints
gbc
JTextField
theDisplay
Constructors Summary
public Calculator()


      
    gbc.weightx = 1.0;  gbc.weighty = 1.0;
    gbc.fill = GridBagConstraints.BOTH;
    ContainerListener listener = new ContainerAdapter(  ) {
      public void componentAdded(ContainerEvent e) {
        Component comp = e.getChild(  );
        if (comp instanceof JButton)
          ((JButton)comp).addActionListener(Calculator.this);
      }
    };
    addContainerListener(listener);
    gbc.gridwidth = 4;
    addGB(this, theDisplay, 0, 0);
    // make the top row
    JPanel topRow = new JPanel(  );
    topRow.addContainerListener(listener);
    gbc.gridwidth = 1;
    gbc.weightx = 1.0;
    addGB(topRow, new JButton("C"), 0, 0);
    gbc.weightx = 0.33;
    addGB(topRow, new JButton("%"), 1, 0);
    gbc.weightx = 1.0;
    addGB(topRow, new JButton("+"), 2, 0 );
    gbc.gridwidth = 4;
    addGB(this, topRow, 0, 1);
    gbc.weightx = 1.0;  gbc.gridwidth = 1;
    // make the digits
    for(int j=0; j<3; j++)
        for(int i=0; i<3; i++)
            addGB(this, new JButton("" + ((2-j)*3+i+1) ), i, j+2);
    // -, x, and divide
    addGB(this, new JButton("-"), 3, 2);
    addGB(this, new JButton("x"), 3, 3);
    addGB(this, new JButton("\u00F7"), 3, 4);
    // make the bottom row
    JPanel bottomRow = new JPanel(  );
    bottomRow.addContainerListener(listener);
    gbc.weightx = 1.0;
    addGB(bottomRow, new JButton("0"), 0, 0);
    gbc.weightx = 0.33;
    addGB(bottomRow, new JButton("."), 1, 0);
    gbc.weightx = 1.0;
    addGB(bottomRow, new JButton("="), 2, 0);
    gbc.gridwidth = 4;
    addGB(this, bottomRow, 0, 5);
  
Methods Summary
public voidactionPerformed(java.awt.event.ActionEvent e)

    if (e.getActionCommand(  ).equals("C"))
      theDisplay.setText("");
    else
      theDisplay.setText(theDisplay.getText(  )
                         + e.getActionCommand(  ));
  
voidaddGB(java.awt.Container cont, java.awt.Component comp, int x, int y)

    if ((cont.getLayout(  ) instanceof GridBagLayout) == false)
      cont.setLayout(new GridBagLayout(  ));
    gbc.gridx = x; gbc.gridy = y;
    cont.add(comp, gbc);
  
public static voidmain(java.lang.String[] args)

    JFrame f = new JFrame("Calculator");
    f.addWindowListener(new WindowAdapter(  ) {
      public void windowClosing(WindowEvent e) { System.exit(0); }
    });
    f.setSize(200, 250);
    f.setLocation(200, 200);
    f.setContentPane(new Calculator(  ));
    f.setVisible(true);