【问题标题】:How do I stop spinner valueFactory from adding values twice in javafx如何阻止微调器 valueFactory 在 javafx 中添加两次值
【发布时间】:2018-06-24 04:30:45
【问题描述】:

我在数据库上创建了两个表(产品记录和销售记录)。我正在尝试增加和减少价格文本文件中的价格值(通过产品数据库中的默认价格值),以便用户可以在微调器值(即数量值)增加或减少时获得总价格值.

因此,当在输入了 productID 的 productID textfiled 上单击 enter 键时,它会在 Product Records 表中设置为 true,并将 productname、price、quantity 设置为它们的 textfileds,并将数量值设置为 spinner textfiled。这是针对产品 ID 文本文件的 ActionEvent 的代码。 我已经在主类上创建了一个连接

private void ProCodeEnterKeyAction(){
    try {
        psta=s.connect.prepareStatement("select productname,price,AVAILABLEQTY from ProductRecords where productID=?");
        psta.setInt(1, Integer.parseInt(textfiledProCode.getText()));
        res=psta.executeQuery();

        if(res.next()){
            textfiledProName.setText(res.getString("productname"));
            textfiledPrice.setText(res.getInt("price")+"");

            tp=Integer.parseInt(textfiledPrice.getText());// to hold the default price value

            spinValue=new SpinnerValueFactory.IntegerSpinnerValueFactory(1,res.getInt("AVAILABLEQTY"));
            spin.setValueFactory(spinValue);

            spin.valueProperty().addListener(new ChangeListener<Integer>() {

                @Override
                public void changed(ObservableValue<? extends Integer> observable, Integer oldValue, Integer newValue) {
                    try {
                        if (newValue>oldValue) {
                            textfiledPrice.setText((Integer.parseInt(textfiledPrice.getText())+tp)+"");
                        }
                        else if(newValue<=res.getInt("AVAILABLEQTY")){
                            textfiledPrice.setText((Integer.parseInt(textfiledPrice.getText())-tp)+"");
                        }
                    } catch (Exception e) {e.printStackTrace();
                    }
                }
            });
        }
        else{
            al=new Alert(Alert.AlertType.ERROR);
            al.setTitle("Infomation");
            al.setContentText("Product Not Found");
            al.showAndWait();
            textfiledProCode.setText("");
            textfiledProName.setText("");
            textfiledPrice.setText("");
        }

    } catch (Exception e) {e.printStackTrace();
    }
}

当程序启动时,输入productID textfiled并按回车键,当微调器第一次增加/减少时输出所有值,它工作正常。但是,当我对另一个 productID 做同样的事情并开始增加/减少微调器时,它总是将价格值增加两倍。喜欢

1500+1500=3000 但我得到 1500+1500=4500。

当我打印出 oldValue 和 newValue 时,输出将是值的两倍

【问题讨论】:

  • 与您的问题无关:请学习 java 命名约定并遵守它们

标签: java database javafx spinner


【解决方案1】:

没有 MVCE 就不容易回答,但是根据您描述的情况和您显示的代码,您似乎忘记删除以前的侦听器。您应该将侦听器添加移到其他位置(例如,在带有 @FXML 注释的方法 public/private void initialize() 中),或者您应该在添加新的之前删除之前创建的 changeListener(实际上是相同的)。

【讨论】:

  • 谢谢。我看到了我的错误,您的解决方案有效
猜你喜欢
  • 2012-09-18
  • 2014-03-29
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2023-03-25
  • 1970-01-01
  • 2014-10-22
  • 1970-01-01
相关资源
最近更新 更多