package freegraph; import java.awt.*; import java.awt.event.*; import java.applet.*; /** * ExpressionParsingApplet displays the RPN expression stack * generated from an infix expression entered by the user. */ public class ExpressionParsingApplet extends Applet implements ActionListener { TextField txtFunction; Button btnConvert; Panel pnlTop; List lstStack; /*** * Initialize the applet by setting up the GUI. This method calls the * internalInit() method to do the actual initialization. If any errors * occur, the stack trace is printed to System.err. */ public void init() { try { internalInit(); } catch (Exception e) { e.printStackTrace(); } } /*** * internally used method to setup the Applet's GUI. */ private void internalInit() throws Exception { setBackground(new Color(getParameterAsInt("bgcolor", 0xFFFFFF, 16))); txtFunction = new TextField(); btnConvert = new Button("Convert"); pnlTop = new Panel(); lstStack = new List(); pnlTop.setLayout(new BorderLayout()); pnlTop.add(txtFunction, BorderLayout.CENTER); pnlTop.add(btnConvert, BorderLayout.EAST); this.setLayout(new BorderLayout()); this.add(pnlTop, BorderLayout.NORTH); this.add(lstStack, BorderLayout.CENTER); btnConvert.addActionListener(this); txtFunction.addActionListener(this); txtFunction.requestFocus(); } public String getAppletInfo() { return "Expression Parsing Applet Information"; } /** * responds to action events from convert button of text field by parsing * the expression and displaying the RPN stack */ public void actionPerformed(ActionEvent e) { if (e.getSource() == btnConvert || e.getSource() == txtFunction) { lstStack.removeAll(); try { ExpressionStack expr = new ExpressionStack(txtFunction.getText()); while (expr.size() > 0) { lstStack.add(expr.pop().toString()); } } catch (Exception e2) { lstStack.add(e2.getMessage()); } } } /*** * returns the value of a parameter as a String. If the parameter * is not defined, def is returned. */ public String getParameter(String key, String def) { return (getParameter(key) != null ? getParameter(key) : def); } /*** * returns the value of a parameter as an int. If the parameter * is not defined, def is returned. The parameter is parsed to integer * using the default radix of 10 */ public int getParameterAsInt(String key, int def) { return getParameterAsInt(key, def, 10); } /*** * returns the value of a parameter as an int. If the parameter * is not defined, def is returned. The parameter is parsed to integer * using the provided radix */ public int getParameterAsInt(String key, int def, int radix) { try { return (getParameter(key) != null ? Integer.parseInt(getParameter(key), radix) : def); } catch (Exception e) { return def; } } }