Java 如何将Jspinner与双变量相乘?
我正在尝试制作一个程序来模拟物品的结帐。我想把物品的数量乘以单位成本,得到总成本,但我很难想出一个方法来做到这一点 这是我的密码Java 如何将Jspinner与双变量相乘?,java,Java,我正在尝试制作一个程序来模拟物品的结帐。我想把物品的数量乘以单位成本,得到总成本,但我很难想出一个方法来做到这一点 这是我的密码 JLabel amount0 = new JLabel("Amount"); JLabel unitcost0 =new JLabel("Unit Cost"); JLabel unitcost1 = new JLabel("$2.45"); JLabel unitcost2
JLabel amount0 = new JLabel("Amount");
JLabel unitcost0 =new JLabel("Unit Cost");
JLabel unitcost1 = new JLabel("$2.45");
JLabel unitcost2 = new JLabel("$79.99");
JLabel unitcost3 = new JLabel("$45.43");
JLabel unitcost4 = new JLabel("$3.00");
JLabel unitcost5 = new JLabel("$42.00");
JSpinner amount1= new JSpinner(new SpinnerNumberModel(0,0,50,1));
JSpinner amount2= new JSpinner(new SpinnerNumberModel(0,0,50,1));
JSpinner amount3 = new JSpinner(new SpinnerNumberModel(0,0,50,1));
JSpinner amount4= new JSpinner(new SpinnerNumberModel(0,0,50,1));
JSpinner amount5 = new JSpinner(new SpinnerNumberModel(0,0,50,1));
JLabel cost0 = new JLabel("Cost");
JLabel cost1 = new JLabel ( unitcost1* amount1);
非常感谢您的帮助。在Java中,您只能对数字执行数学运算,因此在您的情况下,您需要将数字存储为一个数字变量,就像一个
Double
:
Double price = 2.45;
然后,您可以在组件中使用该数字变量:
JLabel yourLabel = new JLabel("$" + price);
然后,要计算成本,需要获得jSpinner的数值:
int spinnerValue = yourSpinner.getValue();
并计算最终总数:
Double total = price * spinnerValue;
JLabel cost1 = new JLabel ("$" + total);
请注意,如果您希望在更改jSpinner时实时执行此操作,则需要在jSpinner上创建一个操作事件来更新值/标签,这是一个更大的主题,需要一个新问题,但下面是一个粗略的示例:
spinner.addChangeListener(new ChangeListener() {
public void stateChanged(ChangeEvent e) {
int spinnerValue = ((JSpinner)e.getSource()).getValue();
Double total = price * spinnerValue;
yourLabel.setText("$" + total);
}
});