首页 > 解决方案 > 连接新设备时如何自动重新加载 ChoiceBox?

问题描述

我是 JavaFX 的新手,我正在尝试在连接闪存卡等新设备时更新 ChoiceBox。我使用周期为 500 毫秒的 ScheduleService 来执行此操作。每 500 毫秒后,我得到一个可移动设备列表并将它们添加到 ObservableList:

@Override
public void initialize(URL url, ResourceBundle resourceBundle) {
    ScheduledService<List<String>> service = getListOfDevices();
    service.setPeriod(Duration.millis(500));
    service.start();
    service.setOnSucceeded(e -> {
        Platform.runLater(() -> flashCardObservableList.setAll(service.getLastValue()));

    });

    nckCardList.setItems(flashCardObservableList);
}

private ScheduledService<List<String>> getListOfDevices() {
    return new ScheduledService<List<String>>() {
        @Override
        protected Task<List<String>> createTask() {
            return new Task<List<String>>() {
                @Override
                protected List<String> call() throws Exception {
                    String result = usb.GetDriveInfo();
                    List<FlashCard.DriveInfo> drives;
                    List<String> diskLetters = new ArrayList<>();
                    if (result.isEmpty() || result == null) return diskLetters;
                    drives = FlashCard.deserialize(result);
                    for (FlashCard.DriveInfo d : drives) {
                        diskLetters.add(d.getFlashName());
                    }
                    return diskLetters;
                }
            };
        }
    };
}

为了获取我使用 DLL 的设备列表,在这个 DLL 中我使用方法 DriveInfo.GetDrives()。但是每 500 毫秒我的选择框就会更新一次,我无法选择任何东西。我希望它在“设备”字段中的程序“Rufus”中看起来像。最好的方法是什么?

标签: javamultithreadingjavafx

解决方案


推荐阅读