如何计算两个整数值的结果,但从java中的jComboBox获取加法或乘法运算符 [英] how to compute the result of two integer values but get the additive or multiplicative operator from a jComboBox in java
问题描述
假设我有整数变量a,b和c。
assume i have integer variables a,b and c.
c = a + b; or c = a - b; or c = a / b; or c = a * b;
如您所见,计算运算符需要在运行时动态传递。所以我有一个jComboBox的运算符,所以用户将从jcomboBox中选择+, - ,*或/。
As you can see, the computation operator needs to be passed dynamically at run time. So i have a jComboBox of operators, so a user will select either a +, -, * or / from the jcomboBox.
我如何获得jCombobox selectedItem(可以是/,*, - 或+)并使用它来获取c的值。
how do i get the jCombobox selectedItem(which will be either /, *, -, or + ) and use it in getting the value of c.
例如。如果用户选择 *,则表达式应为c = a * b 如果用户选择了 +,那么表达式应为c = a + b 。
Eg. if the user selects *, then the expression should be c = a * b else if the user selected say +, then the expression should be c = a + b.
推荐答案
这是一种'欺骗'的方法。所有的解析都是由 ScriptEngine
完成的,我们只需要汇总表达式的各个部分。
Here is a way to 'cheat'. All the parsing is done by the ScriptEngine
, we just need to assemble the parts of the expression.
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);
}
}
参见
-
javax.script
package -
ScriptEngine
- 我的
ScriptEngine
演示。探索JS引擎的功能。 - The
javax.script
package - The
ScriptEngine
- My
ScriptEngine
demo. for exploring the capabilities of the JS engine.
See Also
这篇关于如何计算两个整数值的结果,但从java中的jComboBox获取加法或乘法运算符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!