UNB/ CS/ David Bremner/ teaching/ java/ RPNCalc4.java
import javax.swing.JLabel;
import javax.swing.JPanel;
import java.awt.BorderLayout;
import javax.swing.BoxLayout;
public class RPNCalc4 extends DBFrame implements KeyPadClient, 
                                                 HistoryPaneClient{

    private JLabel resultLabel=new JLabel("results");

    private PromptField input;
    private RPNStack2 stack=new RPNStack2();
    
    private HistoryPane results;

    private final String labels[][]=
            { {"7","8","9"}, 
              {"4","5","6"},
              {"1","2","3"},
              {"0",".", "Enter"},
              {"+","-","*"},
              {"/","clear","quit" }};

    public void mouseClickCallback(String text){
        input.setText(text);
    }

    public void keypressCallback(String text){
        if (text.equals("clear")){
            input.setText("");
            return;
        }
        if (text.equals("quit")){
            System.exit(0);
        }
            
        if ('0' <= text.charAt(0) && 
            text.charAt(0) <= '9' || text.charAt(0)=='.'){           
            input.setText(input.getText() + text);
        } else{
            process(text);
        }
    }

    private void process(String text){
        String result,operand;
        operand=input.getText();
        if (!operand.equals("")){
            try{ stack.push(operand); }
            catch (NumberFormatException e){
                results.addElement("Illegal number: "+operand);
                return;
            }
        }
        try {       
            if (!text.equals("Enter")){
                stack.process(text);
            }
            results.addElement(stack.top().toString());
        } 
        catch (EmptyStackException e){
            results.addElement("Stack Underflow");
        }
        catch (NumberFormatException e){
            results.addElement("Illegal number");
        }
        catch (DivideByZeroException e){
            results.addElement("Divide by zero");
        }


        input.setText("");
    }
    public RPNCalc4(){
        BoxLayout calcLayout=new BoxLayout(getContentPane(),BoxLayout.X_AXIS);
        getContentPane().setLayout(calcLayout);

        
        results=new HistoryPane("Illegal or missing number");
        results.addClient(this);

        JPanel rightGroup=new JPanel(new BorderLayout());
        rightGroup.add(resultLabel,"North");
        rightGroup.add(results,"Center");

        JPanel leftGroup=new JPanel();
        leftGroup.setLayout(new BoxLayout(leftGroup, BoxLayout.Y_AXIS));

        input=new PromptField("input",20);
        leftGroup.add(input);

        leftGroup.add(new KeyPad(labels,this));

        getContentPane().add(leftGroup);
        getContentPane().add(rightGroup);

        setTitle("RPN Calculator");
        pack();
        setVisible(true);
        
    }
    public static void main(String [] args){
        RPNCalc4 r=new RPNCalc4();
    }
}
//