/* * x1_skeleton.java code skeleton for simple calculator SJ 251007 * Requires Java 1.6 (for evaluating values). */ /* * PLACE YOUR SELF-EVALUATION HERE */ /* * Hints: * JTextComponent.setEditable() * Component.setFocusable() * KeyEvent.getKeyText(KeyEvent.getKeyCode()) * */ import java.awt.*; import java.awt.event.*; import javax.swing.*; import javax.script.*; import java.util.HashMap; import java.util.Scanner; import java.io.File; public class yourusername extends JFrame // uncomment following if you implement the interfaces // implements ActionListener, KeyListener { // String array for the buttons private static final String[][] bstrings = { {"+", "-", "*", "/"}, {"1", "2", "3", "("}, {"4", "5", "6", ")"}, {"7", "8", "9", "<-"}, {".", "0", "=", "C"} }; // used for evaluation private ScriptEngine scriptE; // used for tool tips private static HashMap tips = null; public yourusername() { if (tips == null) { tips = new HashMap(); // take calctips.txt from www-page readToolTips(tips, "calctips.txt"); } draw(); // initialize expression evaluator ScriptEngineManager mgr = new ScriptEngineManager(); scriptE = mgr.getEngineByExtension("js"); } /* * Draw the UI initially and bind actions to handlers. */ private void draw() { JFrame mainFrame = new JFrame("yourusername"); mainFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); // TODO //Display the window. mainFrame.pack(); mainFrame.setVisible(true); } // draw() // TODO /* * Evaluates an expression. * * @param buf the input expression * @return the result of the expression, or "error" */ private String evaluateExpression(String buf) { String res = ""; try { res = scriptE.eval(buf).toString(); } catch (ScriptException ex) { res = "error"; } return res; } // evaluateExpression() /* * Read tootips from a file to a {@linkplain java.util.HashMap java.util.HashMap}. * In case of error (e.g., wrong format in file), results empty or incomplete HashMap * * @param fileName name of the source file * @param tips the destination {@linkplain java.util.HashMap java.util.HashMap} */ private static void readToolTips(HashMap tips, String fileName) { try { Scanner in = new Scanner(new File(fileName)); while (in.hasNext()) { String key = in.next(); // read one token as key String val = in.nextLine(); // the rest is tooltip text tips.put(key, val); } } catch (Exception e) { } } // readToolTips() /* * Start the gui. */ public static void main(String[] args) { javax.swing.SwingUtilities.invokeLater(new Runnable() { public void run() { yourusername cgui = new yourusername(); } }); } // main() } // class yourusername