Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>Here is a way to 'cheat'. All the parsing is done by the <code>ScriptEngine</code>, we just need to assemble the parts of the expression.</p> <p><img src="https://i.stack.imgur.com/OE2LU.png" alt="ScriptEngine Calculator"></p> <pre><code>import java.awt.*; import java.awt.event.*; import javax.swing.*; import javax.script.*; class ScriptEngineCalculations { public static void main(String[] args) { final ScriptEngine engine = new ScriptEngineManager(). getEngineByExtension( "js" ); String[] ops = {"+", "-", "*", "/"}; JPanel gui = new JPanel(new BorderLayout(2,2)); JPanel labels = new JPanel(new GridLayout(0,1)); gui.add(labels, BorderLayout.WEST); labels.add(new JLabel("a")); labels.add(new JLabel("operand")); labels.add(new JLabel("b")); labels.add(new JLabel("=")); JPanel controls = new JPanel(new GridLayout(0,1)); gui.add(controls, BorderLayout.CENTER); final JTextField a = new JTextField(10); controls.add(a); final JComboBox operand = new JComboBox(ops); controls.add(operand); final JTextField b = new JTextField(10); controls.add(b); final JTextField output = new JTextField(10); controls.add(output); ActionListener al = new ActionListener(){ public void actionPerformed(ActionEvent ae) { String expression = a.getText() + operand.getSelectedItem() + b.getText(); try { Object result = engine.eval(expression); if (result==null) { output.setText( "Output was 'null'" ); } else { output.setText( result.toString() ); } } catch(ScriptException se) { output.setText( se.getMessage() ); } } }; // do the calculation on event. operand.addActionListener(al); a.addActionListener(al); b.addActionListener(al); JOptionPane.showMessageDialog(null, gui); } } </code></pre> <h2>See Also</h2> <ul> <li>The <a href="http://download.oracle.com/javase/6/docs/api/javax/script/package-summary.html" rel="nofollow noreferrer"><code>javax.script</code> package</a></li> <li>The <a href="http://download.oracle.com/javase/6/docs/api/javax/script/ScriptEngine.html" rel="nofollow noreferrer"><code>ScriptEngine</code></a></li> <li>My <a href="http://pscode.org/jse.html" rel="nofollow noreferrer"><code>ScriptEngine</code> demo.</a> for exploring the capabilities of the JS engine.</li> </ul>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. VO
      singulars
      1. This table or related slice is empty.
    2. VO
      singulars
      1. This table or related slice is empty.
    3. VO
      singulars
      1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload