Skip to content
TheChatArchiveThe Chat Archive
gpt-3.5-turbo-0301· openaiHugging Face Suzhen/CodeChat

javafx 选择文件

  1. User

    javafx 选择文件

  2. Assistant

    可以使用JavaFX中的FileChooser类来选择文件。

    示例代码:

    FileChooser fileChooser = new FileChooser();
    fileChooser.setTitle("选择文件"); // 设置标题
    fileChooser.setInitialDirectory(new File(System.getProperty("user.home"))); // 设置初始目录
    File selectedFile = fileChooser.showOpenDialog(stage); // 打开文件选择器,返回选中的文件
    if (selectedFile != null) {
        // 文件被选中
    } else {
        // 用户取消了操作
    }
    

    以上代码中,FileChooser类有以下常用方法:

    • setTitle(String title):设置文件选择器的标题。
    • setInitialDirectory(File directory):设置初始目录。
    • showOpenDialog(Window owner):打开文件选择器并等待用户选择文件。返回选中的文件,如果用户取消了操作则返回null。
    • showSaveDialog(Window owner):打开文件选择器并等待用户选择保存位置。返回用户指定的文件,如果用户取消了操作则返回null。

    注意需要导入javafx.stage.FileChooser和java.io.File两个类。

Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.