亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

單擊按鈕時 JavaFX 在新線程上運行任務

單擊按鈕時 JavaFX 在新線程上運行任務

BIG陽 2023-10-12 16:49:18
我試圖在 JavaFX 中單擊按鈕時檢索 XLS 文件并將其加載到 TableView 中。我正在使用 Task 類和 ExecutorService 來啟動新線程。我需要閱讀器類可重用,但 FileChooser 沒有顯示。這是我嘗試編寫一些并發代碼。我想知道我做錯了什么以及如何改進我的代碼,因為一切都是事件驅動的?控制器類代碼public void retrieveCustomersFromXLS() {        try {            loader.setOnSucceeded(workerStateEvent -> {                File file = null;                try {                    file = loader.get();                } catch (Exception e) {                    e.printStackTrace();                }                if (file != null && file.exists()) {                    reader.setWorkingFile(file);                    executor.submit(reader);                }            });            reader.setOnSucceeded(workerStateEvent1 -> {                Object[][] XLSFile = new Object[0][];                try {                    XLSFile = reader.get();                } catch (Exception e) {                    e.printStackTrace();                }                if (XLSFile != null) {                    tableInterface.setEntries(XLSFile);                    tableInterface.setEntryType("customers");                    executor.submit(tableInterface);                }            });            executor.submit(loader);        } catch (Exception e) {            e.printStackTrace();        }    }
查看完整描述

1 回答

?
江戶川亂折騰

TA貢獻1851條經驗 獲得超5個贊

您必須調用JavaFX 應用程序線程FileChooser#showXXXDialog上的方法。如果您發現任務失敗,您將看到一條消息,說明您嘗試在錯誤的線程上執行操作。此外,您不需要后臺任務來提示用戶輸入文件。IllegalStateException


Task下面是提示用戶輸入文本文件、讀取 a 中的文本文件并將結果放入 a 中的示例ListView。


App.java


package com.example;


import java.io.IOException;

import javafx.application.Application;

import javafx.fxml.FXMLLoader;

import javafx.scene.Scene;

import javafx.stage.Stage;


public class App extends Application {


  @Override

  public void start(Stage primaryStage) throws IOException {

    Scene scene = new Scene(FXMLLoader.load(getClass().getResource("/App.fxml")));

    primaryStage.setScene(scene);

    primaryStage.setTitle("FileChooser Example");

    primaryStage.show();

  }


}

應用程序.fxml


<?xml version="1.0" encoding="UTF-8"?>


<?import javafx.geometry.Insets?>

<?import javafx.scene.control.Button?>

<?import javafx.scene.control.ListView?>

<?import javafx.scene.control.Separator?>

<?import javafx.scene.layout.VBox?>


<VBox xmlns="http://javafx.com/javafx/13" xmlns:fx="http://javafx.com/fxml/1" spacing="5" prefWidth="600"

      prefHeight="400" alignment="CENTER" fx:controller="com.example.Controller">

    <padding>

        <Insets topRightBottomLeft="5"/>

    </padding>

    <Button text="Open File..." onAction="#handleOpenFile"/>

    <Separator/>

    <ListView fx:id="listView" VBox.vgrow="ALWAYS"/>

</VBox>

Controller.java


package com.example;


import java.io.File;

import java.nio.file.Files;

import java.nio.file.Path;

import java.util.List;

import java.util.Objects;

import java.util.concurrent.Executor;

import java.util.concurrent.Executors;

import javafx.collections.FXCollections;

import javafx.concurrent.Task;

import javafx.event.ActionEvent;

import javafx.fxml.FXML;

import javafx.scene.control.ListView;

import javafx.stage.FileChooser;

import javafx.stage.FileChooser.ExtensionFilter;


public class Controller {


  private final Executor executor = Executors.newSingleThreadExecutor(r -> {

    Thread t = new Thread(r, "controller-thread");

    t.setDaemon(true);

    return t;

  });


  @FXML private ListView<String> listView;


  @FXML

  private void handleOpenFile(ActionEvent event) {

    event.consume();


    FileChooser chooser = new FileChooser();

    chooser.getExtensionFilters()

        .add(new ExtensionFilter("Text Files", "*.txt", "*.json", "*.xml", "*.html", "*.java"));


    File file = chooser.showOpenDialog(listView.getScene().getWindow());

    if (file != null) {

      ReadFileTask task = new ReadFileTask(file.toPath());

      task.setOnSucceeded(wse -> listView.setItems(FXCollections.observableList(task.getValue())));

      task.setOnFailed(wse -> task.getException().printStackTrace());

      executor.execute(task);

    }

  }


  private static class ReadFileTask extends Task<List<String>> {


    private final Path file;


    private ReadFileTask(Path file) {

      this.file = Objects.requireNonNull(file);

    }


    @Override

    protected List<String> call() throws Exception {

      return Files.readAllLines(file);

    }


  }


}



查看完整回答
反對 回復 2023-10-12
  • 1 回答
  • 0 關注
  • 89 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號