简体   繁体   English

JavaFX - 自动增量 ID

[英]JavaFX - Auto increment ID

This is what I have这就是我所拥有的

public class AddNewCategoryController implements Initializable {

    @FXML
    private TextField name;

    @FXML
    private TextField description;

    @Override
    public void initialize(URL url, ResourceBundle resourceBundle) {
    }

    public void save(){
        final AtomicLong identifier = new AtomicLong(5);
        Long id = identifier.incrementAndGet();
        String catgoryName = name.getText();
        String categoryDescription = description.getText();

        Category category = new Category(id,catgoryName,categoryDescription);

        ReadingDataFromFiles.writeCategory(category);

    }
}

When the programs runs there's a screen to add a new category and the user has to write category's name and description but ID should be automatic and should be increased every time the user enters a new Category.当程序运行时,会出现一个添加新类别的屏幕,用户必须编写类别的名称和描述,但 ID 应该是自动的,并且应该在每次用户输入新类别时增加。 The way I've done it doesn't work as intended, it's increased only once but since initial value stays 5 it's always 6.我这样做的方式并没有按预期工作,它只增加了一次,但由于初始值保持为 5,它始终为 6。

Move this line:移动这一行:

final AtomicLong identifier = new AtomicLong(5);

… higher up, outside the method, to be a member field on the class. …更高,在方法之外,成为 class 上的成员字段。

In your existing code, each call to that save method is creating a new AtomicLong to replace the previous one.在您现有的代码中,对该save方法的每次调用都会创建一个新的AtomicLong来替换前一个。 So your counting cannot accumulate.所以你的计数不能累积。

Proper naming can help clarify.适当的命名可以帮助澄清。 That AtomicLong is not an “identifier”. AtomicLong不是“标识符”。 It is an “identifierGenerator”.它是一个“标识符生成器”。 Each number returned by its incrementAndGet method is the “identifier”. incrementAndGet方法返回的每个数字都是“标识符”。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM