阿旭_
import java.awt.Rectangle;
import javax.script.ScriptEngineManager;
import javax.script.ScriptException;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTextField;
public class Test67 {
public static void main(String[] args) {
JFrame frame = new JFrame("计算任意公式");
JLabel mJLabel_1 = new JLabel("请输入要计算的公式,如:(3+2)*5");
mJLabel_1.setBounds(new Rectangle(18, 53, 250, 38));
final JLabel mJLabel_2 = new JLabel("");
mJLabel_2.setBounds(new Rectangle(18, 117, 250, 38));
final JTextField jf1 = new JTextField(20);
jf1.setBounds(new Rectangle(18, 91, 250, 25));
JButton jb = new JButton("确认");
jb.setBounds(new Rectangle(18, 107 * 2 - 53, 150, 38));
jb.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent e) {
double value = 0;
try {
value = (double) new ScriptEngineManager().getEngineByName("js").eval(jf1.getText());
mJLabel_2.setText("" + value);
} catch (ScriptException e1) {
e1.printStackTrace();
mJLabel_2.setText("请输入正确公式");
}
}
});
JPanel p = new JPanel(); // 建立一个面板
p.add(mJLabel_1, null);
p.add(mJLabel_2, null);
p.add(jf1);
p.setLayout(null);
p.add(jb);
frame.add(p);// 将面板添加到窗口
frame.setSize(300, 300);// 设置窗口大小
frame.setAlwaysOnTop(true);// 设置窗口始终在最上层
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);// 设置默认的关闭操作,关闭窗口后退出程序
frame.setLocationRelativeTo(null);// 设置窗口居中
frame.setVisible(true);// 设置窗口可见,尽快调用paint()方法
frame.setResizable(false);
}
}
阿旭_
import javax.script.ScriptEngine;
import javax.script.ScriptEngineManager;
import javax.script.ScriptException;
import javax.swing.JOptionPane;
public class Test68 {
public static void main(String[] args) {
String str = (String) JOptionPane.showInputDialog(null, "请输入要计算的公式,如:(3+2)*5", "title", JOptionPane.PLAIN_MESSAGE, null, null, "");
try {
ScriptEngineManager mScriptEngineManager = new ScriptEngineManager();
ScriptEngine mScriptEngine = mScriptEngineManager.getEngineByName("js");
double value = (double) mScriptEngine.eval(str);
JOptionPane.showMessageDialog(null, "结果为:"+value, "标题",JOptionPane.PLAIN_MESSAGE);
} catch (ScriptException e1) {
e1.printStackTrace();
JOptionPane.showMessageDialog(null, "请输入正确公式", "标题",JOptionPane.ERROR_MESSAGE);
}
}
}